2011-09-23 72 views
7

我希望我的用戶註冊頁面顯示電子郵件和密碼字段,並且沒有用戶名。 我已經創建了這個註冊表格:如何從Django中的UserCreationForm中刪除用戶名字段

class RegisterForm(UserCreationForm): 
    email = forms.EmailField(label = "Email") 
    #fullname = forms.CharField(label = "First name") 

    class Meta: 
     model = User 
     fields = ("email",) 

    def save(self, commit=True):   
     user = super(RegisterForm, self).save(commit=False 
     user.email = self.cleaned_data["email"] 
     if commit: 
      user.save() 
     return user 

但是用戶名仍然出現。我需要重寫其他內容嗎?

+0

我認爲username字段來自'UserCreationForm',所以從這裏排除它! – Ahsan

回答

0

該字段添加到元類的排除:

class RegisterForm(UserCreationForm): 
    email = forms.EmailField(label = "Email") 
    #fullname = forms.CharField(label = "First name") 

    class Meta: 
     model = User 
     exclude = ['username',] 
+0

這確實沒有幫助。所以我嘗試了不同的排除方式,但它對我沒有任何作用。 – ArmenB

5

可以彈出從表單字段的用戶名,像這樣:

class RegisterForm(UserCreationForm): 

    def __init__(self, *args, **kwargs): 
     super(RegisterForm, self).__init__(*args, **kwargs) 
     # remove username 
     self.fields.pop('username') 
    ... 

但那麼你就需要保存像以前一樣以填充一些隨機用戶名所以:

from random import choice 
from string import letters 
... 

class RegisterForm(UserCreationForm): 
... 
    def save(self): 
     random = ''.join([choice(letters) for i in xrange(30)]) 
     self.instance.username = random 
     return super(RegisterForm, self).save() 

還有其他方面的考慮,當你破解這種方式,像確保您的LoginForm的會拉的用戶名採取以後在需要時:

class LoginForm(AuthenticationForm): 

    email = forms.EmailField(label=_("E-mail"), max_length=75) 

    def __init__(self, *args, **kwargs): 
     super(LoginForm, self).__init__(*args, **kwargs) 
     self.fields['email'].required = True 
     # remove username 
     self.fields.pop('username') 

    def clean(self): 
     user = User.objects.get(email=self.cleaned_data.get('email')) 
     self.cleaned_data['username'] = user.username 
     return super(LoginForm, self).clean() 
+1

抱歉,帶有電子郵件字段的LoginForm將先顯示密碼,然後再顯示電子郵件。把它放在__init__中以解決這個問題:self.fields.keyOrder = ['email','password',] –

相關問題