USER REGISTRATION & AUTHENTICATION USING DJANGO.

naftal_m

Naftali M

Posted on August 2, 2024

USER REGISTRATION & AUTHENTICATION USING DJANGO.

This project will guide you through creating users using Django's default forms, registering users, authenticating users via the login form, and displaying certain pages only for authenticated users. You also can logout the user

Create project, and respective apps
Register your application in the settings.py file

INSTALLED_APPS = [
    'your_app', 
]
Enter fullscreen mode Exit fullscreen mode

Create super user.

py manage.py createsuperuser
Enter fullscreen mode Exit fullscreen mode

Create the template folder and have the following html pages
Base.html – contains all code that is extended to other html pages

`<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>User</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<link rel="stylesheet" href="#">
</head>
<body>
    <div class="container">
        <div class="card text-center mt-3">
            <div class="card-header">
              <ul class="nav nav-tabs card-header-tabs">
                <li class="nav-item">
                  <a class="nav-link "  href="#">Home</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link "  href="{%url 'register'%}">Sign Up</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link "  href="{%url 'signin'%}">Login</a>
                </li>
              </ul>
              <div class="card-body bg-info ">

                {% block content%}

                {%endblock%}
            </div>
            </div>
        </div>
    </div> 
</body>
</html>`
Enter fullscreen mode Exit fullscreen mode

Home.html – contains code for our landing page

{%extends 'base.html'%}
{%block content%}
<h2>Welcome to user creation form</h2>
{%endblock%}

Register.html – contains code that renders the registration form
{%extends 'base.html'%}
{%block content%}
<h2>Registration Page</h2>
                 <form action="" method="post">
                    {% csrf_token %}
                    <!--1 {{form}}  Default django form -->
                     <!-- {{form.as_p}} -->

                    {{form.username.label}}{{form.username}}
                    <br>
                    {{form.email.label}} {{form.email}}
                    <br>
                    {{form.password1.label}} {{form.password1}}
                    <br>
                    {{form.password2.label}} {{form.password2}}
                    <br>
                    <!-- add bootstrap form controls here -->
                    <!-- <form >
                        <div class="form-group" style="width: 400px;">
                          <label for="formGroupExampleInput">username</label>
                          {{form.username}}
                        <br>
                          <label for="formGroupExampleInput2">Email</label>
                          {{form.email}}
                          <br>
                          <label for="formGroupExampleInput">password</label>
                          {{form.password1}}
                          <br>
                          <label for="formGroupExampleInput2">Confirm password</label>
                          {{form.password2}}
                        </div>
                      </form> -->
                    <input type="submit">
                    <!-- show any errors -->
                    {{form.errors}}

                    <p>Already have an account <a href="{%url 'signin'%}">Login</a></p>
                 </form>
{%endblock%}

Enter fullscreen mode Exit fullscreen mode

Login page – contains code for the login interface

{%extends 'base.html'%}
{%block content%}
<p>Login form</p>
<form action="" method="POST">
    {% csrf_token %}
    <div class="form-group">
      <label for="">Username</label>
      <input type="text" class="form-control" id="" name="username" placeholder="Username">

      <label for="">password</label>
      <input type="password" class="form-control" id="" name="password" placeholder="password">

    </div>
    <input type="submit" value="submit">
    <p>Don't have an acccount <a href="{%url 'register'%}">Sign Up</a></p>

    <!-- display message -->
     {% for message in messages%}
        <p>{{message}}</p>

     {%endfor%}
  </form>
{%endblock%}

Enter fullscreen mode Exit fullscreen mode

Form.py – this form helps us to override the basic Django user form and add our own email fields

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

#custom user 
class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

urls.py – All our urls are registered to this file

from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [

   path("home/", views.home, name="home"),
   path("signin/", views.signin, name="signin"),
   path("register/", views.register, name="register"),
   path("dashboard/", views.dashboard, name="dashboard"),
   path("logout/", views.logout, name="logout"),
]

Enter fullscreen mode Exit fullscreen mode

Views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import CreateUserForm

#using messages
from django.contrib import messages
# handle login form
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.forms import UserCreationForm

#resctrict access to some pages 
from django.contrib.auth.decorators import login_required
def home(request):
    # return HttpResponse('Hello Learns!!!')
    return render(request, 'home.html')

def register(request):
    form = CreateUserForm()
    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            form.save()
            #get username 
            user = form.cleaned_data.get('username')
            messages.success(request, 'Account succefully created for ' + user)
            # After user has registered take them to login page
            return redirect('signin')
    context = {'form': form}
    #return HttpResponse('Hello Learns!!!')
    return render(request, "register.html", context)

# def register(request):
#     form = UserCreationForm()
#     if request.method == 'POST':
#         form = UserCreationForm(request.POST)
#         if form.is_valid():
#             form.save()
#     context = {'form': form}
#     #return HttpResponse('Hello Learns!!!')
#     return render(request, "register.html", context)


# Create your views here.
def signin(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            return redirect('dashboard')
        else:
            messages.info(request, 'Username or Password is incorrect')

    context = {}
    return render(request, 'login.html', context)

def logout(request): 
    return redirect('home')

@login_required(login_url='signin')
def dashboard(request):
    return render(request, 'dashboard.html')
Enter fullscreen mode Exit fullscreen mode

To get the project code on github: Naftaly

💖 💪 🙅 🚩
naftal_m
Naftali M

Posted on August 2, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related