Ricardo Vilaça
Ricardo Vilaça

Reputation: 1006

Creating user without username (or with auto-generated username)

I want to create a registration page that doesn't ask for an username, since i'm not planning on using it (i only need email and password).

However, i'm not sure how to tell django that username is not mandatory.

I'm having trouble registering users because they all get the same username (blank).

My user model:

class User(AbstractUser):
    departments = models.ManyToManyField(Department)

    def __str__(self):
        return f'{self.first_name} {self.last_name}'

My form for registering:

class UserCreateForm(UserCreationForm):
    class Meta():
        fields = ('first_name', 'last_name', 'email', 'departments', 'password1', 'password2')
        model = get_user_model()

The view:

class SignUpView(CreateView):
    form_class = UserCreateForm
    success_url = reverse_lazy('loginPage')
    template_name = 'accounts/signup.html'

What should i change in order to tell django to ignore the username field for the User model?

Is a random auto-generated username a good idea to avoid this problem? If yes, how do i code it?

@Shahzeb Qureshi, i tried this:

from django.utils.translation import gettext_lazy

class UserCreateForm(UserCreationForm):
    class Meta():
        fields = ('first_name', 'last_name', 'username', 'departments', 'password1', 'password2')
        model = get_user_model()
        labels = {
            'username':gettext_lazy('E-mail'),
        }

Upvotes: 0

Views: 1981

Answers (2)

Pavan kumar
Pavan kumar

Reputation: 515

Just generate the username from email use the code is given below

    email = '[email protected]'
    username = email.split('@')[0]

Upvotes: -1

Shahzeb Qureshi
Shahzeb Qureshi

Reputation: 612

A simple solution would be that you enter the email address in your username field instead of leaving it blank.

Upvotes: 3

Related Questions