0

I have a model with a ForeignKey to User, and it needs to have a value. How do I automatically add the User value when submitting a form?

The model doesn't seem to have access to the request object, so I can't do it at it's save() method.

Thanks in advance!

john2x
  • 22,546
  • 16
  • 57
  • 95
  • Similar question [here][1]. [1]: http://stackoverflow.com/questions/5785727/accessing-request-user-in-class-based-generic-view-createview-in-order-to-set-fk/7376147#7376147 – Bryan Sep 11 '11 at 19:58

1 Answers1

1

When submitting your form, you want to run commit=False on it so that it returns you an object without actually saving it. You can then assign the user to it. Here's an example:

profile = form.save(commit=False)
profile.user = request.user
profile.save()

Here's a little blurb on it in the docs: https://docs.djangoproject.com/en/1.3/topics/forms/modelforms/#the-save-method

Abid A
  • 7,588
  • 4
  • 32
  • 32