Handling ModelForms in views

We will use the post detail view to instantiate the form and process it in order to keep it simple. Edit the views.py file, add imports for the Comment model and the CommentForm form, and modify the post_detail view to make it look like the following:

from .models import Post, Commentfrom .forms import EmailPostForm, CommentFormdef post_detail(request, year, month, day, post):    post = get_object_or_404(Post, slug=post,                                   status='published',                                   publish__year=year,                                   publish__month=month,                                   publish__day=day)     # List of active comments for this post    comments = post.comments.filter(active=True)    new_comment = None    if request.method == 'POST':        # A comment was posted        comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): ...

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.