7

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?

Handcraftsman
  • 6,863
  • 2
  • 40
  • 33
ArmenB
  • 2,125
  • 3
  • 23
  • 47

3 Answers3

8

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()
  • 1
    Sorry, the LoginForm with the email field will show password first and then email. Put this inside __init__ to fix that: self.fields.keyOrder = ['email','password',] – Dean Quiñanola Mar 05 '12 at 19:17
1

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

ArmenB
  • 2,125
  • 3
  • 23
  • 47
  • that's INTERNET for you. I should have pasted the content of the website here. Now I don't even work with django anymore. Sorry my fault. – ArmenB Nov 17 '16 at 20:15
0

Add that field to the Meta class's exclude:

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

    class Meta:
        model = User
        exclude = ['username',]
Jack M.
  • 30,350
  • 7
  • 55
  • 67
  • That didn't help really. so I tried different variations of that exclude but it didn't work for me. – ArmenB Oct 01 '11 at 21:22