Accepting email address as username in Django

后端 未结 12 2070
感动是毒
感动是毒 2020-11-28 19:48

Is there a good way to do this in django without rolling my own authentication system? I want the username to be the user\'s email address instead of them creating a userna

12条回答
  •  生来不讨喜
    2020-11-28 20:34

    Not sure if people are trying to accomplish this, but I found nice (and clean) way to only ask for the email and then set the username as the email in the view before saving.

    My UserForm only requires the email and password:

    class UserForm(forms.ModelForm):
        password = forms.CharField(widget=forms.PasswordInput())
    
        class Meta:
            model = User
            fields = ('email', 'password')
    

    Then in my view I add the following logic:

    if user_form.is_valid():
                # Save the user's form data to a user object without committing.
                user = user_form.save(commit=False)
    
                user.set_password(user.password)
                #Set username of user as the email
                user.username = user.email
                #commit
                user.save()
    

提交回复
热议问题