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 ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.