Authentication System With Django

Authentication System With Django

Building a functional signup and login system with Django

Today I'll show you how to create an authentication system using Django. With the use of this system, users will be given full access to the company's website or landing page after having their logins verified.

PREREQUISITES

  1. Latest version of python installed on your system

  2. Latest Django version installed on your system

Your Django project should be stored in a folder that you create in the file explorer on your computer. Give it the name "DJANGO AUTH SYSTEM." You can access your folder by entering "cd DJANGO AUTH SYSTEM" at the command prompt to open it.

Create your Django project

To create a Django project, type this into your command prompt: django-admin startproject DjangoAuth. Now navigate to your project folder: cd DjangoAuth . The "DjangoAuth" is the name of your project folder. You can name it whatever you want.

Create your Django app

Enter into your command prompt: python manage.py startapp login. The "login" is the name of your app. You can also name it whatever you want to. Now, launch vs code or your preferred IDE and navigate to the Django project folder. It ought to contain these subfolders:

django folder tree

Urls Configuration/ Urls Routing for the project

Navigate to the urls.py file in your project folder (DjangoAuth). You must import an object called "include." Your app's urls must additionally include a path. The urls.py file in your project folder should now appear as seen, and you should save it as follows:

DjangoAuth project's urls.py file

Templates

Make a "templates" folder in your root directory. Create a new folder inside it and give it the same name as your app, such as "login." Next, create four files called "base.html," "index.html," "signup.html," and "signin.html in your templates/login folder.

templates folder structure

Change Settings

Navigate to the settings.py file in your project's folder (DjangoAuth). To access the INSTALLED APPS area, scroll down. Add the name of your app, "login," at the end of the array. Continue to the TEMPLATES section's DIRS object by scrolling down, and put this inside the square bracket: BASE DIR/"templates". Save it.

settings.py file of your project folder

URL Configuration of your app

Create a new file called urls.py inside the app folder. Write the following code into this file to configure it:

from django.contrib import admin
from django.urls import path, include
from . import views

urlpatterns = [
    path("", views.home, name="home"),
    path("signup", views.signup, name="signup"),
    path("signin", views.signin, name="signin"),
    path("signout", views.signout, name="signout"),
]

Modify the view

Inside the views.py file of your app folder, write out this code:

from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout

# Create your views here.
def home(request):
    return render(request, "login/base.html")

# Sign up
def signup(request):

    if request.method == "POST":
        username = request.POST.get('username')
        fname = request.POST.get('fname')
        lname = request.POST.get('lname')
        email = request.POST.get('email')
        password1 = request.POST.get('password1')
        password2 = request.POST.get('password2')


        if User.objects.filter(username=username):
            messages.error(request, "Username already exists")
            return redirect('home')

        if User.objects.filter(email=email):
            messages.error(request, "This email is already being used by another user")
            return redirect('home')

        if password1 != password2:
            messages.error(request, "Incorrect password")
            return redirect('home')

        myuser = User.objects.create_user(username, email, password1)
        myuser.first_name = fname
        myuser.last_name = lname
        myuser.save()
        messages.success(request, "Your account has been succesfully created!")

        return redirect("signin")

    return render(request, "login/signup.html")


# Signin
def signin(request):

    if request.method == "POST":
        username = request.POST['username']
        password1 = request.POST['password1']
        user = authenticate(username=username, password=password1)

        if user is not None:
            login(request, user)
            fname = user.first_name
            return render(request, "login/index.html", {'fname': fname})

        else:
            messages.error(request, "Invalid username or password")
            return redirect('home')

    return render(request, "login/signin.html")


# Sign out
def signout(request):
    logout(request)
    messages.success(request, "Log out successful!")
    return redirect('home')

The html files

signup.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scale=1.0" />
    <title>Sign up Form </title>
  </head>
  <body>
    <section>

      <div>
        <div>
          <header>Sign up</header>
          <form action="/signup" method="post">
            {% csrf_token %}
              <input type="text" name="username" id="username" placeholder="Create your username" class="input" required/>
              <input type="text" name="fname" id="fname" placeholder="Enter your first name" class="input" required/>
              <input type="text" name="lname" id="lname" placeholder="Enter your last name" class="input" required/>
              <input type="text" name="email" id="email" placeholder="Enter your email address" class="input" required/>
              <input type="password" name="password1" id="password1" placeholder="Create password" class="input" required/>
              <input type="password" name="password2" id="password2" placeholder="Confirm password" class="password" required/>
              <button type="submit">Sign up</button>
          </form>
        </div>

      </div>
    </section>
  </body>
</html>

signin.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scale=1.0" />
    <title>Login Form </title>
</head>

<body>
    <section>
        <div>
            <div>
                <header>Login</header>
                <form action="/signin" method="post">
                    {% csrf_token %}
                        <input type="text" name="username" id="username" placeholder="Enter your username" required />
                        <input type="password" name="password1" id="password1" placeholder="Enter your password" required />
                        <button type="submit">Login</button>
                    </div>
                </form>
            </div>
        </div>
    </section>

