What's the best way of creating an email verification in Django?

37 Views Asked by At

So, My idea is:

  • Create a user
  • Verification Code is send in email
  • Confirm email and active user

I tried this views, creating the user but not activate it. Then comparing the user code with the generated code.

but it isn't working

def createuser(request):
    form = MyUserCreationForm()
    # confirmed = User.is_email_confirmed
    if request.method == 'POST':
        form = MyUserCreationForm(request.POST)
        if form.is_valid():     

            code = User.objects.make_random_password(length=6,allowed_chars='1234567890')

            user = form.save(commit=False)
            user.username = user.username.lower()
            user.email = user.email.lower()
            user.is_active = False
            
            user.profile.code = code
            user.save()
            login(request,user)
            

        
    
            subject = 'Confirm your email' 
            confirmation_code = code
            message = f'Confirm your email with this code: {confirmation_code}'
            from_email = '[email protected]'
            to_email = request.POST['email']
            send_mail(subject,message,from_email,[to_email]).save()
            user.save()
            return redirect('verification')
        
        else:
            messages.error(request,'An error occured during your registration')
    context = {'form':form}
    return render(request, 'signup.html', context)

def verifycode(request):
    if request.method == 'POST':
        code = request.POST['code']
        
        # Check if the verification code matches
        if request.user.profile.code == code:
            # Mark the user as active
            request.user.is_active = True
            request.user.save()
            # Log in the user
            login(request, request.user)
            return redirect('home')
        else:
            # Handle incorrect verification code
            return render(request, 'verify.html', {'error': 'Incorrect verification code'})
    else:
        return render(request, 'verify.html')

any other (and functional) way of doing it?

1

There are 1 best solutions below

4
Genchev On

first of all the from code you provide, save user's profile. Add save to

user.profile.save() after user.profile.code = code

Email sending, its not needed to be saved, you can remove .save() from

    send_mail(subject,message,from_email,[to_email]).save()

like

    send_mail(subject,message,from_email,[to_email])  # Removed .save()

also its better to login after verification, so you can remove login after registration in def createuser.

Other way to do this, you can see this one https://pypi.org/project/Django-Verify-Email/ there are also examples.

I hope this helps!