I am a beginner in Django, and I was reading WS Vincent's Django for beginners. In the second to last chapter, he writes the following code. He's creating a view that allows for comments that can handle GET and POST requests without mixing FormMixin and his created ArticleDetailView. I understand all of that, but what I don't understand is why it was constructed like this? Can someone explain what self.object and self.get_object are in this example? Also, why do we save twice in the second method? Thanks::
def post(self, request, *args, **kwargs):
self.object = self.get_object()
return super().post(request, *args, **kwargs)
def form_valid(self, form):
comment = form.save(commit=False)
comment.article = self.object
comment.save()
return super().form_valid(form)
def get_success_url(self):
article = self.get_object()
return reverse("article_detail", kwargs={"pk": article.pk})
I don't have the book, but get_object
will return the object that this view displays. In your example the view is probably set to display a single Article
, but the form posts details for a Comment
. You use the get_object
method to get access to the Article
instance so that you can associate the Comment
with it.
Your second question: It doesn't save twice. It may be confusing, but when you set commit
to False
it instantiates the object, but does not save it. You do this when you want to add extra information after instantiating the model instance. It is actually saved to the database after the comment.save()
call.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.