【问题标题】:Django: form save exculde certain fieldDjango:表单保存排除某些字段
【发布时间】:2013-07-15 08:12:58
【问题描述】:

关于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'字段将不会显示在前端,调用表单保存方法时不会保存。
但是当我按照文档说的那样做时,'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'] 就不起作用了?

【问题讨论】:

    标签: python django forms


    【解决方案1】:

    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”的字段。

    【讨论】:

    • 那么,save方法只用于保存class Meta下定义的model,而extra_field不会被保存?
    • 由于模型本身不存在 extra_field,您希望将 extra_field 保存在哪里?
    • 谢谢!我现在明白了。对大型 django 项目进行一些修改确实是一种很难的方法...
    • 如果我想在保存时提供title 怎么办。我应该把数据放在cleaned_data['title'] = 'something'
    【解决方案2】:

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

    form = PartialAuthorForm()
    

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

    {{ form.as_p }}
    

    其次,在模型表单中添加额外的字段应该没有问题,参见例如this 发帖。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-08
      • 2011-06-23
      • 1970-01-01
      • 2013-08-28
      • 2013-12-03
      • 2011-08-30
      相关资源
      最近更新 更多