Registration with mail confirmation in Django

Hei guys,

Today I am going to show you how to create a process for registration with mail confirmation. It will work like, you fill up a form and submit it. Then check your mail and confirm the mail verification by clicking on a unique link. It’s simple to use and a great authentication process. So without further due, let’s start. First of all, go to settings.py file and set the mail server and host like below:

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'example@example.com'
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 587

Change EMAIL_HOST_USER to your Gmail and EMAIL_HOST_PASSWORD  to your Gmail password. Then create a token.py file and paste the following coding snippet.

from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six
class TokenGenerator(PasswordResetTokenGenerator):
    def _make_hash_value(self, user, timestamp):
        return (six.text_type(user.pk) + six.text_type(timestamp) +six.text_type(user.is_active))
    account_activation_token = TokenGenerator()

It is responsible to create a unique string for the verification link. Create a forms.py file and paste the following code to forms.py file to create form instance.

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class registerUser(UserCreationForm):
    class Meta:
        model = User
        fields = [
        'first_name',
        'last_name',
        'email',
        'username',
        'password1',
        'password2'
        ]

Now write the views function to send the filled data to the server and send the required hashed data to the mail server. Here we are using Django core mail client to send emails to the user’s email address. Please follow the below code snippet:

from .forms import registerUser
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import send_mail
from .tokens import account_activation_token
def getRegister(self, request):
    form = registerUser(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.is_active = False
        instance.save()
        current_site = get_current_site(request)
        mail_subject = 'VMA: Activate your account.'
        message = render_to_string('mail_confirm_message.html', {
            'user': instance,
            'domain': current_site.domain,
            'uid': instance.pk,
            'token': account_activation_token.make_token(instance)
        })
        to_email = form.cleaned_data.get('email')
        to_list = [to_email]
        from_email = settings.EMAIL_HOST_USER
        usr = get_object_or_404(User, id=instance.id)
        obj = verifyAccount.objects.create(user=usr, hash_code=message, is_verify=False)
        obj.save()
        send_mail(mail_subject, message, from_email, to_list, fail_silently=True)
        return HttpResponse('<h3>A confirmation mail was sent. Please check inbox and confirm your account to '
                'login</h3>')
    else:
        messages.warning(request, 'something went wrong')
        return redirect('account:register')

Now create mail_confirm_message.html file in the template directory and paste the following code.

{% autoescape off %}
Hi {{ user.username }},
Thanks for your registration in our site
Please click on the link below to confirm your registration,
http://{{ domain }}{% url 'activate' uid=uid token=token %}
{% endautoescape %}

Write another function named activate in your views.py file and paste the following code to activate the account.

def activate(request, uid, token):
    try:
        user = User.objects.get(pk=uid)
        verify = verifyAccount.objects.get(user_id=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.save()
        verify.is_verify = True
        verify.save()
        return HttpResponse('Thank you for your email confirmation. Now you can <a href="/login" %}"="">login</a> your account.')
    else:
        return HttpResponse('Activation link is invalid!')

For the first time, when a user fills up the registration form and submit, an email will be sent to the host mail that will seek permission to login from an unauthorized source. So you have to accept the permission. Now every successful submission of the registration form will send an email to the user’s mail which he was provided in the email field.

145 Views

About Author

Nasir

Welcome to CodeKit.xyz. I am working in an automation company as a software engineer. From the deep thirst of learning, I have developed this platform.

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>