我不了解有关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表单保存方法将保存所有表单数据。如果一组排除=('某事'),'某事'字段将不会显示在调用表单保存方法时,前端并不会保存
但当我按照文件说的那样,'某事'领域仍然显示。问题是什么?
我还想在一个表单中添加一些字段来验证哪些字段可以显示在前端而不保存。我很遗憾没有找到这个需求。
**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
如果排除仅影响在Meta类下定义的模型,那么exclude = ['captcha_text']
将不起作用?
答案 0 :(得分: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”的字段。
答案 1 :(得分:0)
首先,您的标题字段仍然显示的原因必须在您的视图中的某个位置。确保您创建(未绑定)表单实例,如下所示:
form = PartialAuthorForm()
并在模板中尝试这种简单的渲染方法
{{ form.as_p }}
其次,向模型表单添加额外字段应该没有问题,例如, this发帖。