django
  1. django-user-registration-with-email-confirmation

User Registration with Email Confirmation - ( User Management in Django )

Heading h2

Syntax

Django

from django.contrib.auth.models import User
from django.core.mail import EmailMessage
from django.shortcuts import render, redirect
from django.urls import reverse
from django.contrib import messages
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode

from .forms import RegistrationForm
from .token import account_activation_token

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            message = render(request, 'accounts/activate_account_email.html', {
                        'user': user,
                        'domain': current_site.domain,
                        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                        'token': account_activation_token.make_token(user)
            })
            mail_subject = 'Activate your account'
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(mail_subject, message, to=[to_email])
            email.send()
            messages.success(request, 'Activation link sent to your email.')
            return redirect('/')
    else:
        form = RegistrationForm()
    return render(request, 'accounts/register.html', {'form': form})


def activate_account(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=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()
        messages.success(request, 'Account activated successfully.')
        return redirect('login')
    else:
        messages.error(request, 'Activation link is invalid.')
        return redirect('register')

Example

Django

In this example, we create a user registration page where the user enters their username, email, and password. We then send a confirmation email to the user, which includes an activation link that they can click to activate their account.

from django.contrib.auth.models import User
from django.core.mail import EmailMessage
from django.shortcuts import render, redirect
from django.urls import reverse
from django.contrib import messages
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode

from .forms import RegistrationForm
from .token import account_activation_token

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            message = render(request, 'accounts/activate_account_email.html', {
                        'user': user, 'domain': current_site.domain,
                        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                        'token': account_activation_token.make_token(user)
            })
            mail_subject = 'Activate your account'
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(mail_subject, message, to=[to_email])
            email.send()
            messages.success(request, 'Activation link sent to your email.')
            return redirect('/')
    else:
        form = RegistrationForm()
    return render(request, 'accounts/register.html', {'form': form})


def activate_account(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=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()
        messages.success(request, 'Account activated successfully.')
        return redirect('login')
    else:
        messages.error(request, 'Activation link is invalid.')
        return redirect('register')

Output

Django

When the user enters their registration information, they receive an email confirmation with an activation link. Upon clicking the activation link, the user's account is activated and they are redirected to the login page.

Explanation

This example demonstrates how to implement user registration with email confirmation in Django. When a user registers, an email is sent to their email address with an activation link. The activation link contains a token that is associated with the user's account. When the user clicks on the activation link, the token is validated, and the user's account is activated.

Use

This user registration feature is useful for websites that require user authentication and want to ensure that the user's email address is valid. This feature can be used for creating new user accounts, verifying existing user accounts, and resetting passwords.

Important Points

  • User registration with email confirmation is a popular feature in web applications that require user authentication.
  • Django provides built-in authentication support, which can be extended to include email confirmation.
  • Email confirmation helps to ensure that the user's email address is valid and reduces the likelihood of fraudulent accounts.

Summary

In conclusion, user registration with email confirmation is an important feature for web applications that require user authentication. Django provides built-in support for user authentication and can be extended to include email confirmation. By validating the user's email address, we can reduce the likelihood of fraudulent accounts and improve the security of our web application.

Published on: