2013-07-15 77 views
0

我不明白關於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']是行不通的?

回答

0

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」。

+0

因此,save方法只用於保存在** class Meta **下定義的'model',並且extra_field不會被保存? – Mithril

+0

由於extra_field不存在於模型本身中,因此您期望extra_field得到保存? – Sudipta

+0

謝謝!我明白了。這是一個很難的方式來做一個大django項目的一些修改... – Mithril

0

首先,您的標題字段仍然顯示的原因必須在您的視圖中。請確保您創建(綁定)形式的實例是這樣的:

form = PartialAuthorForm() 

,並嘗試在模板這個簡單的渲染方法

{{ form.as_p }} 

其次,它應該是沒有問題的額外字段添加到模型形式,見例如this後。