Django Login Page With Database

Python Programming

As a developer, creating a login page is crucial for any web application. This page ensures a safe method for users to log into their accounts and access restricted sections of the website. In this article, I will provide step-by-step instructions for creating a Django login page using a database.

Setting up the Django Project

Before we dive into creating the login page, let’s first set up our Django project. Open up your terminal and create a new directory for our project by running the following command:

mkdir myproject

Navigate into the newly created directory:

cd myproject

Now, let’s create a new virtual environment for our project to ensure we have a clean environment:

python -m venv env

Activate the virtual environment:

source env/bin/activate

We can install Django by running the following command:

pip install django

Once Django is installed, let’s create a new Django project:

django-admin startproject myproject

Now, we can navigate into the project directory:

cd myproject

Creating the Login App

In Django, an app is a self-contained module that houses specific functionality. To create our login page, let’s create a new app called “accounts” by running the following command:

python manage.py startapp accounts

Once the app is created, we need to add it to the list of installed apps in our project’s settings.py file:

INSTALLED_APPS = [
...
'accounts',
...
]

Next, let’s create a new file called urls.py in the accounts app directory and add the following code:

from django.urls import path
from . import views

urlpatterns = [
path('login/', views.login_view, name='login'),
]

Now, let’s create a new file called views.py in the accounts app directory and add the following code:

from django.shortcuts import render

def login_view(request):
return render(request, 'accounts/login.html')

We have created the basic structure of our login page. We will create the actual HTML template in the next step.

Creating the Login Template

In Django, templates are used to generate HTML dynamically. Let’s create a new directory called “templates” in the accounts app directory, and inside the templates directory, create another directory called “accounts”. Finally, create a new file called “login.html” inside the accounts directory. Add the following code to the login.html file:

<h2>Login</h2>
<form method="post">
{% csrf_token %}
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<input type="submit" value="Login">
</form>

In this template, we have a simple form that asks for the username and password. We also include the CSRF token to protect against cross-site scripting attacks.

Adding Authentication Logic

Now that we have our login page template, let’s add the authentication logic to handle the form submission. Modify the views.py file in the accounts app directory as follows:

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login

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

In this code, we first check if the request method is POST, which means that the form has been submitted. We then retrieve the username and password from the POST data and use the authenticate() function to verify the credentials. If the user is authenticated, we use the login() function to log the user in and redirect them to the home page. If the credentials are invalid, we render the login.html template again with an error message.

Securing the Login Page

By default, Django’s login view is already secure as it requires a valid CSRF token. However, it’s a good practice to add additional security measures to protect against brute-force attacks. One way to do this is by implementing rate limiting to limit the number of login attempts per IP address. There are several Django packages available that can help with this, such as Django Ratelimit.

Conclusion

Creating a Django login page with a database is an essential step in building a secure web application. By following the steps outlined in this article, you can create a functional login page that allows users to authenticate and access protected areas of your website. Remember to always prioritize security and consider implementing additional measures to protect against potential threats.

For more information on Django’s authentication framework and other security best practices, check out the official Django documentation at https://docs.djangoproject.com/en/3.2/topics/auth/.