1

我不明白关于exclude的官方文档。

Set the exclude attribute of the ModelForm‘s inner Meta class to a list of fields to be excluded from the form.

For example:

class PartialAuthorForm(ModelForm):
    class Meta:
        model = Author
        exclude = ['title']
Since the Author model has the 3 fields name, title and birth_date, this will result in the fields name and birth_date being present on the form.


我的理解如下:django form save 方法会保存所有的表单数据。如果一组 exclude =(' something ',) ,'something' 字段将不会显示在前端并且在调用表单保存方法时不会被保存。
但是当我按照文件说的那样做时,“某事”字段仍然显示。这是怎么回事?

我还想在表单中添加一些字段以进行验证,这些字段可以在不保存的情况下显示在前端。奇怪的是,我对这种需求一无所知。



**update**

我的代码:

class ProfileForm(Html5Mixin, forms.ModelForm):

    password1 = forms.CharField(label=_("Password"),
                                widget=forms.PasswordInput(render_value=False))
    password2 = forms.CharField(label=_("Password (again)"),
                                widget=forms.PasswordInput(render_value=False))

    captcha_text = forms.CharField(label=_("captcha"),
                                widget=forms.TextInput())
    captcha_detext = forms.CharField(
                                widget=forms.HiddenInput())

    class Meta:
        model = User
        fields = ("email", "username")
        exclude = ['captcha_text']

    def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        ..........

    def clean_username(self):
        .....

    def clean_password2(self):
        ....

    def save(self, *args, **kwargs):
        """
        Create the new user. If no username is supplied (may be hidden
        via ``ACCOUNTS_PROFILE_FORM_EXCLUDE_FIELDS`` or
        ``ACCOUNTS_NO_USERNAME``), we generate a unique username, so
        that if profile pages are enabled, we still have something to
        use as the profile's slug.
        """
        ..............

    def get_profile_fields_form(self):
        return ProfileFieldsForm

如果exclude只影响在 Meta 类下定义的模型,那exclude = ['captcha_text']不行吗?

4

2 回答 2

2

exclude = ['title']将从表单中排除该字段,而不是从模型中。 form.save()将尝试使用可用字段保存模型实例,但模型可能会抛出与缺少字段有关的任何错误。

要在模型表单中添加额外字段,请执行以下操作:

class PartialAuthorForm (ModelForm):
    extra_field = forms.IntegerField()

    class Meta:
        model = Author

    def save(self, *args, **kwargs):
        # do something with self.cleaned_data['extra_field']
        super(PartialAuthorForm, self).save(*args, **kwargs)

但请确保模型作者中没有名为“PartialAuthorForm”的字段。

于 2013-07-15T08:40:34.813 回答
0

首先,您的标题字段仍然显示的原因必须在您的视图中。确保您像这样创建(未绑定)表单实例:

form = PartialAuthorForm()

并在模板中尝试这个简单的渲染方法

{{ form.as_p }}

其次,在模型表单中添加额外的字段应该没有问题,参见例如这篇文章。

于 2013-07-15T08:42:59.857 回答