setting-up-a-basic-authentication-system-in-django.html

Setting Up a Basic Authentication System in Django

Django, a high-level Python web framework, is known for its simplicity and flexibility, making it an excellent choice for developers looking to build robust applications quickly. One of the essential features of any web application is user authentication. In this article, we’ll explore how to set up a basic authentication system in Django, including user registration, login, and logout functionalities. By following the steps outlined here, you’ll have a functional authentication system that can be customized for your specific needs.

What is User Authentication?

User authentication is the process of verifying the identity of a user attempting to access a system. It typically involves checking user credentials, such as usernames and passwords, against a database. In web applications, a solid authentication system is crucial for security, allowing only authorized users to access specific resources or features.

Use Cases for Authentication Systems

  • User Profiles: Allow users to create and manage personal profiles.
  • Content Management: Restrict access to certain content based on user roles (e.g., admin vs. regular user).
  • E-commerce: Secure user accounts for order tracking and payment information.
  • APIs: Authenticate users to access RESTful APIs securely.

Setting Up Your Django Project

Before diving into the authentication system, ensure you have Django installed. If you haven’t yet created a Django project, you can do so with the following commands:

pip install django
django-admin startproject myproject
cd myproject
python manage.py startapp accounts

Next, add your new app to the INSTALLED_APPS list in settings.py:

# myproject/settings.py

INSTALLED_APPS = [
    ...
    'accounts',
]

Creating User Registration

To allow users to register, you need to create a registration form. Django provides a built-in user model that you can use directly.

Step 1: Create a Registration Form

Create a new file called forms.py in your accounts app directory:

# accounts/forms.py

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

class UserRegistrationForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    password_confirm = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ['username', 'email', 'password']

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get("password")
        password_confirm = cleaned_data.get("password_confirm")

        if password and password_confirm and password != password_confirm:
            raise forms.ValidationError("Passwords do not match.")

Step 2: Create Registration View

Add a view to handle user registration in views.py:

# accounts/views.py

from django.shortcuts import render, redirect
from .forms import UserRegistrationForm
from django.contrib.auth import login

def register(request):
    if request.method == 'POST':
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(form.cleaned_data['password'])  # Hash password
            user.save()
            login(request, user)  # Automatically login after registration
            return redirect('home')
    else:
        form = UserRegistrationForm()
    return render(request, 'accounts/register.html', {'form': form})

Step 3: Create Registration Template

Create a template for the registration form. Make a directory named templates/accounts and create a file called register.html:

<!-- templates/accounts/register.html -->

<h2>Register</h2>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Register</button>
</form>

Implementing Login and Logout Functionality

Step 4: Create Login View

In the same views.py file, add the following code for logging in users:

# accounts/views.py (continued)

from django.contrib.auth import authenticate, login as auth_login
from django.contrib.auth.forms import AuthenticationForm

def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(request, username=username, password=password)
            if user is not None:
                auth_login(request, user)
                return redirect('home')
    else:
        form = AuthenticationForm()
    return render(request, 'accounts/login.html', {'form': form})

Step 5: Create Login Template

Create a login.html file in the same templates directory:

<!-- templates/accounts/login.html -->

<h2>Login</h2>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Login</button>
</form>

Step 6: Create Logout View

Django provides a built-in logout view. You can use it directly in your URLs. First, include the logout view in your urls.py:

# accounts/urls.py

from django.urls import path
from .views import register, login

urlpatterns = [
    path('register/', register, name='register'),
    path('login/', login, name='login'),
    path('logout/', 'django.contrib.auth.views.LogoutView.as_view()', name='logout'),
]

Make sure to include these URLs in your main urls.py:

# myproject/urls.py

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

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

Final Touches and Testing

Step 7: Apply Migrations

Run the following command to create the necessary database tables:

python manage.py migrate

Step 8: Run the Server

Start your Django development server to test the authentication system:

python manage.py runserver

Navigate to http://127.0.0.1:8000/accounts/register/ to see your registration form. After registering, you can log in at http://127.0.0.1:8000/accounts/login/.

Conclusion

Setting up a basic authentication system in Django is a straightforward process that can be accomplished in just a few steps. This guide provided you with the foundational components for user registration, login, and logout functionalities. From here, you can further customize the system with features like email verification, password reset, and user profile management.

With Django's built-in tools and the flexibility of Python, you are well on your way to creating secure and user-friendly web applications. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.