我不明白關於exclude的官方文檔。Django:表格保存exculde某些字段
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
如果排除隻影響下級元定義的模型,所以exclude = ['captcha_text']
是行不通的?
因此,save方法只用於保存在** class Meta **下定義的'model',並且extra_field不會被保存? – Mithril
由於extra_field不存在於模型本身中,因此您期望extra_field得到保存? – Sudipta
謝謝!我明白了。這是一個很難的方式來做一個大django項目的一些修改... – Mithril