-
-
Save sleekslush/1667396 to your computer and use it in GitHub Desktop.
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) |
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 😄
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
Hmm. Very interesting. It's starting to gel, somewhat. is
self.object
something intrinsic toCreateView
? This is the first time I'm seeingform.save
, so I'll go take a look at the docs/source for that one.Thanks for the continued help on this.