Django signup: set username to provided email address and save?

924 Views Asked by At

Short question (no actual need to read the rest): I have read multiple threads/tutorials (e.g. this one) on how to let users login via email. And I was wondering: why can't I just keep things simple and ask for an email address upon signup and then set the username to that email address and save the user?

Long part: I would create a form that is very similar to the UserCreationForm of Django 1.8. I'm not sure why I cannot find the same code for 3.1 (which makes me wonder even more whether my idea might be bad practice for some reason) but basically I would do this: create a ModelForm for the default user model, set fields = ["email"], render it manually as {{form.email}} in the template and then, in the view, I'll call form.save(commit=False) to get the object, set the username of that object to the given email address and save it. Orrrr don't I? :-)

EDIT

Since more source code was asked, here's basically what I meant:

forms.py

class UserCreationForm(forms.ModelForm):

    class Meta:
        model = User
        fields = ["email"]

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

views.py

...
form = UserCreationForm()
return render(request, 'myapp/createuser.html', {'form': form})
...

createuser.html

<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Register</button>
</form>
2

There are 2 best solutions below

0
On

your form seems just right try something like:

obj = form.save(commit=False)
obj.username= email
obj.save()

and that should do it also update me

2
On

That's a great question, you can do multiple things like

  1. Use AbstractBaseUser and you can username field to null being true.

  2. Or the better one use AbstractBaseUser, PermissionsMixin, BaseUserManager and in your User model manager you can do this;

    def create_user(self,email,username,profile_pic,password=None):
    if not email:
        raise ValueError("Email can't be empty")
    
    if not username:
        raise ValueError("Username can't be empty")
    
    email = self.normalize_email(email)
    username = email
    user = self.model(
        email=email,
        username=username,
        profile_pic=profile_pic,
    )
    user.set_password(password)
    user.save()
    
    return user