Django的forms.Form vs forms.ModelForm [英] Django's forms.Form vs forms.ModelForm
问题描述
从 forms.Form
创建的表单是手动的由你配置对于不直接与模型交互的表单,您最好使用这些表单。例如联系表单或通讯订阅表单,您可能不一定要与数据库进行交互。
从 forms.ModelForm
将自动创建,然后可以稍后调整。最好的例子来自Django网站上提供的精湛的文档。
forms.Form
文档:表单对象
使用 forms.Form创建的正常表单示例
:
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length = 100)
message = forms .CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required = False)
forms.ModelForm
:
文档:从模型创建表单
直接从文档:
如果您的表单将被使用到
直接添加或编辑Django模型,
您可以使用ModelForm
来避免
复制您的模型描述。
使用 forms.Modelform
创建的模型表单示例:
from django.forms import ModelForm
from。导入模型
#创建表单类。
class ArticleForm(ModelForm):
class Meta:
model = models.Article
此表单自动具有与文章
模型创建的所有相同的字段类型。
Could anyone please explain to me similarities and differences of Django's forms.Form & forms.ModelForm? I've used Django for 4 days, so excuse me if I don't know basic things. Thanks in advance!
Forms created from forms.Form
are manually configured by you. You're better off using these for forms that do not directly interact with models. For example a contact form, or a newsletter subscription form, where you might not necessarily be interacting with the database.
Where as a form created from forms.ModelForm
will be automatically created and then can later be tweaked by you. The best examples really are from the superb documentation provided on the Django website.
forms.Form
:
Documentation: Form objects
Example of a normal form created with forms.Form
:
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
forms.ModelForm
:
Documentation: Creating forms from models
Straight from the docs:
If your form is going to be used to directly add or edit a Django model, you can use a
ModelForm
to avoid duplicating your model description.
Example of a model form created with forms.Modelform
:
from django.forms import ModelForm
from . import models
# Create the form class.
class ArticleForm(ModelForm):
class Meta:
model = models.Article
This form automatically has all the same field types as the Article
model it was created from.
这篇关于Django的forms.Form vs forms.ModelForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!