[Django]-Send activation code by email after registration instead of URL

2πŸ‘

I’ve used a variation of the following in projects:

# models.py
import random

from django.conf import settings
from django.db import models


def generate_activation_code():
    return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(6))


class ActivationCode(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    code = models.CharField(max_length=6, default=generate_activation_code)


# views.py
from django.http import Http404

def register_user(request):
    # create your `new_user` however you see fit
    code = ActivationCode.objects.create(user=new_user)
    send_mail(
        'Activate Your Account',
        'Here is the activation code: %s' % code,
        'from@example.com',
        [user.email]
    )
    render(request, 'activation_sent.html')

def check_activation_code(request, code):
    try:
        ActivationCode.objects.get(code=code)
        # ... All set, activate & login the user, & delete the activation code
    except ActivationCode.DoesNotExist:
        raise Http404

    return render(request, 'welcome.html')

Enhancements could include adding an expiry date to the ActivationCode that you check in the view, and/or a management job to clean old codes.

πŸ‘€notanumber

1πŸ‘

Instead of creating a random value, encode some unique user data and append it to the url. like this

import jwt
data = {'email' : "test@test.com"} # Some unique field for reference
secret_key = "test"
algorithm = "HS256" # You can use MD5 or whatever you want
jwt.encode(data, secret_key, algorithm)

After they click the mail activation url you can decode and validate the unique field in Database. For this you don’t want save the code in DB. It’s my suggestion

-1πŸ‘

You can generate 6 digit random number:

import random  
codeval = random.randint(111111,999999)

And send it with email. And you can keep exact the same copy of the random number. And when user will give his number. You can match it with the stored one. If it matches then you will activate the user profile.

Leave a comment