smilebomb
smilebomb

Reputation: 5483

Django form User is 'not-null' even though it's manually set

For ease of use, one of the fields in my form can have multiple foos, but eachfoo should/will create it's own record in the database. I have a ModelForm (MyForm) that captures the fields that are repeated for each instance of foo.

Inside my views.py I copy MyForm for each instance of foo. All that is working, except for the bit where the logged in user is set as the submitter of the form. The following error is thrown: null value in column "submitter_id" violates not-null constraint.

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

Note: obj is a dictionary of however many foos were entered into the form

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

Upvotes: 0

Views: 58

Answers (2)

NS0
NS0

Reputation: 6096

Try setting it in the following way

copy.instance.submitter = request.user

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599600

You need to set it on the model instance, which is returned from the form save. Also, for some reason you are re-instantiating the form after checking it is valid; you should not do that.

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()

(Instead of messing about with dicts containing copies of forms, you should use formsets.)

Upvotes: 2

Related Questions