【发布时间】: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'] 就不起作用了?
【问题讨论】: