How to Create Signup, Login, and Logout Functionality in Django

Creating user authentication functionality is a fundamental part of many web applications. Django, a powerful Python web framework, makes it relatively straightforward to implement user registration, login, and logout features. In this tutorial, we’ll walk you through the process step by step with proper examples.

Prerequisites

Before you begin, make sure you have the following installed:

  1. Python: You’ll need Python installed on your system. You can download it from python.org if it’s not already installed.
  2. Django: Install Django using pip by running the following command: pip install django

Now that you have the prerequisites in place, let’s dive into creating a Django project with user authentication.

Setup Django Project and App for Authentication System

Step 1. Create a Django Project: First, create a new Django project using the following command:

django-admin startproject projectname

Replace projectname with the desired name for your project.

Step 2. Create a Django App: Next, create a Django app within your project:

cd projectname
python manage.py startapp appname

Replace appname with the name you want to give to your app.

Step 3. Configure Settings: Open the settings.py file located in your project’s directory and add your app to the INSTALLED_APPS list. Also, make sure the django.contrib.auth and django.contrib.sessions apps are included:

INSTALLED_APPS = [
    # ...
    'django.contrib.auth',
    'django.contrib.sessions',
    'appname',  # Replace with your app's name
    # ...
]

Step 4. Migrate to Database:

python manage.py makemigrations
python manage.py migrate

Step 5. Create Base Templates: Within your app, create a folder named templates and inside it base.html, which we will use to inherit in other html files.

Here’s an example of a basic base.html template in Django, which you can use as a starting point for your project’s base template:

<!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>{% block title %}Your Website Title{% endblock %}</title>
    <!-- Add your CSS and JavaScript links here -->
</head>

<body>

    <main>
        {% block content %}
        {% endblock %}
    </main>

    <footer>
        <!-- Add your footer content here -->
    </footer>
</body>

</html>

Implement User Signup Registration

Step 1: First, create a custom registration form in your forms.py file within your app:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class CustomUserCreationForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=True, help_text='Required. Enter your first name.')
    last_name = forms.CharField(max_length=30, required=True, help_text='Required. Enter your last name.')

    class Meta:
        model = User
        fields = [
            'username', 
            'first_name', 
            'last_name', 
            'email', 
            'password1', 
            'password2', 
        ]

In this example, we’ve created a form CustomUserCreationForm that inherits from UserCreationForm and adds fields for first_name and last_name.

Step 2: Now, let’s create a view for user registration. In your app’s views.py file, add the following code:

from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect
from .forms import CustomUserCreationForm  # Import your custom form

def signup(request):
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect('home')  # Replace 'home' with the URL name of your home page
    else:
        form = CustomUserCreationForm()
    return render(request, 'signup.html', {'form': form})