Django - Creating forms from mod

2020-05-21  本文已影响0人  DCmf9w7Fnfm

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链接的modelArticle.

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. 如果想要额外添加UserUserForm以外的fields则可以如代码例中添加password1

另外, fields = ['username', 'email', 'password', 'is_active']中不属于User的部分会无法存入默认的UserModel

上一篇下一篇

猜你喜欢

热点阅读