Django可以创建直接存入models的form, 叫做ModelForm
>>> from django.forms import ModelForm
>>> from myapp.models import Article
# Create the form class.
>>> class ArticleForm(ModelForm):
... class Meta:
... model = Article
... fields = ['pub_date', 'headline', 'content', 'reporter']
首先ArticleForm
可以继承ModelForm
, 在ArticleForm
的内部类Meta
中指定该Form
链接的model
是Article
.
model = Article
用于在admin.py
中添加该model
, 本文为例即应当是
from .models import Article
admin.site.register(Article)
fields = ['pub_date', 'headline', 'content', 'reporter']
中的元素应当是Article
中的field
.
一个更复杂的场景是, form
本身继承另一个form
, 举例
class UserForm(UserCreationForm):
password1 = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ['username', 'email', 'password', 'is_active']
widgets = {
'username': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Type a username'}),
'email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'example@email.com'}),
}
在此种场景下, fields = ['username', 'email', 'password', 'is_active']
里的元素不仅仅可以是User
的fields, 还可以UserForm
的fields. 如果想要额外添加User
和UserForm
以外的fields则可以如代码例中添加password1
另外, fields = ['username', 'email', 'password', 'is_active']
中不属于User
的部分会无法存入默认的User
Model
网友评论