Django Tutorial

Django Create A Complete Project

Django Template

Django Database Query

Django Form

Django Authentication and Permission Management

Django unittest

Django Advanced

Django Auth App Module

In this tutorial, we will explore Django's built-in authentication app module. The Django authentication app module provides functionalities like user registration, authentication, password management, and other user-related features, making it easy to manage user accounts in your web application.

Setup

Before we start, make sure you have Django installed. If you haven't, install it using pip:

pip install django

Create a new Django project and add the 'django.contrib.auth' and 'django.contrib.contenttypes' apps to your INSTALLED_APPS in settings.py (they should be included by default):

INSTALLED_APPS = [
    # ...
    'django.contrib.auth',
    'django.contrib.contenttypes',
    # ...
]

User Model

Django's authentication framework comes with a built-in User model that represents users in your application. The User model includes fields for storing user-related data like username, email, password, first name, last name, and user's active status.

To use the User model, you need to import it:

from django.contrib.auth.models import User

Registration

You can create a new user by calling the User.objects.create_user() method:

new_user = User.objects.create_user(username='john', password='johnpassword')

The create_user() method takes the following arguments:

  • username: The unique username for the user.
  • password: The password for the user. It will be hashed before storing it in the database.
  • email (optional): The user's email address.
  • first_name (optional): The user's first name.
  • last_name (optional): The user's last name.

Authentication

To authenticate a user, you can use the authenticate() function from django.contrib.auth. This function checks the given credentials and returns a User object if the credentials are valid. If the credentials are not valid, it returns None.

Here's an example:

from django.contrib.auth import authenticate

username = 'john'
password = 'johnpassword'

user = authenticate(username=username, password=password)

if user is not None:
    print("Authentication successful")
else:
    print("Invalid credentials")

Login and Logout

Once you have authenticated a user, you can log them in using the login() function from django.contrib.auth. The login() function takes an HttpRequest object and a User object:

from django.contrib.auth import login

def login_view(request):
    # Assume that you have already authenticated the user
    user = authenticate(request, username='john', password='johnpassword')

    if user is not None:
        login(request, user)
        return HttpResponse("Logged in successfully")
    else:
        return HttpResponse("Invalid credentials")

To log out a user, you can use the logout() function from django.contrib.auth. The logout() function takes an HttpRequest object:

from django.contrib.auth import logout

def logout_view(request):
    logout(request)
    return HttpResponse("Logged out successfully")

Password Management

Django's authentication framework provides built-in functions to handle password-related tasks like changing, resetting, and hashing passwords.

  • To change a user's password, you can use the set_password() method:
user = User.objects.get(username='john')
user.set_password('newpassword')
user.save()
  • To check if a given raw password matches the user's password, you can use the check_password() method:
from django.contrib.auth.hashers import check_password

user = User.objects.get(username='john')
is_correct_password = check_password('newpassword')
  1. User authentication in Django: Django's authentication system includes a built-in User model. You can use it to handle user registration, login, and other authentication-related tasks.

    from django.contrib.auth.models import User
    
    # Creating a new user
    user = User.objects.create_user(username='john_doe', password='password123')
    
    # Authenticating a user
    user = authenticate(request, username='john_doe', password='password123')
    
  2. Django auth app models: Django's auth app provides models like User, Group, and Permission. These models handle user-related data, group management, and permissions.

    from django.contrib.auth.models import User, Group, Permission
    
    # Accessing User, Group, and Permission models
    user = User.objects.get(username='john_doe')
    group = Group.objects.get(name='Staff')
    permission = Permission.objects.get(codename='can_view_dashboard')
    
  3. Customizing Django auth app forms: You can customize authentication forms in Django to include additional fields or modify their behavior.

    from django import forms
    from django.contrib.auth.forms import AuthenticationForm
    
    class CustomAuthenticationForm(AuthenticationForm):
        # Add custom fields or override methods here
    
  4. Login and logout views in Django auth app: Django provides built-in views for handling user login and logout.

    from django.contrib.auth.views import LoginView, LogoutView
    
    # URL patterns
    path('login/', LoginView.as_view(), name='login'),
    path('logout/', LogoutView.as_view(), name='logout'),
    
  5. Django authentication middleware: Middleware in Django allows you to process requests globally. Authentication middleware handles user authentication for each request.

    MIDDLEWARE = [
        # ...
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        # ...
    ]
    
  6. Signals in Django auth app: Signals allow you to attach custom functions to certain events in Django. In the auth app, signals can be used for tasks like sending email notifications on user creation.

    from django.db.models.signals import post_save
    from django.dispatch import receiver
    from django.contrib.auth.models import User
    
    @receiver(post_save, sender=User)
    def user_created(sender, instance, created, **kwargs):
        if created:
            # Send welcome email or perform other actions
    
  7. Group and permission management in Django auth: Django provides a way to organize users into groups and manage permissions at the group level.

    # Adding a user to a group
    user.groups.add(group)
    
    # Checking user permissions
    if user.has_perm('app_name.can_edit_content'):
        # Perform actions based on permission
    
  8. Django social authentication with auth app: You can integrate social authentication with third-party providers using packages like django-allauth or python-social-auth.

    # Using python-social-auth for GitHub authentication
    SOCIAL_AUTH_GITHUB_KEY = 'your-github-key'
    SOCIAL_AUTH_GITHUB_SECRET = 'your-github-secret'