Django,将已排除的属性添加到提交的模型窗体中 [英] Django, adding excluded properties to the submitted modelform
问题描述
create_date
和 created_by
字段。现在,当使用 save()
方法时,我得到Not Null错误,因为 created_by
是空的。 p> 我已经尝试在 save()
方法之前的表单中添加用户ID,如下所示: form.cleaned_data ['created_by'] = 1
和 form.cleaned_data ['created_by_id'] = 1
。但这些都不行。有人可以向我解释一下,如何将附加附加内容添加到提交的模型中,以便保存?
pre $
class Location(models.Model):
name = models.CharField(max_length = 100)
created_by = models.ForeignKey(User)
create_date = models.DateTimeField(auto_now = True)
class LocationForm(forms.ModelForm):
class Meta:
model = Location
exclude =('created_by' ,'create_date',)
您的表单中的 created_by
和 create_date
的字段,尝试通过 form.cleaned_data
没有任何意义。
这是你可以做的:
如果你有一个看法,你可以简单地使用 form.save(commit = False)
,然后设置 created_by
/ p>
def my_view(request):
如果request.method ==POST:
form = LocationForm(request.POST)
如果form.is_valid():
obj = form.save(commit = False)
obj.created_by = request.user
obj.save()
...
...
`
如果您使用管理员,可以覆盖 save_model()方法以获得所需的结果。
class LocationAdmin(admin.ModelAdmin):
def save_model(self,request,obj,form,change):
obj .created_by = request.user
obj.save()
I've a modelform and I excluded two fields, the create_date
and the created_by
fields. Now I get the "Not Null" error when using the save()
method because the created_by
is empty.
I've tried to add the user id to the form before the save()
method like this: form.cleaned_data['created_by'] = 1
and form.cleaned_data['created_by_id'] = 1
. But none of this works.
Can someone explain to me how I can 'add' additional stuff to the submitted modelform so that it will save?
class Location(models.Model):
name = models.CharField(max_length = 100)
created_by = models.ForeignKey(User)
create_date = models.DateTimeField(auto_now=True)
class LocationForm(forms.ModelForm):
class Meta:
model = Location
exclude = ('created_by', 'create_date', )
Since you have excluded the fields created_by
and create_date
in your form, trying to assign them through form.cleaned_data
does not make any sense.
Here is what you can do:
If you have a view, you can simply use form.save(commit=False)
and then set the value of created_by
def my_view(request):
if request.method == "POST":
form = LocationForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.created_by = request.user
obj.save()
...
...
`
If you are using the Admin, you can override the save_model() method to get the desired result.
class LocationAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.created_by = request.user
obj.save()
这篇关于Django,将已排除的属性添加到提交的模型窗体中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!