官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 新野县| 平乐县| 穆棱市| 曲麻莱县| 祁阳县| 玛曲县| 怀集县| 项城市| 凤翔县| 兴安盟| 峨边| 西乌珠穆沁旗| 潞西市| 五华县| 丰台区| 海门市| 梨树县| 祁东县| 延吉市| 台安县| 滦平县| 耿马| 贵德县| 商城县| 高台县| 泗阳县| 台湾省| 电白县| 西和县| 夏河县| 怀安县| 汕尾市| 岑溪市| 五指山市| 叶城县| 定结县| 全南县| 宜宾市| 布尔津县| 怀安县| 安平县|