Django Custom Login And Registration Example

Published On: 18/07/2022 | Category: Django Python


Hi Dev,

I am going to explain you example of django custom login and registration example. I’m going to show you about how to create login and registration in django. I would like to share with you django login and registration example. you will learn django login and registration with mysql database. Follow bellow tutorial step of django custom user registration form.

So, as you may have seen, django comes with a built-in user registration form. we just need to configure it to our needs.

Django comes with a pre-built register form called UserCreationForm that connects to the pre-built model User. However, the UserCreationForm only requires a username and password (password1 is the initial password and password2 is the password confirmation).

Here i explained simply step by step let's see bellow example i’m going to show you about how to create login and registration in django.

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2 : Create a App
python3 manage.py startapp core
Step 3 : Update setting.py

Here, do not forget to register the new app in the settings.py file. Under installed apps, just add ‘users’ to the list:

And another one add this logout redirect url in settings.py file while you are logout automatically redirect to the login page.

....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]

LOGOUT_REDIRECT_URL = "login"
Step 4 : Database Setup

Next step, we will modify the settings.py file and update the database settings to configure the mydb database:

settings.py
DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
        'USER':'root',  
        'PASSWORD':'root',  
        'HOST':'localhost',  
        'PORT':'3306'  
    }  
}  
Step 5: Create a Form

In this step We need to create a form that will be used in our user registration process. There is a default Django form called UserCreationForm, that is available for this process. Only problem is the form has limited fields, plus we need to add custom styling.

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class SignUpForm(UserCreationForm):
    username = forms.CharField(
        widget=forms.TextInput(
            attrs={
                "placeholder": "Username",
                "class": "form-control"
            }
        ),error_messages={
               'required': 'The username field is required.'
        })
    email = forms.EmailField(
        widget=forms.EmailInput(
            attrs={
                "placeholder": "Email",
                "class": "form-control"
            }
        ),error_messages={
               'required': 'The email field is required.'
        })
    password1 = forms.CharField(
        widget=forms.PasswordInput(
            attrs={
                "placeholder": "Password",
                "class": "form-control"
            }
        ),error_messages={
               'required': 'The password field is required.'
        })
    password2 = forms.CharField(
        widget=forms.PasswordInput(
            attrs={
                "placeholder": "Confirm Password",
                "class": "form-control"
            }
        ),error_messages={
               'required': 'The confirm password field is required.'
        })

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')


class LoginForm(forms.Form):
    username = forms.CharField(
        widget=forms.TextInput(
            attrs={
                "placeholder": "Username",
                "class": "form-control"
            }
        ),error_messages={
               'required': 'The username field is required.'
        })
    password = forms.CharField(
        widget=forms.PasswordInput(
            attrs={
                "placeholder": "Password",
                "class": "form-control"
            }
        ),error_messages={
               'required': 'The password field is required.'
        })
Step 6 : Creating the Views

So, in this section We need to import SignUpForm,and LoginForm the new class we just created extending UserCreationForm.

In this function, we are going to handle two types of requests. Since we have a form we need to handle the POST request, over and above the usual GET request.

core/views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import authenticate, login
from .forms import SignUpForm, LoginForm
from django.contrib import messages

# Create your views here.

# Register
def register_user(request):
    msg = None
    success = False

    if request.method == "POST":
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get("username")
            raw_password = form.cleaned_data.get("password1")
            user = authenticate(username=username, password=raw_password)
            return redirect("/login/")
        else:
            messages.error(request, 'Form is not valid.')
    else:
        form = SignUpForm()

    return render(request, "register.html", {"form": form, "msg": msg, "success": success})

# Login
def login_view(request):
    form = LoginForm(request.POST or None)

    msg = None

    if not request.user.is_authenticated:
        if request.method == "POST":

            if form.is_valid():
                user = authenticate(username=request.POST.get("username"), password=request.POST.get("password"))
                if user is not None:
                    login(request, user)
                    return redirect('home')
                else:
                    messages.error(request, 'Invalid credentials.')
            else:
                messages.error(request, 'Error validating the form.')
        return render(request, "login.html", {"form": form, "msg": msg})
    return redirect("home")

# Dashboard
def home(request):
    if request.user.is_authenticated:
        return render(request, "home.html")
    return redirect('login')
