上QQ阅读APP看书,第一时间看更新
Handling forms in views
You have to create a new view that handles the form and sends an email when it's successfully submitted. Edit the views.py file of your blog application and add the following code to it:
from .forms import EmailPostForm
def post_share(request, post_id):
# Retrieve post by id
post = get_object_or_404(Post, id=post_id, status='published')
if request.method == 'POST':
# Form was submitted
form = EmailPostForm(request.POST)
if form.is_valid():
# Form fields passed validation
cd = form.cleaned_data
# ... send email
else:
form = EmailPostForm()
return render(request, 'blog/post/share.html', {'post': post,
'form': form})
This view works as follows:
- We define the post_share view that takes the request object and the post_id variable as parameters.
- We use the get_object_or_404() shortcut to retrieve the post by ID and make sure that the retrieved post has a published status.
- We use the same view for both displaying the initial form and processing the submitted data. We differentiate whether the form was submitted or not based on the request method and submit the form using POST. We assume that if we get a GET request, an empty form has to be displayed, and if we get a POST request, the form is submitted and needs to be processed. Therefore, we use request.method == 'POST' to distinguish between the two scenarios.
The following is the process to display and handle the form:
- When the view is loaded initially with a GET request, we create a new form instance that will be used to display the empty form in the template:
form = EmailPostForm()
- The user fills in the form and submits it via POST. Then, we create a form instance using the submitted data that is contained in request.POST:
if request.method == 'POST':
# Form was submitted
form = EmailPostForm(request.POST)
- After this, we validate the submitted data using the form's is_valid() method. This method validates the data introduced in the form and returns True if all fields contain valid data. If any field contains invalid data, then is_valid() returns False. You can see a list of validation errors by accessing form.errors.
- If the form is not valid, we render the form in the template again with the submitted data. We will display validation errors in the template.
- If the form is valid, we retrieve the validated data accessing form.cleaned_data. This attribute is a dictionary of form fields and their values.
If your form data does not validate, cleaned_data will contain only the valid fields.
Now, let's learn how to send emails using Django to put everything together.