Django Sign Up and login with confirmation Email | Python
Last Updated :
12 Jul, 2025
Django provides a built-in authentication system that handles users, login, logout, and registration. In this article, we will implement a user registration and login system with email confirmation using Django and django-crispy-forms for elegant form rendering.
Install crispy forms using the terminal:
pip install --upgrade django-crispy-forms
Step 1: Create a New Django Project and App
Start a new Django project and move into the project directory:
django-admin startproject project
cd project
Create a new app called user:
python manage.py startapp user
Step 2: Set Up Templates Folder
Navigate to your user app folder and create a templates/user directory. Inside this folder, create the following HTML files:
- index.html
- login.html
- register.html
- Email.html
Your project structure should look like this:
Project StructureOpen your project/settings.py file and make the following changes:
1. Add 'user' and 'crispy_forms' to your installed apps:
INSTALLED_APPS = [
# Default Django apps...
'crispy_forms',
'user',
]
2. Add the crispy forms template pack setting at the end of the file:
CRISPY_TEMPLATE_PACK = 'bootstrap4'
3. Configure your email settings by adding your email credentials (replace placeholders):
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'your_email_password' # Use app password if 2FA enabled
Edit the project-level urls.py (project/urls.py) to route authentication URLs:
Python
from django.contrib import admin
from django.urls import path, include
from user import views as user_view
from django.contrib.auth import views as auth
urlpatterns = [
path('admin/', admin.site.urls),
##### user related path##########################
path('', include('user.urls')),
path('login/', user_view.Login, name ='login'),
path('logout/', auth.LogoutView.as_view(template_name ='user/index.html'), name ='logout'),
path('register/', user_view.register, name ='register'),
]
Create user/urls.py if it does not exist and add:
Python
from django.urls import path, include
from django.conf import settings
from . import views
from django.conf.urls.static import static
urlpatterns = [
path('', views.index, name ='index'),
]
Create a forms.py file inside the user app and add the following:
Python
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
phone_no = forms.CharField(max_length = 20)
first_name = forms.CharField(max_length = 20)
last_name = forms.CharField(max_length = 20)
class Meta:
model = User
fields = ['username', 'email', 'phone_no', 'password1', 'password2']
Step 7: Define Views for Registration and Login
Edit user/views.py to handle user registration, login, and rendering pages:
Python
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm
from .forms import UserRegisterForm
from django.core.mail import send_mail
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.template import Context
#################### index#######################################
def index(request):
return render(request, 'user/index.html', {'title':'index'})
########### register here #####################################
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
email = form.cleaned_data.get('email')
######################### mail system ####################################
htmly = get_template('user/Email.html')
d = { 'username': username }
subject, from_email, to = 'welcome', '[email protected]', email
html_content = htmly.render(d)
msg = EmailMultiAlternatives(subject, html_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
##################################################################
messages.success(request, f'Your account has been created ! You are now able to log in')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'user/register.html', {'form': form, 'title':'register here'})
################ login forms###################################################
def Login(request):
if request.method == 'POST':
# AuthenticationForm_can_also_be_used__
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username = username, password = password)
if user is not None:
form = login(request, user)
messages.success(request, f' welcome {username} !!')
return redirect('index')
else:
messages.info(request, f'account done not exit plz sign in')
form = AuthenticationForm()
return render(request, 'user/login.html', {'form':form, 'title':'log in'})
Step 8: Create HTML Templates
index.html
This template includes navigation, login/logout links, and dynamic welcome messages.
HTML
{% load static %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="title" content="project">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="language" content="English">
<meta name="author" content="vinayak sharma">
<title>{{title}}</title>
<!-- bootstrap file -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- bootstrap file-->
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- main css -->
<link rel="stylesheet" type="text/css" href="{% static "index.css" %}" />
<!-- message here -->
{% if messages %}
{% for message in messages %}
<script>
alert("{{ message }}");
</script>
{% endfor %}
{% endif %}
<!--_______________________________________________-->
</head>
<body class="container-fluid">
<header class="row">
<!-- navbar-->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button class="navbar-toggle" data-toggle="collapse" data-target="#mainNavBar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" class="styleheader" href="{% url "index" %}">project</a>
</div>
<div class="collapse navbar-collapse" id="mainNavBar">
<ul class="nav navbar-nav navbar-right">
<li><a href="{% url "index" %}">Home</a></li>
{% if user.is_authenticated %}
<li><a href="{% url "logout" %}"><span class="glyphicon glyphicon-log-out"></span> Logout</a></li>
{% else %}
<li><a href="{% url "register" %}"><span class="glyphicon glyphicon-user"></span> Sign up</a></li>
<li><a href="{% url "login" %}"><span class="glyphicon glyphicon-log-in"></span> Log in</a></li>
{% endif %}
</ul>
</div>
</div>
</nav>
</header>
<br/>
<br>
<br>
<div class="row">
{% block start %}
{% if user.is_authenticated %}
<center><h1>welcome back {{user.username}}!</h1></center>
{% else %}
<center><h1>log in, plz . . .</h1></center>
{% endif %}
{% endblock %}
</div>
</body>
</html>
Email.html
The provided HTML code is an email template for a registration confirmation message. It uses the Roboto font, has a centered thank-you message with user-specific content (username), and a horizontal line for separation. This template is designed to deliver a visually pleasing and informative confirmation email to users.
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style>
@import url('https://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900');
</style>
</head>
<body style="background: #f5f8fa;font-family: 'Roboto', sans-serif;">
<div style="width: 90%;max-width:600px;margin: 20px auto;background: #ffffff;">
<section style="margin: 0 15px;color:#425b76;">
<h2 style="margin: 40px 0 27px 0;text-align: center;">Thank you to registration</h2>
<hr style="border:0;border-top: 1px solid rgba(66,91,118,0.3);max-width: 50%">
<p style="font-size:15.5px;font-weight: bold;margin:40px 20px 15px 20px;">Hi {{username}}, we have received your details and will process soon.</p>
</section>
</div>
</body>
</html>
Login.html
Inside this block, it creates a centered login form with specific styling, including a black border, padding, and a rounded border. The form includes a CSRF token for security and uses the crispy filter to render form fields with enhanced formatting, along with a login button and a link to the registration page.
HTML
{% extends "user/index.html" %}
{% load crispy_forms_tags %}
{% block start %}
<div class="content-section col-md-8 col-md-offset-2">
<center>
<form method="POST" style="border: 1px solid black; margin: 4%; padding:10%; border-radius:1%;">
{% csrf_token %}
<fieldset class="form-group">
{{ form|crispy}}
</fieldset>
<center>
<button style="background: black; font-size: 2rem; padding:1%;" class="btn btn-outline-info" type="submit"><span class="glyphicon glyphicon-log-in"></span> login</button>
</center>
<br/>
<sub style="text-align: left;"><a href="{% url 'register' %}" style="text-decoration: none; color: blue; padding:2%; cursor:pointer; margin-right:2%;">don't have account,sign up</a></sub>
</form>
</center>
</div>
{% endblock start %}
Register.html
This file creates a centered sign-up form with specific styling, including a black border, padding, and rounded corners. The form includes a CSRF token for security and uses the crispy filter for enhanced form field rendering, along with a sign-up button and a link to the login page for users with existing accounts.
Python
{% extends "user/index.html" %}
{% load crispy_forms_tags %}
{% block start %}
<div class="content-section col-md-8 col-md-offset-2">
<form method="POST" style="border: 1px solid black; margin: 4%; padding:10%; border-radius:1%;">
{% csrf_token %}
<fieldset class="form-group">
{{ form|crispy}}
</fieldset>
<center>
<button style="background: black; padding:2%; font-size: 2rem; color:white;" class="btn btn-outline-info" type="submit"><span class="glyphicon glyphicon-check"></span> sign up</button>
</center>
<br />
<sub><a href="{% url "login" %}" style="text-decoration: none; color: blue; padding:3%; cursor:pointer;">Already have an account ?</a></sub>
</form>
</div>
{% endblock start %}
Step 9: How to Generate a Gmail App Password (For Sending Emails)
To securely send emails through Gmail SMTP from your Django application, you need to generate an App Password and set up email confirmation to verify users during registration.
Generating a Gmail App Password
1. Go to your Google Account security settings:
Open this URL in your browser:
https://accounts.google.com/v3/signin/identifier?continue=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fmyaccount.google.com%2Fgeneral-light&followup=https%3A%2F%2Ffanyv88.com%3A443%2Fhttps%2Fmyaccount.google.com%2Fgeneral-light&ifkv=AdBytiNmhNybpYPAImjtZLcI61txPrTgaUw9MCf3aLoVpjsgQYJY29MO_P2wZBJjIk5zQShayFmp&osid=1&passive=1209600&flowName=WebLiteSignIn&flowEntry=ServiceLogin&dsh=S-734960398%3A1752268640094531
2. Verify that 2-Step Verification is enabled:
- Under “Signing in to Google”, check if 2-Step Verification is ON.
- If it is not enabled, click on it and follow the instructions to enable it for your account.
3. Create an App Password:
- After enabling 2-Step Verification, return to the Security page.
- Click on App passwords (this option appears only if 2FA is enabled).
- Under Select app, choose Other (Custom name).
- Enter a name such as Django App and click Generate.
- Google will generate a 16-character app password (e.g., abcd efgh ijkl mnop).
- Copy this app password carefully and remove any spaces when you paste it into your Django settings.
4. Use the App Password in your Django settings.py:
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'your_16_character_app_password_without_spaces'
Step 10: Make Migrations and Run Server
Run migrations:
python manage.py makemigrations
python manage.py migrate
Run your server:
python manage.py runserver
Login PageVerification mail after successful login:
Confirmation Mail
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Fundamentals
Python IntroductionPython was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in PythonUnderstanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython's input() function
7 min read
Python VariablesIn Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Python OperatorsIn Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /,
6 min read
Python KeywordsKeywords in Python are reserved words that have special meanings and serve specific purposes in the language syntax. Python keywords cannot be used as the names of variables, functions, and classes or any other identifier. Getting List of all Python keywordsWe can also get all the keyword names usin
2 min read
Python Data TypesPython Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Conditional Statements in PythonConditional statements in Python are used to execute certain blocks of code based on specific conditions. These statements help control the flow of a program, making it behave differently in different situations.If Conditional Statement in PythonIf statement is the simplest form of a conditional sta
6 min read
Loops in Python - For, While and Nested LoopsLoops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). In this article, we will look at Python loops and understand their working with the help of examples. For Loop in PythonFor loops is used to iterate ov
9 min read
Python FunctionsPython Functions is a block of statements that does a specific task. The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over an
9 min read
Recursion in PythonRecursion involves a function calling itself directly or indirectly to solve a problem by breaking it down into simpler and more manageable parts. In Python, recursion is widely used for tasks that can be divided into identical subtasks.In Python, a recursive function is defined like any other funct
6 min read
Python Lambda FunctionsPython Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python. In the example, we defined a lambda function(u
6 min read
Python Data Structures
Python StringA string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut
6 min read
Python ListsIn Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Python TuplesA tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
6 min read
Dictionaries in PythonPython dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
7 min read
Python SetsPython set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can change.Creating a Set in PythonIn Python, the most basic and efficient method for creating
10 min read
Python ArraysLists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences:Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
9 min read
List Comprehension in PythonList comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.For example,
4 min read
Advanced Python
Python OOPs ConceptsObject Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. OOPs is a way of organizing code that uses objects and classes to represent real-world entities and their behavior. In OOPs, object has attributes thing th
11 min read
Python Exception HandlingPython Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let's look at an example:Handl
6 min read
File Handling in PythonFile handling refers to the process of performing operations on a file, such as creating, opening, reading, writing and closing it through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
4 min read
Python Database TutorialPython being a high-level language provides support for various databases. We can connect and run queries for a particular database using Python and without writing raw queries in the terminal or shell of that particular database, we just need to have that database installed in our system.A database
4 min read
Python MongoDB TutorialMongoDB is a popular NoSQL database designed to store and manage data flexibly and at scale. Unlike traditional relational databases that use tables and rows, MongoDB stores data as JSON-like documents using a format called BSON (Binary JSON). This document-oriented model makes it easy to handle com
2 min read
Python MySQLMySQL is a widely used open-source relational database for managing structured data. Integrating it with Python enables efficient data storage, retrieval and manipulation within applications. To work with MySQL in Python, we use MySQL Connector, a driver that enables seamless integration between the
9 min read
Python PackagesPython packages are a way to organize and structure code by grouping related modules into directories. A package is essentially a folder that contains an __init__.py file and one or more Python files (modules). This organization helps manage and reuse code effectively, especially in larger projects.
12 min read
Python ModulesPython Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we c
7 min read
Python DSA LibrariesData Structures and Algorithms (DSA) serve as the backbone for efficient problem-solving and software development. Python, known for its simplicity and versatility, offers a plethora of libraries and packages that facilitate the implementation of various DSA concepts. In this article, we'll delve in
15 min read
List of Python GUI Library and PackagesGraphical User Interfaces (GUIs) play a pivotal role in enhancing user interaction and experience. Python, known for its simplicity and versatility, has evolved into a prominent choice for building GUI applications. With the advent of Python 3, developers have been equipped with lots of tools and li
11 min read
Data Science with Python
NumPy Tutorial - Python LibraryNumPy (short for Numerical Python ) is one of the most fundamental libraries in Python for scientific computing. It provides support for large, multi-dimensional arrays and matrices along with a collection of mathematical functions to operate on arrays.At its core it introduces the ndarray (n-dimens
3 min read
Pandas TutorialPandas is an open-source software library designed for data manipulation and analysis. It provides data structures like series and DataFrames to easily clean, transform and analyze large datasets and integrates with other Python libraries, such as NumPy and Matplotlib. It offers functions for data t
6 min read
Matplotlib TutorialMatplotlib is an open-source visualization library for the Python programming language, widely used for creating static, animated and interactive plots. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, Qt, GTK and wxPython. It
5 min read
Python Seaborn TutorialSeaborn is a library mostly used for statistical plotting in Python. It is built on top of Matplotlib and provides beautiful default styles and color palettes to make statistical plots more attractive.In this tutorial, we will learn about Python Seaborn from basics to advance using a huge dataset of
15+ min read
StatsModel Library- TutorialStatsmodels is a useful Python library for doing statistics and hypothesis testing. It provides tools for fitting various statistical models, performing tests and analyzing data. It is especially used for tasks in data science ,economics and other fields where understanding data is important. It is
4 min read
Learning Model Building in Scikit-learnBuilding machine learning models from scratch can be complex and time-consuming. Scikit-learn which is an open-source Python library which helps in making machine learning more accessible. It provides a straightforward, consistent interface for a variety of tasks like classification, regression, clu
8 min read
TensorFlow TutorialTensorFlow is an open-source machine-learning framework developed by Google. It is written in Python, making it accessible and easy to understand. It is designed to build and train machine learning (ML) and deep learning models. It is highly scalable for both research and production.It supports CPUs
2 min read
PyTorch TutorialPyTorch is an open-source deep learning framework designed to simplify the process of building neural networks and machine learning models. With its dynamic computation graph, PyTorch allows developers to modify the networkâs behavior in real-time, making it an excellent choice for both beginners an
7 min read
Web Development with Python
Flask TutorialFlask is a lightweight and powerful web framework for Python. Itâs often called a "micro-framework" because it provides the essentials for web development without unnecessary complexity. Unlike Django, which comes with built-in features like authentication and an admin panel, Flask keeps things mini
8 min read
Django Tutorial | Learn Django FrameworkDjango is a Python framework that simplifies web development by handling complex tasks for you. It follows the "Don't Repeat Yourself" (DRY) principle, promoting reusable components and making development faster. With built-in features like user authentication, database connections, and CRUD operati
10 min read
Django ORM - Inserting, Updating & Deleting DataDjango's Object-Relational Mapping (ORM) is one of the key features that simplifies interaction with the database. It allows developers to define their database schema in Python classes and manage data without writing raw SQL queries. The Django ORM bridges the gap between Python objects and databas
4 min read
Templating With Jinja2 in FlaskFlask is a lightweight WSGI framework that is built on Python programming. WSGI simply means Web Server Gateway Interface. Flask is widely used as a backend to develop a fully-fledged Website. And to make a sure website, templating is very important. Flask is supported by inbuilt template support na
6 min read
Django TemplatesTemplates are the third and most important part of Django's MVT Structure. A Django template is basically an HTML file that can also include CSS and JavaScript. The Django framework uses these templates to dynamically generate web pages that users interact with. Since Django primarily handles the ba
7 min read
Python | Build a REST API using FlaskPrerequisite: Introduction to Rest API REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Fla
3 min read
How to Create a basic API using Django Rest Framework ?Django REST Framework (DRF) is a powerful extension of Django that helps you build APIs quickly and easily. It simplifies exposing your Django models as RESTfulAPIs, which can be consumed by frontend apps, mobile clients or other services.Before creating an API, there are three main steps to underst
4 min read
Python Practice
Python QuizThese Python quiz questions are designed to help you become more familiar with Python and test your knowledge across various topics. From Python basics to advanced concepts, these topic-specific quizzes offer a comprehensive way to practice and assess your understanding of Python concepts. These Pyt
3 min read
Python Coding Practice ProblemsThis collection of Python coding practice problems is designed to help you improve your overall programming skills in Python.The links below lead to different topic pages, each containing coding problems, and this page also includes links to quizzes. You need to log in first to write your code. Your
1 min read
Python Interview Questions and AnswersPython is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read