Step 7 : Creating the Templates

So, finally we are here to this step we need to creating django templates following below file:

  • core/templates/register.html
  • core/templates/login.html
  • core/templates/home.html

Next, open the core/templates/register.html file and the add:

core/templates/register.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tuts-Station.com - Register</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
    <div class="container mt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3>Register</h3>
                    </div>
                    <div class="card-body">
                        {% if messages %}
                            {% for message in messages %}
                                <div class="alert alert-danger alert-dismissible" role="alert" >
                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                      <span aria-hidden="True">×</span>
                                    </button>
                                    {{ message }}
                                </div>
                            {% endfor %}
                        {% endif %}
                        <form method="POST" novalidate>

                            {% csrf_token %}
                        
                            <div class="form-row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="small mb-1">Username:</label>
                                        {{ form.username }}
                                        <small class="text-danger">{{ form.errors.username|striptags }}</small>
                                    </div>
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="small mb-1">Email:</label>
                                        {{ form.email }}
                                        <small class="text-danger">{{ form.errors.email|striptags }}</small>
                                    </div>
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="small mb-1">Password:</label>
                                        {{ form.password1 }}
                                        <small class="text-danger">{{ form.errors.password1|striptags }}</small>
                                    </div>
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="small mb-1">Confirm Password:</label>
                                        {{ form.password2 }}
                                        <small class="text-danger">{{ form.errors.password2|striptags }}</small>
                                    </div>
                                </div>
                            </div>
                            <div class="text-center">
                                <button type="submit" class="btn btn-primary mt-2">Create account</button>
                            </div>
                            <div class="row">
                                <div class="col-md-12 text-center">
                                    <p class="mb-0 mt-3"><small class="text-dark mr-2">Already have an account ?</small> <a href="{% url 'login' %}" class="text-dark font-weight-bold">Sign in</a></p>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Next, open the core/templates/login.html file and the add:

core/templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tuts-Station.com - Login</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3>Login</h3>
                    </div>
                    <div class="card-body">
                        {% if messages %}
                            {% for message in messages %}
                                <div class="alert alert-danger alert-dismissible" role="alert" >
                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                      <span aria-hidden="True">×</span>
                                    </button>
                                    {{ message }}
                                </div>
                            {% endfor %}
                        {% endif %}
                        <form class="login-form" method="POST" novalidate>
                        {% csrf_token %}
                            <div class="row">
                                <div class="col-lg-12">
                                    <div class="form-group position-relative">
                                        <label>Username <span class="text-danger">*</span></label>
                                        {{form.username}}
                                        <small class="text-danger">{{ form.errors.username|striptags }}</small>
                                    </div>
                                </div>
                                <div class="col-lg-12">
                                    <div class="form-group position-relative">
                                        <label>Password <span class="text-danger">*</span></label>
                                        {{form.password}}
                                        <small class="text-danger">{{ form.errors.password|striptags }}</small>
                                    </div>
                                </div>
                                <div class="col-lg-12 mb-0">
                                    <button class="btn btn-primary w-100" type="submit">Login</button>
                                </div>
                                <div class="col-12 text-center">
                                    <p class="mb-0 mt-3"><small class="text-dark mr-2">Don't have an account ?</small> <a href="{% url 'register' %}" class="text-dark font-weight-bold">Sign Up</a></p>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Next, open the core/templates/home.html file and the add:

core/templates/home.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tuts-Station.com - Home</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3>Home</h3>
                    </div>
                    <div class="card-body">
                        <p>Welcome to Dashboard</p>
                        <a href="{% url 'logout' %}" class="btn btn-primary">Logout</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
Step 8 : Creating URLs

In this section, we’ll create the urls to access our views.Go to the urls.py core/urls.py file and update it as follows:

core/urls.py
from django.urls import path
from .views import login_view, register_user, home
from django.contrib.auth.views import LogoutView

urlpatterns = [
    path('login/', login_view, name="login"),
    path('register/', register_user, name="register"),
    path('home/', home, name="home"),
    path("logout/", LogoutView.as_view(), name="logout")
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

example/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/register address with a web browser.

Register Page:

Login Page:

Dashboard Page:

I Hope It will help you....