Django,将排除的属性添加到提交的模型表单中
我有一个模型表单,并且排除了两个字段:create_date
和 created_by
字段。现在,我在使用 save()
方法时收到“Not Null”错误,因为 created_by
为空。
我尝试在 save()
方法之前将用户 ID 添加到表单,如下所示: form.cleaned_data['created_by'] = 1
和 form .cleaned_data['created_by_id'] = 1
。但这些都不起作用。
有人可以向我解释如何向提交的模型表单“添加”额外的内容以便保存吗?
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', )
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', )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于您已在表单中排除了
created_by
和create_date
字段,因此尝试通过form.cleaned_data
分配它们没有任何意义。您可以执行以下操作:
如果您有视图,则只需使用
form.save(commit=False)
,然后设置created_by
的值`
如果您是使用管理员,您可以覆盖 save_model() 方法来获得所需的结果。
Since you have excluded the fields
created_by
andcreate_date
in your form, trying to assign them throughform.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 ofcreated_by
`
If you are using the Admin, you can override the save_model() method to get the desired result.
将用户作为参数传递给构造函数,然后使用它来设置模型实例的created_by字段:
Pass a user as a parameter to form constructor, then use it to set created_by field of a model instance:
正确的解决方案是将带有预填充字段的对象实例传递给模型表单的构造函数。这样,这些字段将在验证时填充。如果需要字段,则在
form.save()
之后赋值可能会导致验证错误。请注意,instance 是一个未保存的对象,因此在 form 保存它之前不会分配 id。
The correct solution is to pass an instance of the object with pre-filled fields to the model form's constructor. That way the fields will be populated at validation time. Assigning values after
form.save()
may result in validation errors if fields are required.Notice that instance is an unsaved object, so the id will not be assigned until form saves it.
一种方法是使用 form.save(commit=False) (doc)
这将返回模型类的对象实例,而不将其提交到数据库。
因此,您的处理可能如下所示:
One way to do this is by using form.save(commit=False) (doc)
That will return an object instance of the model class without committing it to the database.
So, your processing might look something like this: