How To Create A Login Page Using Django

How To Articles

Creating a login page is a crucial step in building any web application, as it allows users to access personalized features and secure their data. In this article, I will guide you through the process of creating a login page using Django, a powerful and user-friendly Python web framework. Along the way, I’ll share my personal experiences and provide commentary to help you understand the concepts better. So let’s dive into the world of Django login pages!

Preparation

Before we jump into coding, let’s make sure we have everything we need in place. Firstly, ensure that you have Django installed on your system. If not, you can install it by running the command pip install django in your terminal. Additionally, make sure you have a code editor, such as Visual Studio Code or PyCharm, set up for a seamless development experience.

Once you have Django installed and your code editor ready, let’s create a new Django project. Open your terminal and navigate to the desired location where you want to create your project. Use the command django-admin startproject myproject to create a new Django project named “myproject”. Feel free to replace “myproject” with the desired name for your project. Now, navigate into the project directory using cd myproject.

Creating the Login App

Next, we need to create a Django app to handle the login functionality. Django follows the MVC (Model-View-Controller) pattern, where an app represents a specific functionality of the project. In this case, our app will handle the login-related functionality.

To create the app, run the command python manage.py startapp login_app. This will create a new directory named “login_app” within your project. We will use this directory to write the code for our login page.

With the app created, it’s time to define the necessary models for user authentication. Django provides a built-in User model, which we will use for handling user authentication. Open the “models.py” file inside the “login_app” directory and add the following code:


from django.contrib.auth.models import User
from django.db import models

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# Add additional fields for the user's profile

In the above code, we have created a Profile model that has a one-to-one relationship with the User model. This allows us to store additional information about the user, such as their profile picture or a short bio. The on_delete=models.CASCADE parameter ensures that when a user is deleted, their associated profile is also deleted.

Creating the Login View

Now that we have our models set up, let’s move on to creating the views for our login page. Views handle the logic behind the web pages and render the appropriate template. In our case, we want to render a template containing the login form and handle the form submission.

Create a new file called “views.py” inside the “login_app” directory and write the following code:


from django.contrib import auth
from django.shortcuts import render, redirect
from .forms import LoginForm

def login(request)
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect('home')
else:
error_message = "Invalid username or password"
return render(request, 'login.html', {'form': form, 'error_message': error_message})
else:
form = LoginForm()
return render(request, 'login.html', {'form': form})

In the above code, we define a login view that handles both GET and POST requests. For GET requests, it renders a template called “login.html” and passes in an instance of the LoginForm. For POST requests, it validates the form data, authenticates the user using the authenticate method from Django’s built-in authentication system, and redirects the user to the home page upon successful login. If the login fails, it displays an error message on the login page.

Since we referenced a LoginForm in our view, let’s create that form now. Create a new file called “forms.py” inside the “login_app” directory and add the following code:


from django import forms

class LoginForm(forms.Form):
username = forms.CharField(label='Username')
password = forms.CharField(label='Password', widget=forms.PasswordInput)

In the above code, we define a form called LoginForm that contains two fields, “username” and “password”. The CharField class represents a text input field, and we use the PasswordInput widget to hide the password as the user types.

Creating the Login Template

Now that we have our view and form set up, let’s create a template for our login page. Templates define the structure and layout of the web pages in Django. Create a new directory called “templates” inside the “login_app” directory. Inside the “templates” directory, create a new file called “login.html” and add the following code:


<h2>Login</h2>

{% if error_message %}
<p class="error">{{ error_message }}</p>
{% endif %}

<form method="post" action="{% url 'login' %}">
{% csrf_token %}

{{ form.username.label_tag }}
{{ form.username }}

{{ form.password.label_tag }}
{{ form.password }}

<button type="submit">Sign In</button>
</form>

In the above code, we first display the heading “Login”. If there is an error message (passed from the view), we display it in a paragraph with the “error” CSS class. We then define a form that submits to the login view URL. The CSRF token, which provides protection against cross-site request forgery attacks, is included using the {% csrf_token %} template tag. Finally, we display the username and password fields along with a “Sign In” button.

Configuring URL Routing

To complete the login page setup, we need to configure the URL routing in Django to map the appropriate URLs to our views. Open the “urls.py” file located in the project directory and add the following code:


from django.urls import path
from login_app import views

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

The above code creates a URL pattern that matches the URL “login/” and maps it to the login view we defined earlier. The name ‘login’ is used to refer to this URL throughout the project, allowing us to easily link to the login page from other pages.

Conclusion

Congratulations! You have successfully created a login page using Django. We covered the basic steps of creating the login app, defining models, creating views and forms, and configuring URL routing. By following this guide, you can customize and enhance your login page according to your application’s requirements. Remember to handle user authentication securely and provide a smooth user experience. Happy coding!