Django表单用户是' not-null'即使手动设置

时间:2017-04-18 15:43:54

标签: python django

为了便于使用,我的表单中的一个字段可以有多个foo,但每个foo应该/将在数据库中创建它自己的记录。我有一个ModelFormMyForm)来捕获为foo的每个实例重复的字段。

在我的views.py内,我为MyForm的每个实例复制foo。除了将登录用户设置为表单提交者的位之外,所有工作都正常。抛出以下错误:列中的空值" submitter_id"违反非空约束

models.py

class MyModel(models.Model):
  foo_bar = models.CharField(max_length=10)
  foo_baz = models.CharField(max_length=10)
  submitter = models.ForeignKey(User)

forms.py

class MyForm(forms.ModelForm):
  class Meta:
    Model = MyModel
    exclude = ['foo_bar','foo_baz','submitter']

views.py

注意:obj是一个字典,但很多foo已输入表单

my_form = MyForm(request.POST)
if my_form.is_valid():
  for k,v in obj:
    copy = MyForm(request.post)
    copy.save(commit=False)
    copy.foo_bar = k
    copy.foo_baz = v
    copy.submitter = request.user    # I have inspected this, and request.user is an instance of the User model
    copy.save()                      # <-- here is where I get the error above

2 个答案:

答案 0 :(得分:2)

您需要在模型实例上设置它,该实例从表单save返回。此外,由于某种原因,您在检查表单有效后重新实例化该表单;你不应该这样做。

if my_form.is_valid():
    instance = copy.save(commit=False)
    instance.submitter = request.user    # I have inspected this, and request.user is an instance of the User model
    instance.save()

(而不是弄乱包含表格副本的词典,你应该使用表格集。)

答案 1 :(得分:1)

尝试按以下方式设置

copy.instance.submitter = request.user