</body>
</html>

base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Django Authentication Website</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font- 
    awesome/5.15.3/css/all.min.css" />

</head>

<body>

    {% for message in messages %}
    <div class="alert alert-{{ message.tags }} alert-dismissible fade show block justify-center text-center text-xl"
        role="alert">
        <strong class="text-xl">Message: </strong> {{ message }}
    </div>
    {% endfor %}


    <header>
        {% if user.is_authenticated %}
        <div>
            <h2>Hello {{ fname }}</h2>
            <h3>You are successfully logged in</h3>
        </div>
        <div>
            <h1>OmaTour</h1>

            <div>
                <div>
                    <button type="submit"><a href="/signout">Sign out</a></button>
                </div>
                {% else %}
                <h1>Oma_Tour</h1>

                <button type="submit"><a href="/signin">Sign in</a>
                </button>
                <button type="submit"><a href="/signup">Sign up</a>
                </button>
                {% endif %}
            </div>
    </header>

    <div>
        <div>
            <h1>Take a tour around the world.</h1>
            <p>Providing touring services to tourists at affordable rates. It was founded in the year 2010 and has its
                headquarter in <strong>Lorem.</strong> Lorem ipsum dolor sit amet consectetur adipisicing elit.
                Voluptatibus, dolorum eligendi! Nam labore beatae aliquid. Placeat quibusdam eveniet fuga porro!</p>
        </div>
    </div>

    {% block content %}
    {% endblock content %}

</body>
</html>

index.html

{% extends 'login/base.html' %}
{% block content %}

<main>

    <!--Features section-->
    <section>
        <div>
            <h2>Features</h2>

            <div>
                <div>
                    <div>
                        <h2>Translation Software</h2>
                        <p>Since we get to take tourists from different parts of the world to different parts of the
                            world, our system software is designed to translate languages for easy communication.</p>
                        <a href="">Learn More &#8594;
                        </a>
                    </div>
                </div>

                <div>
                    <div>
                        <h2>Payment System</h2>
                        <p>Our portal is designed to accept all forms of payments ranging from cash, card payment,
                            paypal and even payments in form of crypto tokens/coins. It is scalable and easy to use.</p>
                        <a href="">Learn More &#8594;
                        </a>
                    </div>
                </div>

                <div>
                    <div>
                        <h2>Enticing Packages</h2>
                        <p>At OmaTour, we are dedicated to giving you the best and so we have attractive incentives for
                            our cutomers which includes; pick and drop services, insurance, rental cars usage.</p>
                        <a href="">Learn More &#8594;
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </section>

</main>

<!-- Footer Section -->
<footer>
    <div>
        <div>
            <a href="#"><i class="fab fa-instagram"></i></a>
            <a href="#"><i class="fab fa-linkedin-in"></i></a>
            <a href="#"><i class="fab fa-facebook"></i></a>
            <a href="#"><i class="fab fa-twitter"></i></a>
        </div>
        <h1>
            &copy; Copyright 2022 | All right reserved </h1>
        <p>Crafted with <i class="fa fa-heart"> </i> by
            <a href=""><strong>Name</strong></a>
        </p>
    </div>
    </div>
</footer>

{% endblock content %}

Notice the if, endif, for, endfor terms in your html files? These are called templates tags and they allow you to perform programming logic in Django. The csrf_token must be included whenever a POST method is used on a form. They are all executed by surrounding them with this: {% %}. The extends tag in the index.html file is used to add a parent template(base.html) for the current template(index.html).

To view your project live on your browser, make sure you've navigated into your project directory and then follow these steps:

  1. To perform database migrations, enter the following commands at your command prompt: python manage.py makemigrations
  2. Then enter this, to migrate your database: python manage.py migrate

  3. To display it on your browser: python manage.py runserver

  4. A localhost:8000 link should then be generated right there in your terminal or command prompt, which you can click on or copy and paste into your browser.

Final Note:

Yaaay🎉, your Django authentication system is ready. The main page will be displayed but only to an extent and there'll be a sign-in and signup button for users. Users who don't already have an account will be prompted to sign up and if the procedure was successful, be directed to log in using their sign-up information. After logging in, users will have full access to the website, and the sign-in and sign-up buttons will be replaced with a sign-out one. A message will be displayed when a user:

  • Successfully creates an account
  • Logs in successfully
  • Enters an incorrect username or password while logging in, and
  • Logs out.

This is the live version of what your authentication system should look like now:

landing page before user signs up or signs in sign up form log in form landing page after users signup and login or just logs in user logout

Notice that I didn't add any form of styling to this website, you can go ahead and style it yourself either directly in the html files or by having separate css files in a static folder and then linking them to their respective html files. Keep an eye out for my next article.😉