Django: Sign-in and Logout Tutorial for Beginners

Alifia Ghantiwala
5 min readApr 10, 2023
Photo by Faisal on Unsplash

Table of Contents:

Introduction

Installations

Setting up the main code

Final Result

Conclusion

Shameless Self-Promotion

Introduction:

In my pursuit to master the Python language, I have already dabbled my hands with writing scripts for automating manual tasks, and to do something different for this weekend I decided to build a web application using Python. After some research, I found that Django is a framework that would allow me to do the same. Though I was not able to build an entire application, I managed to create a simple sign-in and logout functionality using the auth package in Django, which I thought I should share with you as it is really simple, and anybody can do it. I would be adding other functionalities as well to my application and writing about them, so if you like this article, do stay tuned for more.

Without further ado, let’s get the ball rolling, shall we?

Rolling Willy Wonka GIF By Laff

Installations:

We will first install a virtual env in which we would install Django.

pip3 install virtualenv #Installing 
virtualenv env # Creating a virtual env named 'env'
env/scripts/activate #Activating the virtual env.
Image by Author

Once you activate the virtual environment, you would see the name of the environment in round brackets before your command line, as above.

Next, install Django and start the server.

pip3 install django
django-admin startproject project_name #Creates a folder with your project name and all boiler plate files.
#In my case project_name is GroupStudy
python manage.py runserver #Start the server

On starting the server, you would be able to see the below on your command prompt.

Image by Author

On viewing the localhost(http://127.0.0.1:8000/), in your browser, you should be able to see the below.

Image by Author.

If you see the above page on your browser, it means you have successfully installed Django.

I am using VisualStudioCode as my code editor, you can use anything that suits you like Notepad++, or Atom. The project structure you would see would be as below.

Image by Author.

Setting up the main code:

Create a folder named ‘templates’ and the below HTML files within the folder. I have added comments within the code blocks to make it easy to understand.

#main.html: Boiler plate html code
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title> Group Study</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
{% include 'navbar.html' %}
# we would be including login and logout buttons in the navbar, so that a user can login from any page of the application.
{% block content %}

{% endblock%}
</body>
</html>
#Using the include keyword we can reference one html template in another, aswe have done here.
#navbar.html 
#In the navbar we have a link to take us to the homepage.
#Next, we first check if the user is authenticated,
# if not we provide them an option to login.
<a href="/">
<h1>LOGO</h1>
</a>
{% if user.is_authenticated%}
<p>Hi, {{user.username}} :)</p>
<p><a href="{% url 'logout' %}">Log Out</a></p>
{%else%}
<p>You are not logged in</p>
<a href="{% url 'login' %}">Login</a>
{%endif%}
<hr>

Within your project folder structure, within the folder project_name/base, you would find a file urls.py, add the following to it.

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

urlpatterns = [
path("accounts/", include("django.contrib.auth.urls")),
]

In the file ‘project_name/setting.py’ make the following changes:

If you see the installed apps in settings.py you should find that django.contrib.auth is added already by default, as below, we would be using the same auth package for our signing-in setup.

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'base.apps.BaseConfig',
]
  1. Add BASE_DIR / ‘templates’ which is the folder name where we have stored our HTML files so that our app knows where it has to look to render the HTML pages.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR / 'templates'
],

2. We want that login as well as log out to our app redirects to the home page, for the same we would have to specify the below in the settings.py file at the end of the existing code present there.

LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"

Final Result:

On completion of the above steps, you should be able to see the below on the homepage.

Image by Author

On clicking the login button, you would see the below:

Image by Author.

Do make a note of the changing URLs in every screenshot, we have defined in the Python script ‘urls.py’ that on calling path accounts/ auth package by Django should be invoked.

Now for logging in we would need a username and password. For the same, run the below command.

python manage.py createsuperuser

Now follow the prompts and add a username and password of your choosing.

Image by Author.

Using the username and password you just created try to log in to your application. You should be redirected to the home page of your application with the below message.

Image by Author.

And now you can see a logout option to sign out as well.

Conclusion:

In conclusion, we have used the ‘django.contrib.auth’ package to create a simple sign-in and sign-out functionality for our application.

Next, I would be covering how we can register a user directly from our application.

Shameless Self-Promotion:

As I mentioned at the start of this blog, I have written some articles on automation using Python, linking them here, in case you would want to have a look :P

Thanks for reading along, have fun Pythoning :)

Monty Python Terry Gilliam Animation GIF

--

--