Django Blog #20: Processing Forms in Views

by Alex
Django Blog #20: Processing Forms in Views
You need to create a new view that processes the form and sends an email when it is accepted successfully. Edit the 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  
        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 the request object and the post_id variable as parameters
  • The get_object_or_404 shortcut is used to get the post ID. It also checks if the post status is published.
  • 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 with POST. Assume that if the request is GET, the form will be displayed blank, and if POST, the form is sent and processed. So the scripts use request.method == 'POST' to find the difference.

Next, the process of displaying and processing the form:

  1. When the view is initially loaded with a GET request, a new form instance is created that will be used to display an empty form in the template:
    form = EmailPostForm()
  2. 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 in request.POST:
    if request.method == 'POST' 
       # The form has been submitted 
        form = EmailPostForm(request.POST)
  3. The sent data is then validated using the form’s is_valid() method. It validates the data and returns True if all fields contain valid data. If there is incorrect information somewhere, the is_valid() method returns False. You can see a list of validation errors by accessing form.errors.
  4. If the form failed validation, it is rendered again in the template with the new data. Validation errors are displayed in the template.
  5. 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.

Related Posts