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 the form dynamically for us. Each model field type has a corresponding default form field type. The way we define our model fields is taken into account for form validation. By default, Django builds a form field for each field contained in the model. However, you can explicitly tell the framework which fields you want to include in your form using a fields list or define which fields you want to exclude using an exclude list of fields. For our CommentForm form, we will just use the name, email, and body fields because those are the only fields our users will be able to fill in.