Django Custom User Model SignUp, Login and Logout
In this article, you will learn to implement a Django custom user model that allows a user to signup, login and logout.
Do you want to implement signup, login and logout features in your application? If you develop this process from scratch, it will take lots of development time and testing effort. Django provides built-in user models and an authentication system, which is great. The Django custom user model is a solid solution for authentication and storing data about users. It allows us to modify the login behaviour of users, like instead of login with a username and password, they can login with an email and password.
Here, we have mentioned a simple approach to begin a new Django project with the custom user model implementation.
Setup a new project and application
We have created a new empty project 'teamwork' and a new app 'users'-
(env) c:\python37\Scripts\projects>django-admin startproject teamwork
(env) c:\python37\Scripts\projects>cd teamwork
(env) c:\python37\Scripts\projects\teamwork>django-admin startapp users
Install django-crispy-forms
The 'Django-crispy-forms' is an application that helps to manage Django forms. It allows us to easily add and render Bootstrap 4 styled forms. It limits the Django forms in just one line of code, which makes rendering the form template really easy. The following command installs django-crispy-forms using the package manager pip-
pip install django-crispy-forms
settings.py
After creating the app and installing the crispy-forms, we need to mention these in the configuration. So, we have edited the settings file and added the name of the application and the name of the installed 'crispy-forms' to the INSTALLED_APPS list.
INSTALLED_APPS = [
.......
......
'users.apps.UsersConfig',
'crispy_forms',
]
AUTH_USER_MODEL = 'users.TeamUser'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
We have also separately defined constants for the 'Login' and 'Logout' redirect pages.
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
Configure Database
Here, we have changed the database configuration settings for the MySQL database.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'teamwork',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306'
}
}
Project Structure
Here is the folders and files structure of this project-
models.py
Here, we have created a custom user model in 'models.py' by extending AbstractUser. The AbstractUser provides the full implementation of the default user as an abstract model.
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class TeamUser(AbstractUser):
pass
forms.py
In a similar way that a model class's fields map to database fields, a form class's fields map to HTML form elements. Here, we have created a UserCreationForm 'forms.py' under 'users' app.
The Django authentication framework provides a form named UserCreationForm. To use UserCreationForm, we have to first import it from django.contrib.auth.forms as follows.
from django import forms
from django.contrib.auth.forms
import UserCreationForm
from .models import TeamUser
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = TeamUser
fields = ('username')
views.py
In the 'views.py', we have imported the 'TeamUserForm' form. Next, we define a class 'TeamSignUp' for rendering the pages.
from django.shortcuts import render
# Create your views here.
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView
from .forms import TeamUserForm
class TeamSignUp(CreateView):
form_class = TeamUserForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
urls.py
In the users app (teamwork/users/), we have created a file 'urls.py' and added the following URL pattern.
teamwork/users/urls.pyfrom django.urls import path
from .views import TeamSignUp
urlpatterns = [
path('signup/', TeamSignUp.as_view(), name='signup'),
]
Next, we have edited the 'urls.py' file, located in 'teamwork/teamwork/' and added the following URL patterns.
teamwork/teamwork/urls.pyfrom django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('', TemplateView.as_view(template_name='home.html'), name='home'),
path('users/', include('users.urls')),
path('users/', include('django.contrib.auth.urls')),
]
Templates
Next, we have created a template folder in 'teamwork/user/' and placed the following HTML files.
base.htmlThis HTML file includes the Bootstrap 4 file. We have specified one block for content, which will be included further.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{% block title %}Django Custom User Model{% endblock %}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<main>
{% block content %}
{% endblock %}
</main>
</body>
</html>
Django custom dashboard
home.htmlNext, we have created a new template 'home.html' in the users app with the following code. Above, we have set this page as Login and Logout redirect url. At first, we have included the 'base.html' page at the top and then added '{% load crispy_forms_tags %}' to the template and appended the |crispy filter to your form.
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %}Home{% endblock %}
{% block content %}
<div style="width: 450px; margin: 0 auto; padding: 10px;">
{% if user.is_authenticated %}
Hi {{ user.username }}!
<p><a href="{% url 'logout' %}">Logout</a></p>
{% else %}
<h2>Welcome to Teamwork</h2>
<p>Login or Create your account</p>
<a href="{% url 'login' %}" class="btn btn-primary">Login</a>
<a href="{% url 'signup' %}" class="btn btn-primary">SignUp</a>
{% endif %}
</div>
{% endblock %}
Django custom signup form
signup.htmlWhen the user clicked on the 'SignUp' button, the following form will display.
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %}Sign Up{% endblock %}
{% block content %}
<div style="width: 450px; margin: 0 auto; padding: 10px;">
<h2>SignUp Form</h2>
<form method="post" >
{% csrf_token %}
{{ form|crispy}}
<button type="submit" class="btn btn-primary">Sign Up</button>
</form>
</div>
{% endblock %}
Django custom login form
login.htmlNext, we have created a 'registration' folder in 'teamwork/user/template' and placed the following HTML file 'login.html'. When the user clicks on the 'Login' button, the following login form will display.
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block title %}Login{% endblock %}
{% block content %}
<div style="width: 450px; margin: 0 auto; padding: 10px;">
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form|crispy}}
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
{% endblock %}
Related Articles
Python | Uploading images in DjangoDjango pass variable from view to HTML template
How to read and write a file using Django
Django serialize queryset into JSON and display in template
Django Export Model Data to CSV
Django Custom User Model SignUp, Login and Logout
How to display image from database in Django
Django Pagination with Ajax and jQuery
Django download file
Django Simple File Upload
Django ajax GET and POST request
Django bootstrap 4 form template
Django upload image to database
Windows command to create and run first Django app
Django Send Mail on Contact form submission
How to insert data in MySQL database from an HTML form using Django
Convert MySQL query result to JSON in Python
Display data from MySQL in HTML table using Python
Insert XML Data to MySQL Table using Python
CRUD operations in Python using MYSQL Connector