Reputation: 301
I'm following a Django Course about user authentication and authorisation. But the point is that I don't really understand the form_valid() method here :
class ArticleCreateView(CreateView):
model = Article
template_name = 'article_new.html'
fields = ('title', 'body') # new
def form_valid(self, form): # new
form.instance.author = self.request.user
return super().form_valid(form)
I cannnot figure what this method returns.
Thanks
Upvotes: 1
Views: 2051
Reputation: 93
Thank you to the people who answered this question.
By the way, this example is from the book: Django for Beginners 3.1 Build websites with Python & Django by William S. Vincent
I too wanted to know what was going on with this method. So, I printed out the variables.
print(f"form type: {type(form)}")
Results:
form type: <class 'django.forms.widgets.ArticleForm'>
And below; Yep, this really is the contents of the form that I filled out.
print(f"form: {form}")
form:
<tr>
<th>
<label for="id_title">Title:</label>
</th>
<td>
<input type="text" name="title" value="This is the title for this article" maxlength="255" required id="id_title">
</td>
</tr>
<tr>
<th>
<label for="id_body">Body:</label>
</th>
<td>
<textarea name="body" cols="40" rows="10" required id="id_body">And, this is the contents of this article,...blah, blah, blah.</textarea>
</td>
</tr>
Here we are redirecting the user to a page specific to this newly created article. In this example, the article was the 8th article that had been created. status_code=302 is a URL redirection
print(f"response type: {type(response)}")
print(f"response: {response}")
Here are the results:
response type: <class 'django.http.response.HttpResponseRedirect'>
response: <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/articles/8/">
When I looked at the results on the redirected page, I could see that the author was indeed assigned the value of the current user. So, this method took care of assigning the current user to the author field. No need to have the user fill this in while entering data in the form.
If you go to GitHub django/django and search this repository for form_valid
, the following link will contain various examples of how form_valid
may be used.
https://github.com/django/django/search?p=1&q=form_valid
Upvotes: 1
Reputation: 489
This method is called when correct data is entered into the form and the form has been successfully validated without any errors. You can handle post-success logic here like send a notification email to the user, redirect to a thank you page etc.
Django Documentation | Generic editing views
Upvotes: 3