Creating forms from models

We will still need to build a form to let our users comment on blog posts. Remember that Django has two base classes to build forms, Form and ModelForm. You used the first one previously to let your users share posts by email. In the present case, you will need to use ModelForm because you have to build a form dynamically from your Comment model. Edit the forms.py file of your blog application and add the following lines:

from .models import Comment class CommentForm(forms.ModelForm):    class Meta:        model = Comment        fields = ('name', 'email', 'body')

To create a form from a model, we will just need to indicate which model to use to build the form in the Meta class of the form. Django introspects the model and builds ...

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.