You need to create a new view that processes the form and sends an email when it is accepted successfully. Edit the
views.py
file of the blog
application and add the following code: from .forms import EmailPostForm
def post_share(request, post_id)
# get post by id
post = get_object_or_404(Post, id=post_id, status='published')
if request.method == 'POST'
# The form has been sent
form = EmailPostForm(request.POST)
if form.is_valid()
# Form fields have been validated
cd = form.cleaned_data
# ... send email
else
form = EmailPostForm()
return render(request, 'blog/post/share.html', {'post': post,
{ 'form': form})
The view works as follows:
- A
post_share
representation is defined that takes therequest
object and thepost_id
variable as parameters - The
get_object_or_404
shortcut is used to get the post ID. It also checks if the post status ispublished
. - The same view is used to display the original form and process the submitted data. Based on the
request
method, you can see if the data has been submitted with the form or not yet, and acceptance is done withPOST
. Assume that if the request isGET
, the form will be displayed blank, and ifPOST
, the form is sent and processed. So the scripts userequest.method == 'POST'
to find the difference.
Next, the process of displaying and processing the form:
- When the view is initially loaded with a
GET
request, a newform
instance is created that will be used to display an empty form in the template:form = EmailPostForm()
- The user fills out the form and submits it using
POST
. An instance of the form is then created with the submitted data, which is stored inrequest.POST
:if request.method == 'POST' # The form has been submitted form = EmailPostForm(request.POST)
- The sent data is then validated using the form’s
is_valid()
method. It validates the data and returnsTrue
if all fields contain valid data. If there is incorrect information somewhere, theis_valid()
method returnsFalse
. You can see a list of validation errors by accessingform.errors
. - If the form failed validation, it is rendered again in the template with the new data. Validation errors are displayed in the template.
- If the validation passes, the data can be accessed using
form.cleaned_data
. This attribute is a dictionary, where its values are form fields.
If the form failed validation,
cleaned_data
will only contain fields whose data matched. Now we need to know how to send an email with Django.