Skip to content

Instantly share code, notes, and snippets.

@sleekslush
Created January 24, 2012 02:23
Show Gist options
  • Save sleekslush/1667396 to your computer and use it in GitHub Desktop.
Save sleekslush/1667396 to your computer and use it in GitHub Desktop.
Adding request user to a form save
class MyView(CreateView):
model = Team
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return FormMixin.form_valid(self, form)
@dnoyes
Copy link

dnoyes commented Jan 24, 2012

Hmm. Very interesting. It's starting to gel, somewhat. is self.object something intrinsic to CreateView? This is the first time I'm seeing form.save, so I'll go take a look at the docs/source for that one.

Thanks for the continued help on this.

@sleekslush
Copy link
Author

So yes and no. The self.object originates from django.views.generic.detail.SingleObjectMixin. The biggest issue I have with Django's class-based views is they are not 100% easily extensible. In the example above, I have to know about a side effect of the method, which is that it sets the self.object to the result of a form.save(). Most of this I learned from reading the source.

form.save() will return an instance of Team with all the model's fields populated from a form POST. In your case, you want to add another value to the model, which is the request.user object. So what I do is I say, "give me a model instance bound with data from the POST, but DO NOT SAVE IT YET!" (that last part is where commit=False comes into play). Now that I've got the model instance, I set the user property and then I explicitly call the save() method on self.object to perform the actual commit operation to the database.

It's not that it's all that complicated, but rather, there's a very specific way to accomplish the task at hand. Let me know if you want me to continue rambling. I love django and this stuff makes me smile 😄

@dnoyes
Copy link

dnoyes commented Jan 24, 2012

Great explanation. Thanks.

To avoid severe brain melt, I've backed off an am doing it the "easy" way first. I'll post that when I've got it done (probably tomorrow night). Then I can circle back to try and use CreateView again.

Even without CreateView, I think it's going to be pretty slim. Being able to use ModelForm and form.save(commit=False) makes things super nice.

@dnoyes
Copy link

dnoyes commented Jan 25, 2012

Here's what I ended up with: https://gist.github.com/1674741

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment