1

I have this custom user model on my Django project. I want to make the email as authentication field instead of the username. Also, I want to perform an email verification.

models.py

class es_user(models.Model):
    user = models.OneToOneField(User,related_name='es_user', on_delete=models.CASCADE),
    is_activated = models.BooleanField(default=False)
    def get_absolute_url(self):
        return reverse('user_detail', kwargs={'id': self.pk })

view.py

def signup(request):
    signup_form_instance = SignUpForm()
    if request.method == "POST":
        signup_form_instance = SignUpForm(request.POST)
        if signup_form_instance.is_valid():
            signup_form_instance2 = signup_form_instance.save(commit = False)
            username = signup_form_instance2.username
            password = signup_form_instance2.password
            signup_form_instance2.password = make_password(signup_form_instance.cleaned_data['password'])
            signup_form_instance2.save()
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request,user)
                    active_user = request.user
                    es_user_instance = es_user.objects.create(user= active_user)
            # return index(request)
            return redirect('index')
            # return user_detail(request)#successful signup redirect or return
            # return redirect('user_detail',id = [str(request.user.id) ])#kwargs={'id': request.user.id })
        else:
            print("SIGN UP FORM INVALID")

    return render(request,'signup.html',{'signup_form':signup_form_instance})

forms.py

class SignUpForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('username', 'email', 'password')
        # for adding bootstrap classes & placeholders
        widgets = {
            'username': TextInput(attrs={
                'class':'form-control',
                'placeholder': 'Username *'}),

            'email': EmailInput(attrs={
                'class':'form-control',
                'placeholder': 'Your Email *'}),

            'password':  PasswordInput(attrs={
                'class':'form-control',
                'placeholder': 'Your Password *'}),
        }
        help_texts = {
            'username': None,
        }
        # to remove labels in form
        labels = {
            'username': (''),
            'email':(''),
            'password':(''),
        }

My project is near completion so I cannot change my user model anymore or even change its name. So is there a way I can add email verification and using email instead of username for authentication without changing my user model.

I've seen a solution for a similar problem in this post . But I cannot use it since I use my custom user model es_user. is there a way in which I can edit it for my problem

Andrey Leontyev
  • 421
  • 3
  • 11
Adarsh D
  • 511
  • 6
  • 14

1 Answers1

0

To use Email as authentication, you have to use make new python file Backend.py and inside it write

class AuthenticationBackend(backends.ModelBackend):
    def authenticate(self, request,  username=None, password=None, **kwargs):
        usermodel = get_user_model()
        print(usermodel)

        try:
            user = usermodel.objects.get(Q(username__iexact=username) | Q(
                email__iexact=username))
            if user.check_password(password):
                return user
        except user.DoesNotExist:
            pass

and add this AuthenticationBackend in settings.py as

AUTHENTICATION_BACKENDS = (
    'users.backend.AuthenticationBackend',
    'django.contrib.auth.backends.ModelBackend',
    )

This will let you authenticate user with both username and password.

For second part of your question,Please follow:

Django Custom User Email Account Verification

Kshitish
  • 60
  • 10