Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the Username field from the UserCreationForm in Django

I want my user registration page to display email and password field, and no username. I have created this Register Form:

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

But the username still appears. Do I need to override something else?

like image 859
ArmenB Avatar asked Sep 23 '11 06:09

ArmenB


2 Answers

You can pop out the username from the form's fields like so:

class RegisterForm(UserCreationForm):

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

But then you would need to fill-in some random username before saving like so:

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()

There are other considerations to take when you hack it this way, like making sure your LoginForm would pull the username later on when it is needed:

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()
like image 148
Dean Quiñanola Avatar answered Nov 04 '22 22:11

Dean Quiñanola


Found it. This is exactly what I wanted to do: http://www.micahcarrick.com/django-email-authentication.html

like image 39
ArmenB Avatar answered Nov 04 '22 22:11

ArmenB