Created
January 24, 2012 02:23
-
-
Save sleekslush/1667396 to your computer and use it in GitHub Desktop.
Adding request user to a form save
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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.
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
So yes and no. The
self.object
originates fromdjango.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 theself.object
to the result of aform.save()
. Most of this I learned from reading the source.form.save()
will return an instance ofTeam
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 therequest.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 wherecommit=False
comes into play). Now that I've got the model instance, I set theuser
property and then I explicitly call thesave()
method onself.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 😄