How to build a User Registration(Login/Signup/Logout) System in Django

1. Introduction


In this post, we are going to see how to build a User registration system in Django using the auth module in Django. The example will cover steps to build your registration system where users can register(signup)/login using the credentials and logout of the system.



Let's get Started! 

2. Starting a new Project 

If you are new to Django, please make sure to check out the steps to create a virtual envt in python before creating a Django project. If you already have one you can continue to follow along with me.

Step #1 : Create a Django project

We are not going to use any database-model for this tutorial, we will cover soon in some other post. Let's create a new Django project by running the below command inside your virtual env.

 django-admin startproject mysite

Step #2: Create a Django app

In this tutorial, we’ll create our accounts app in the same directory as your manage.py file so that it can be imported as its own top-level module, rather than a submodule of mysite.

To create your app, make sure you’re in the same directory as manage.py and type this command:

python manage.py startapp accounts

Once done you should be able to see a below folder structure with the below files.

Step #3: Update your Setting.py


Make sure to update your setting.py with a new app so that it can be picked up while running the server.

INSTALLED_APPS = [

    'accounts.apps.AccountsConfig',
	
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

3. Building your Base template for homepage/signup page/login page/login

First, we are going to build a base template for our homepage using Bootstrap. Navigate to mysite ((app) inside the main mysite project). create a template folder and add a file called base.html

You can paste the below code inside base.html .This will be a basic template which we are going to use in our project.


<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">


  <title>NintyZero</title>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

</head>

<body>

  <header>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <a class="navbar-brand" href="">NintyZero</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
      </div>
    </nav>
  </header>
  <div class="container">
      {% block content %}
      {% endblock %}
  </div>

  <footer class="text-muted">
    <div class="container text-center">
      <p>This is a footer {% now "Y" %}</p>
      </div>
  </footer>

  <!-- Bootstrap core JavaScript
  ================================================== -->
  <!-- Placed at the end of the document so the pages load faster -->
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>

</code></pre>

4.Updating the URL for navigation 

To update the URL pattern (for ex we want to show login page once user reaches account/login or account/signup. we can do that by adding the URL pattern in urls.py file(if not found create one) inside your mysite folder and add the below code.

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


urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.home,name="home"),
    path('accounts/',include ('accounts.urls')),
]


5.Adding view for Login/Signup/Logout

Create a template/account folder inside account app and add two Html files named login.html and signup.html

Use the below code to create a Signup Page


{% extends 'base.html' %}

{% block content %}


{% if error %}
{{ error }}

<br/>
<br/>
{% endif %}

<h1>Signup!</h1>

<form method = "POST" action="{% url 'signup' %}">
    {% csrf_token %}
    username:
    <br/>
    <input type="text" name="username" />
    <br/>
    Password:
    <br/>
    <input type="password" name="password1" />
    <br/>
    confirm Password:
    <br/>
    <input type="password" name="password2" />
    <br/>
    <input class ="btn btn-primary" type="submit" value= "signup" />
    <br/>



</form>


{% endblock %}
Login.html

{% extends 'base.html' %}

{% block content %}


{% if error %}
{{ error }}

<br/>
<br/>
{% endif %}

<h1>Login!</h1>

<form method = "POST" action="{% url 'login' %}">
    {% csrf_token %}
    username:
    <br/>
    <input type="text" name="username" />
    <br/>
    Password:
    <br/>
    <input type="password" name="password" />
    <br/>
    <input class ="btn btn-primary" type="submit" value= "Login" />
    <br/>



</form>


{% endblock %}

6. Adding the logic for login and signup

Open the view.py (create one if now found) inside accounts app folder and add the below code to it.

from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from django.contrib import auth

def signup(request):
    if request.method == "POST":
        if request.POST['password1'] == request.POST['password2']:
            try:
                User.objects.get(username = request.POST['username'])
                return render (request,'accounts/signup.html', {'error':'Username is already taken!'})
            except User.DoesNotExist:
                user = User.objects.create_user(request.POST['username'],password=request.POST['password1'])
                auth.login(request,user)
                return redirect('home')
        else:
            return render (request,'accounts/signup.html', {'error':'Password does not match!'})
    else:
        return render(request,'accounts/signup.html')

def login(request):
    if request.method == 'POST':
        user = auth.authenticate(username=request.POST['username'],password = request.POST['password'])
        if user is not None:
            auth.login(request,user)
            return redirect('home')
        else:
            return render (request,'accounts/login.html', {'error':'Username or password is incorrect!'})
    else:
        return render(request,'accounts/login.html')

def logout(request):
    if request.method == 'POST':
        auth.logout(request)
    return redirect('home')


Conclusion:

In this post, we learned how to build a user login and signup systems. we also saw how to build views and use it to register and log in.

Hey I'm Venkat
Developer, Blogger, Thinker and Data scientist. nintyzeros [at] gmail.com I love the Data and Problem - An Indian Lives in US .If you have any question do reach me out via below social media