- Django 2 by Example
- Antonio Melé
- 240字
- 2021-06-25 21:19:04
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.
- 自動駕駛網絡:自智時代的網絡架構
- C++黑客編程揭秘與防范
- 異構基因共表達網絡的分析方法
- Hands-On Chatbots and Conversational UI Development
- 智慧城市中的移動互聯網技術
- 中小型局域網組建、管理與維護實戰
- 6G新技術 新網絡 新通信
- OMNeT++與網絡仿真
- Unity Artificial Intelligence Programming
- Master Apache JMeter:From Load Testing to DevOps
- Echo Quick Start Guide
- VMware NSX網絡虛擬化入門
- Implementing NetScaler VPX?
- 物聯網基礎及應用
- 圖神經網絡前沿