2013-05-02 69 views
5

我試圖找出如何從UserChangeForm中排除用戶名和/或密碼的方法。我嘗試了excludefields,但我沒有爲這兩個領域工作。從Django身份驗證中的UserChangeForm中排除用戶名或密碼

下面是一些代碼:

class ArtistForm(ModelForm): 
    class Meta: 
     model = Artist 
     exclude = ('user',) 

class UserForm(UserChangeForm): 
    class Meta: 
     model = User 
     fields = (
      'first_name', 
      'last_name', 
      'email', 
      ) 
     exclude = ('username','password',) 

    def __init__(self, *args, **kwargs): 
     self.helper = FormHelper 
     self.helper.form_tag = False 
     super(UserForm, self).__init__(*args, **kwargs) 
     artist_kwargs = kwargs.copy() 
     if kwargs.has_key('instance'): 
      self.artist = kwargs['instance'].artist 
      artist_kwargs['instance'] = self.artist 
     self.artist_form = ArtistForm(*args, **artist_kwargs) 
     self.fields.update(self.artist_form.fields) 
     self.initial.update(self.artist_form.initial) 

    def clean(self): 
     cleaned_data = super(UserForm, self).clean() 
     self.errors.update(self.artist_form.errors) 
     return cleaned_data 

    def save(self, commit=True): 
     self.artist_form.save(commit) 
     return super(UserForm, self).save(commit) 

回答

9

您將無法如果您使用UserChangeForm做到這一點。

看到這個https://github.com/django/django/blob/master/django/contrib/auth/forms.py

您會注意到,此頁面上的UserChangeForm明確定義了usernamepassword。這些字段存在於表單上的變量declared_fields中。

excludefields只適用於取自Meta中定義的model的字段。如果您明確定義某個字段(即declared_fields),即使已使用exclude排除該字段,它們也會出現在表單中。所以,這些領域展現給你。

想了解更多關於這ModelFormMetaclass檢查__new__https://github.com/django/django/blob/master/django/forms/models.py

解決方法:

不要使用UserChangeForm並閱讀其代碼。它不會提供太多。您可以編寫自己的表格,該表格的範圍僅限於ModelForm,並且設置爲Meta Model。在表單中複製UserChangeForm中的零件。

class UserForm(forms.ModelForm): 

    class Meta: 
     model = User 

    def __init__(self, *args, **kwargs): 
     #copy any functionality you want form UserChangeForm 

    def clean_password(self): 
     #copy functionality provided by UserChangeForm 
+0

確定這做了工作,但現在每次我調用'save()'時,用戶名和密碼都是NULL。另外從我的擴展用戶類的參數不會得到保存以太。 – codingjoe 2013-05-05 13:49:51

相關問題