Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Configuration
3.
Generate Token
4.
Create Registration Form
4.1.
forms.py
5.
Create Activation View
6.
URLS
7.
Frequently Asked Questions
8.
Key Takeaways
Last Updated: Mar 27, 2024

Django Sign Up and Login with Confirmation Email

Introduction

When we join up for a website, it usually provides us a confirmation link to activate our account. It may also request an email address to modify an account's email address or reset the password.

When someone registers on our web app, this tutorial will teach you to send a confirmation email using Django. We'll talk about how to do it quickly. On the other hand, Django offers a variety of different solutions, such as Django all auth application, Django-registration, and Django-registration-redux. This task is made a lot easier with those applications.

Before we begin, we must ensure that we are familiar with the Django and Python programming languages. Create a Django installation and customize the settings.

Configuration

We must first configure the email host server in settings.py for the confirmation email. In the settings.py file, add the following configuration.

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

 

We used the email address and password and the Gmail SMTP host server. You can also use the other SMTP server.

Generate Token

The token that will be used in the email confirmation URL must be created. Create a token.py file in the token folder and paste the code below into it.

from django.contrib.auth.tokens import PasswordResetTokenGenerator  
from django.utils import six  
class TokenGen(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 = TokenGen()  

 

To change the password, we utilized the PasswordTokenGenerator class. We produced the unique token for confirmation in the code above.

Create Registration Form

The built-in UserCreationForm class in Django is a great class for constructing forms. In the program, we create a forms.py file and import the UserCreationForm class. Let's have a look at the following code

forms.py

from django import forms  
from django.contrib.auth.forms import UserCreationForm  
from django.contrib.auth.models import User  
  
class SignupForm(UserCreationForm):  
    email = forms.EmailField(max_length=200, help_text='Required')  
    class Meta:  
        model = User  
        fields = ('username', 'email', 'password1', 'password2')  

 

The UserCreationForm and built-in User were imported in the code above. Then we designed a SignupForm that included an extra field for email.
 

view.py

from .forms import SignupForm
from django.http import HttpResponse  
from django.shortcuts import render, redirect  
from django.contrib.auth import login, authenticate  
from django.utils.encoding import force_bytes, force_text
urlsafe_base64_decode     
from django.contrib.sites.shortcuts import get_current_site  
from django.template.loader import render_to_string 
from django.utils.http import urlsafe_base64_encode,   
from django.core.mail import EmailMessage  
from .tokens import account_activation_token  
from django.contrib.auth.models import User  
 
  
def signup(request):  
    if request.method == 'POST':  
        form = SignupForm(request.POST)  
        if form.is_valid():  
            # the form has to be saved in the memory and not in DB
            user = form.save(commit=False)  
            user.is_active = False  
            user.save()  
            #This is  to obtain the current cite domain   
            current_site_info = get_current_site(request)  
            mail_subject = 'The Activation link has been sent to your email address'  
            message = render_to_string('acc_active_email.html', {  
                'user': user,  
                'domain': current_site_info.domain,  
                'uid':urlsafe_base64_encode(force_bytes(user.pk)),  
                'token':account_activation_token.make_token(user),  
            })  
            to_email = form.cleaned_data.get('email')  
            email = EmailMessage(  
                        mail_subject, message, to=[to_email]  
            )  
            email.send()  
            return HttpResponse('Please proceed confirm your email address to complete the registration')  
    else:  
        form = SignupForm()  
    return render(request, 'signup.html', {'form': form})  

 

Here, we develop a sign-up view that receives data using the POST method and validates it. We chose commit = False since it allows us to get the model object and add some additional characteristics. We've set user.is active = False, which implies the user won't be able to log in until the email has been validated.

Then we sent mail with the subject message using the EmailMessage() function. A template was used to produce the email message.

templates/acc_active_email.html

{% autoescape off %}  
Greetings, {{ user.username }},  
Kindly click below given link to confirm your registration, 
http://{{ domain }}{% url 'activate' uidb64=uid token=token %}  
{% endautoescape %}  

 

The above template generates an email body with an activation link that will be sent to the applicant.

For the activation link, we'll need to construct a view.

Create Activation View

We must activate the user's account via the activation link once they have clicked on it. The activate view is in charge of this procedure.

views.py

def activate(request, uidb64, token):  
    User = get_user_model()  
    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()  
        return HttpResponse('Thank you for your email confirmation. Now you can login your account.')  
    else:  
        return HttpResponse('Activation link is invalid!')  

 

After the signup function, we've included the activate function. This view will verify that the token is legitimate before allowing the user to activate and log in. We set user.is active = True, indicating that the user is able to log in.

The views will now be mapped to the URLs.

URLS

from django.urls import path  
from .views import home, index, activate  
urlpatterns = [  
    path('', home, name = 'home'),  
    path('form/', index, name = 'index'),  
    path('activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/',  
        activate, name='activate'),  
] 

 

Now, create a signup form in signup.html.

{% extends 'baseview.html' %}  
  
{% block content %}  
<div class = "container">  
  <h2>Sign up</h2>  
  <form method="post">  
    {% csrf_token %}  
      {% for field in form %}  
      <p>  
        {{ field.label_tag }}<br>  
        {{ field }}  
        {% if field.help_text %}  
          <small style="display: none ">{{ field.help_text }}</small>  
        {% endif %}  
        {% for error in field.errors %}  
          <p style="color: red">{{ error }}</p>  
        {% endfor %}  
      </p>  
      {% endfor %}  
    <button type="submit">Sign up</button>  
  </form>  
</div>  
{% endblock %}  

 

The form will look like below. When the user clicks on the submit button the activation link sends their entered email id.


When you click on the signup button, the confirmation email is sent on the given email-id. Click on the received link and now you are ready to log in.

Frequently Asked Questions

  1. How is authentication handled in Django?
    Both authentication and authorization are handled by the Django authentication system. In a nutshell, authentication validates that a user is who they say they are, whereas authorization decides what an authenticated person can do. Both tasks are referred to as authentication in this context.
     
  2. What is OAuth in Django?
    OAuth is a security mechanism that allows you to authorize one application to engage with another on your behalf without disclosing your password.
     
  3. How many types of authentication are there in Django?
    Django provides two authentication functions: authenticate() and login (). Use authenticate to verify a given account and password ().

Key Takeaways

When we join up for a website, it usually provides us with a confirmation link to activate our account. It may also request an email address to modify an account's email address or reset the password.

Django comes with an authentication system configured by default. The authentication system's heart is made up of user objects.

We have some similar blogs on Django. You may have a look on for loop- Django template tags.

Thanks for visiting!

Live masterclass