In this article, we are going to see How to build Django User Registration using the auth module in Django. Django framework comes with necessary features to set up a complete user authentication using auth module. We will make a complete user registration system where users can register(Sign up), log in using the credentials, and can logout from the system. We will build:
- Registration
- Login
- Logout
Prerequisites:
- Installation of Python and Basic knowledge of Python
- Knowledge of Django Framework
- HTML, CSS and BootStrap
- Start a New Project
1. Start a New Project
Step.1 Create a Django Project
First, you will have to create a Django project where we will make a registration app. So to do this, copy the below code and run it in your Command Prompt(CMD) where you want to create your Django folder.
django-admin startproject login_register_project
Step.2 Create a Django App
We have successfully created our project. To create your app, make sure you’re in the same directory as manage.py or type this command to go at manage.py:
cd login_register_project
To Create Django App run this command in your Command Prompt:
python manage.py startapp accounts
Notice: Our project name is “login_register_project” and our app name is “accounts”. Now you can see below folder structure in your text editor.
Step.3 Update your settings.py file
After creating an app, make sure you have added your app in settings.py so that it can be picked up while running the server on the web browser.
login_register_project > login_register_project > settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
]
Step.4 Create forms.py in App for UserCreationForm
login_register_project > accounts > new file(forms.py)
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import User
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
First, we are going to create a file “forms.py” in-app folder(accounts). And add these codes in that file. Here, UserCreationForm is used to create new users for registration purposes.
Step.5 Create urls.py in App
login_register_project > accounts > urls.py
Create a file “urls.py” in the App folder(accounts)
Step.6 Update your project urls.py file
Now Add app “urls.py” in project “urls.py” and below code.
login_register_project > login_register_project > urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('accounts.urls')),
]
Step.7 Makemigrations and Migrate
So now it’s time to make migrations and migrate our app, for this copy the below command and run it in your Command Prompt in the same folder where manage.py is saved.
For Migrations:
python manage.py makemigrations
For Migrate:
python manage.py migrate
2. Creating Home Page(home.html)
First, create a folder “templates’ in the app folder(accounts) after that create again a folder “accounts” in templates. Make sure you have given the name of the folder right. After creating accounts/templates/accounts folder create a file “home.html” in accounts/templates/accounts. Here we will create all HTML pages which are known as templates. In this code, we have created a navbar, and footer with design. Now add the below code in home.html:
login_register_project > accounts > templates > accounts > home.html
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<title> Dev Duniya </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.8/css/all.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<style>
.fa {
padding: 5px;
font-size: 25px;
width: 50px;
}
.inputfield input{
margin-bottom: 10px;
}
.inputlabel label{
margin-bottom: 17px;
}
.wrapper{
text-align: center;
padding-top: 8em;
font-size: 29px;
}
</style>
</head>
<body>
<div>
<nav class="navbar navbar bg-primary navbar-dark">
<div class="col-sm-6">
<a class="navbar-brand" href="/"> Dev Duniya </a>
</div>
<div class="col-sm-6" style="text-align:right;">
<a class="navbar-brand" href="/"> Home </a>
{% if user.is_authenticated %}
<a class="navbar-brand" href="/logout">LOGOUT</a>
<a class="navbar-brand" href="/">Welcome-{{user.username}}</a>
{% else %}
<a class="navbar-brand" href="/loginpage"> Login </a>
<a class="navbar-brand" href="/registerpage"> Register </a>
{% endif %}
</div>
</div>
</nav>
</div>
{% include 'accounts/message.html' %}
<div style="min-height: 90vh">
{% block content %}
<div class="wrapper">
<h2>Dev Duniya</h2>
<h4>Login and Register Project</h4>
</div>
{% endblock %}
</div>
<footer
class="text-center text-lg-start text-white"
style="background-color: #1c2331"
>
<section
class="d-flex justify-content-between p-4"
style="background-color: #6351ce"
>
<div class="me-5">
<span>Get connected with us on social networks:</span>
</div>
<div style="padding-right:50px;">
<a href="https://www.facebook.com/bestcodecreator" class="text-white me-4" style="margin-right:8px;">
<i class="fab fa-facebook-f"></i>
</a>
<a href="https://twitter.com/expoashish" class="text-white me-4" style="margin-right:8px;">
<i class="fab fa-twitter"></i>
</a>
<a href="https://www.google.com/" class="text-white me-4" style="margin-right:8px;">
<i class="fab fa-google"></i>
</a>
<a href="https://www.instagram.com/expoashish/" class="text-white me-4" style="margin-right:8px;">
<i class="fab fa-instagram"></i>
</a>
<a href="https://www.linkedin.com/in/expoashish/" class="text-white me-4" style="margin-right:8px;">
<i class="fab fa-linkedin"></i>
</a>
<a href="https://github.com/expoashish " class="text-white me-4" style="margin-right:8px;">
<i class="fab fa-github"></i>
</a>
</div>
</section>
<section class="">
<div class="container text-md-start mt-5">
<div class="row mt-3">
<div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
<h6 class="text-uppercase fw-bold">DevDuniya</h6>
<hr
class="mb-4 mt-0 d-inline-block mx-auto"
style="width: 60px; background-color: #7c4dff; height: 2px"
/>
<p style="text-align:left;">
Login and Register Project in DJango
</p>
</div>
<div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4 text-left">
<h6 class="text-uppercase fw-bold">Pages</h6>
<hr
class="mb-4 mt-0 d-inline-block mx-auto"
style="width: 60px; background-color: #7c4dff; height: 2px"
/>
<div style="text-align:left;">
<a href="/" class="text-white">Home</a><br>
</div>
</div>
<div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4 text-left" >
<h6 class="text-uppercase fw-bold">Contact</h6>
<hr
class="mb-4 mt-0 d-inline-block mx-auto"
style="width: 60px; background-color: #7c4dff; height: 2px"
/>
<div style="text-align:left;">
<p><i class="fas fa-home mr-3"></i> New Delhi, ND 110082, INDIA</p>
<p><i class="fas fa-envelope mr-3"></i> mail@devduniya.com</p>
<p><i class="fas fa-phone mr-3"></i> +91 9876543289</p>
<p><i class="fas fa-print mr-3"></i> +91 9878979556</p>
</div>
</div>
</div>
</div>
</section>
<div
class="text-center p-3"
style="background-color: rgba(0, 0, 0, 0.2)"
>
<a class="text-white" href="/"
>DevDuniya</a
>
</div>
</footer>
</div>
</body>
</html>
Now it’s to update the app “urls.py” for home page navigation. So copy the below code and add it to the accounts/urls.py file.
login_register_project > accounts > urls.py
urls.py
from django.urls import path
from . import views
app_name='accounts'
urlpatterns = [
path('', views.home, name='home'),
]
4. Creating a view of the home
We have created home.html and updated the accounts/urls.py file. Now add the below code in the accounts/views.py file.
login_register_project > accounts > views.py
views.py
from django.shortcuts import render,redirect,get_object_or_404
from .forms import *
from django.http import HttpResponse,HttpResponseRedirect
# Create your views here.
def home( request):
return render(request, 'accounts/home.html')
5. Run the Django Development server
As we have created our home page with views.py and updated urls.py for navigation. Now run the Django development server, to do this copy the below command and run it in your accounts folder:
python manage.py runserver
Now go to your browser, visit http://127.0.0.1:8000/ in your web browser. You will see a beautiful design with a navbar and footer.
6. Create a register and login page
Now we are going to create a register and login page in accounts/templates/accounts. So we will create registerpage.html and loginpage.html, and add the below code in these files.
login_register_project > accounts > templates > accounts > registerpage.html
registerpage.html
{% extends './home.html' %}
<!DOCTYPE html>
<html>
{% block content %}
<head>
<title>Login</title>
<style>
.mainclass {
background: #84fab0;
background: -webkit-linear-gradient(to right, rgba(132, 250, 176, 0.5), rgba(143, 211, 244, 0.5));
background: linear-gradient(to right, rgba(132, 250, 176, 0.5), rgba(143, 211, 244, 0.5))
}
.gradient-custom-4 {
background: #84fab0;
background: -webkit-linear-gradient(to right, rgba(132, 250, 176, 1), rgba(143, 211, 244, 1));
background: linear-gradient(to right, rgba(132, 250, 176, 1), rgba(143, 211, 244, 1))
}
</style>
</head>
<body class="mainclass">
<section>
<div class="mask d-flex align-items-center h-100 " style="padding-top:20px;">
<div class="container h-100">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-12 col-md-9 col-lg-7 col-xl-6">
<div class="card" style="border-radius: 15px;">
<div class="card-body p-5">
<h2 class="text-uppercase text-center mb-5"><b>SIGN UP</b></h2>
<form method="POST", enctype="multipart/form-data" class="inputfield">
{% csrf_token %}
<div class="row">
<div class="col-sm-6 text-left inputlabel">
<label>Username</label></br>
<label>Email</label></br>
<label >Password</label></br>
<label>Confirm Password</label>
</div>
<div class="col-sm-6 text-right">
{{form.username}}
{{form.email}}
{{form.password1}}
{{form.password2}}
</div>
</div>
<div class="d-flex justify-content-center" style="padding: 25px 150px;">
<button type="submit" class="btn btn-success btn-block btn-lg gradient-custom-4 text-body" value="Submit">Register</button>
</div>
<p class="text-center text-muted mt-5 mb-0">Have already an account? <a href="{% url 'accounts:loginpage' %}" class="fw-bold text-body"><u>Login here</u></a></p>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</body>
{% endblock %}
</html>
login_register_project > accounts > templates > accounts > loginpage.html
loginpage.html
{% extends './home.html' %}
<!DOCTYPE html>
<html>
{% block content %}
<head>
<title>Login</title>
<style>
.mainclass {
background: #84fab0;
background: -webkit-linear-gradient(to right, rgba(132, 250, 176, 0.5), rgba(143, 211, 244, 0.5));
background: linear-gradient(to right, rgba(132, 250, 176, 0.5), rgba(143, 211, 244, 0.5))
}
.gradient-custom-4 {
background: #84fab0;
background: -webkit-linear-gradient(to right, rgba(132, 250, 176, 1), rgba(143, 211, 244, 1));
background: linear-gradient(to right, rgba(132, 250, 176, 1), rgba(143, 211, 244, 1))
}
</style>
</head>
<body>
<section class="mainclass">
<div class="container py-5 h-100">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-12 col-md-8 col-lg-6 col-xl-5">
<div class="card shadow-2-strong" style="border-radius: 1rem;">
<div class="card-body p-5 text-center">
<h3 class="mb-5"><b>Login</b></h3>
<form method="POST", enctype="multipart/form-data" class="inputfield">
{% csrf_token %}
<div class="row">
<div class="col-sm-6 text-left inputlabel">
<label class="form-label" for="typePasswordX-2">Username</label></br>
<label class="form-label" for="typePasswordX-2">Password</label>
</div>
<div class="col-sm-6 text-right ">
{{form.username}}</br>
{{form.password1}}
</div>
</div>
<div class="d-flex justify-content-center" style="padding: 25px 100px;">
<button type="submit" class="btn btn-success btn-block btn-lg gradient-custom-4 text-body" value="Submit">Login</button>
</div>
<p class="text-center text-muted mt-5 mb-0">Have Not an account? <a href="{% url 'accounts:registerpage' %}" class="fw-bold text-body"><u>Register Here</u></a></p>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
</body>
{% endblock %}
</html>
Now Update App Urls for register, login, and logout navigation.
login_register_project > accounts > urls.py
urls.py
from django.urls import path
from . import views
app_name='accounts'
urlpatterns = [
path('loginpage/', views.loginPage, name="loginpage"),
path('registerpage/', views.registerPage, name="registerpage"),
path('logout/', views.logoutUser, name="logout"),
path('', views.home, name='home'),
]
8. Create a View for register, login, and logout
We have created our pages and URLs for navigation, now it’s time to create a view for registering, login in, and logout. Copy the below code and paste it into your accounts/views.py file.
login_register_project > accounts > views.py
views.py
from django.shortcuts import render,redirect,get_object_or_404
from .forms import *
from django.http import HttpResponse,HttpResponseRedirect
from .forms import CreateUserForm
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
# Create your views here.
def loginPage(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password1']
user = authenticate(request, username = username, password = password)
if user is not None:
form = login(request, user)
messages.success(request, f' wecome {username} !!')
return redirect('accounts:home')
else:
messages.info(request, f'account done not exit plz sign in')
form = CreateUserForm()
return render(request, 'accounts/loginpage.html', {'form':form, 'title':'log in'})
def registerPage(request):
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, f'Your account has been created. You can log in now!')
return redirect('accounts:home')
else:
form = CreateUserForm()
return render(request, 'accounts/registerpage.html', {'form' : form})
@login_required
def logoutUser(request):
logout(request)
messages.info(request, "Logged out successfully!")
return redirect("accounts:home")
def home( request):
return render(request, 'accounts/home.html')
9. Adding Success and Error Messages
I want to add success and error messages while registering and login in, so to do this, we will have to create a “message.html” file in accounts/templates/accounts. Copy the below code and add it to the message.html file.
login_register_project > accounts > templates > accounts > message.html
message.html
{% for message in messages %}
<div class="alert {{ message.tags }} alert-dismissible" role="alert" style="position: absolute;
z-index: 1;
right: 0px;
background-color: skyblue;
top: 88px;">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ message }}
</div>
</div>
{% endfor %}
10 Now Update the “home.html” file
We have create “registerpage.html” , “loginpage.html” , “logout” and “message.html”. So these files should navigate from home. For this, we will have to update our “home.html” file. Copy the below code and update the “home.html” file.
login_register_project > accounts > templates > accounts > home.html
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<title> Dev Duniya </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.8/css/all.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<style>
.fa {
padding: 5px;
font-size: 25px;
width: 50px;
}
.inputfield input{
margin-bottom: 10px;
}
.inputlabel label{
margin-bottom: 17px;
}
.wrapper{
text-align: center;
padding-top: 8em;
font-size: 29px;
}
</style>
</head>
<body>
<div>
<nav class="navbar navbar bg-primary navbar-dark">
<div class="col-sm-6">
<a class="navbar-brand" href="/"> Dev Duniya </a>
</div>
<div class="col-sm-6" style="text-align:right;">
<a class="navbar-brand" href="/"> Home </a>
{% if user.is_authenticated %}
<a class="navbar-brand" href="/logout">LOGOUT</a>
<a class="navbar-brand" href="/">Welcome-{{user.username}}</a>
{% else %}
<a class="navbar-brand" href="/loginpage"> Login </a>
<a class="navbar-brand" href="/registerpage"> Register </a>
{% endif %}
</div>
</div>
</nav>
</div>
{% include 'accounts/message.html' %}
<div style="min-height: 90vh">
{% block content %}
<div class="wrapper">
<h2>Dev Duniya</h2>
<h4>Login and Register Project</h4>
</div>
{% endblock %}
</div>
<footer
class="text-center text-lg-start text-white"
style="background-color: #1c2331"
>
<section
class="d-flex justify-content-between p-4"
style="background-color: #6351ce"
>
<div class="me-5">
<span>Get connected with us on social networks:</span>
</div>
<div style="padding-right:50px;">
<a href="https://www.facebook.com/bestcodecreator" class="text-white me-4" style="margin-right:8px;">
<i class="fab fa-facebook-f"></i>
</a>
<a href="https://twitter.com/expoashish" class="text-white me-4" style="margin-right:8px;">
<i class="fab fa-twitter"></i>
</a>
<a href="https://www.google.com/" class="text-white me-4" style="margin-right:8px;">
<i class="fab fa-google"></i>
</a>
<a href="https://www.instagram.com/expoashish/" class="text-white me-4" style="margin-right:8px;">
<i class="fab fa-instagram"></i>
</a>
<a href="https://www.linkedin.com/in/expoashish/" class="text-white me-4" style="margin-right:8px;">
<i class="fab fa-linkedin"></i>
</a>
<a href="https://github.com/expoashish " class="text-white me-4" style="margin-right:8px;">
<i class="fab fa-github"></i>
</a>
</div>
</section>
<section class="">
<div class="container text-md-start mt-5">
<div class="row mt-3">
<div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
<h6 class="text-uppercase fw-bold">DevDuniya</h6>
<hr
class="mb-4 mt-0 d-inline-block mx-auto"
style="width: 60px; background-color: #7c4dff; height: 2px"
/>
<p style="text-align:left;">
Login and Register Project in DJango
</p>
</div>
<div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4 text-left">
<h6 class="text-uppercase fw-bold">Pages</h6>
<hr
class="mb-4 mt-0 d-inline-block mx-auto"
style="width: 60px; background-color: #7c4dff; height: 2px"
/>
<div style="text-align:left;">
<a href="/" class="text-white">Home</a><br>
</div>
</div>
<div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4 text-left" >
<h6 class="text-uppercase fw-bold">Contact</h6>
<hr
class="mb-4 mt-0 d-inline-block mx-auto"
style="width: 60px; background-color: #7c4dff; height: 2px"
/>
<div style="text-align:left;">
<p><i class="fas fa-home mr-3"></i> New Delhi, ND 110082, INDIA</p>
<p><i class="fas fa-envelope mr-3"></i> mail@devduniya.com</p>
<p><i class="fas fa-phone mr-3"></i> +91 9876543289</p>
<p><i class="fas fa-print mr-3"></i> +91 9878979556</p>
</div>
</div>
</div>
</div>
</section>
<div
class="text-center p-3"
style="background-color: rgba(0, 0, 0, 0.2)"
>
<a class="text-white" href="/"
>DevDuniya</a
>
</div>
</footer>
</div>
</body>
</html>
11. Now Run the Django Development server
We have successfully created a Django User Registration System. It’s time to run the server and see our work. Now go to your browser, visit http://127.0.0.1:8000/ in your web browser. You will see our login, register, and home page with the best design.
12. Testing register, login, and logout pages
So, we have created a registration system, now it’s time to test it. I have included some images for this purpose.
Home Page Without Login:
Footer:
Home Page After Login:
Conclusion:
We have successfully created a user registration system using auth module in Django. We have created a register, login, logout, and message system in Django.
If you have any queries related to this article, then you can ask in the comment section, we will contact you soon, and Thank you for reading this article.
Follow me to receive more useful content:
Instagram | Twitter | Linkedin | Youtube
Thank you
Thanks for fantastic info. What trips can you recommend in 2024? Astro tourism, eco diving, home swapping, train stations are the new food destinations,sports tourism, coolcationing, gig tripping, private group travel?
Thanks for one’s marvelous posting! I seriously enjoyed reading it, you are a great
author.I will always bookmark your blog and
will eventually come back sometime soon. I want to encourage that you continue
your great work, have a nice weekend!
Hello my family member! I want to say that this post is awesome,
nice written and come with almost all important infos. I would like to see extra posts like this .
I think the admin of this website is actually working hard in support
of his website, for the reason that here every material is quality
based data.
This is my first time go to see at here and i am
actually impressed to read everthing at one place.
I like it whenever people come together and share opinions.
Great website, stick with it!
Hello there! I just wish to give you a big thumbs
up for your excellent information you have right here on this post.
I am returning to your blog for more soon.
you’re actually a good webmaster. The web site loading pace is incredible.
It sort of feels that you are doing any distinctive trick.
Also, The contents are masterpiece. you’ve done a fantastic activity on this matter!
I enjoy reading through a post that will make people think.
Also, thank you for permitting me to comment!
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Great goods from you, man. I have be aware your stuff prior to and you are just extremely wonderful.
I actually like what you have obtained right here, really like what you’re stating and the best way during which
you say it. You are making it entertaining and you still take care of to keep it wise.
I cant wait to learn far more from you. That is
really a terrific web site.