美文网首页
Django - Creating forms from mod

Django - Creating forms from mod

作者: DCmf9w7Fnfm | 来源:发表于2020-05-21 20:10 被阅读0次

    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

    相关文章

      网友评论

          本文标题:Django - Creating forms from mod

          本文链接:https://www.haomeiwen.com/subject/riitahtx.html