如何从Django中的UserCreationForm中删除用户名字段

时间:2011-09-23 06:22:42

标签: django forms django-registration

我希望我的用户注册页面显示电子邮件和密码字段,而不是用户名。 我创建了这个注册表:

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

但用户名仍然显示。我是否需要覆盖其他内容?

3 个答案:

答案 0 :(得分:7)

您可以从表单的字段中弹出用户名,如下所示:

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 :(得分:1)

找到它。这正是我想要做的: http://www.micahcarrick.com/django-email-authentication.html

答案 2 :(得分:0)

将该字段添加到Meta类的exclude:

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

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