User Authentication - potatoscript/django GitHub Wiki

🔐 Django User Authentication – Login & Logout

In this tutorial, we’ll walk you through how to set up user authentication in Django, focusing on how to allow users to log in and log out. We’ll cover the steps in a way that’s simple to understand but also highly professional for any web development project.


📂 Step 1: Setting Up User Authentication

Django comes with a built-in authentication system that handles tasks like logging in, logging out, password management, and user sessions. For this, we will use Django’s auth app.

🗂️ Add django.contrib.auth to Installed Apps

Django comes with the auth app already included in the default project settings. To confirm, check if it's in your INSTALLED_APPS in settings.py:

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

If it’s not there, add it. The auth app is what handles the login and logout functionalities.


📂 Step 2: Setting Up URLs for Login & Logout

Django provides pre-built views for login and logout. To make them work, you need to set up URLs.

  1. Create a file called urls.py in your app folder (if it doesn’t already exist). Inside that file, add the following code to include Django’s built-in login and logout views:
from django.urls import path
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('login/', auth_views.LoginView.as_view(), name='login'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]

This sets up two URLs:

  • /login/ for logging in.
  • /logout/ for logging out.

📂 Step 3: Creating Login and Logout Templates

Django’s built-in login and logout views look for HTML templates in specific locations. By default:

  • The Login view looks for registration/login.html.
  • The Logout view looks for registration/logged_out.html.

🖼️ Step 3.1: Create a Login Template

Create a directory named registration in your project’s templates folder (create the templates folder if it doesn’t exist). Inside the registration folder, create a file called login.html.

<!-- registration/login.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>
    
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Login</button>
    </form>

    <p>Don't have an account? <a href="{% url 'signup' %}">Sign up here</a></p>
</body>
</html>

This template displays a login form. It uses the built-in form {{ form.as_p }} to display the form fields provided by Django’s login form.

🖼️ Step 3.2: Create a Logged Out Template

Create another file named logged_out.html inside the registration folder.

<!-- registration/logged_out.html -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Logged Out</title>
</head>
<body>
    <h2>You have been logged out successfully.</h2>
    <p><a href="{% url 'login' %}">Login again</a></p>
</body>
</html>

This template displays a simple message saying the user has logged out successfully.


📂 Step 4: Configuring the Login Redirect

After logging in, Django needs to know where to redirect the user. By default, Django redirects to /accounts/profile/ after logging in. You can change this by setting the LOGIN_REDIRECT_URL in settings.py.

For example, if you want to redirect users to the homepage after login:

# settings.py

LOGIN_REDIRECT_URL = '/'

This makes sure that once users log in successfully, they are redirected to the homepage.


📂 Step 5: Handling Unauthorized Access (Optional)

You might want to ensure that only authenticated users can access certain views. You can restrict access using the @login_required decorator.

🖼️ Example: Protecting Views with Login Required

For example, let’s protect a view called dashboard that should only be accessible by logged-in users.

# views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render

@login_required
def dashboard(request):
    return render(request, 'dashboard.html')

Now, if a user who is not logged in tries to visit /dashboard/, they’ll be redirected to the login page automatically.

You can also specify a custom redirect URL in the decorator:

@login_required(login_url='/login/')
def dashboard(request):
    return render(request, 'dashboard.html')

This will redirect unauthenticated users to the /login/ URL.


📂 Step 6: Testing Login and Logout

  1. Run the server:

    python manage.py runserver
  2. Visit the login page: Open your browser and go to http://127.0.0.1:8000/login/ to test the login form. Enter valid credentials (you can create a user using python manage.py createsuperuser).

  3. Logout: After logging in, visit http://127.0.0.1:8000/logout/ to log out.


🧩 Summary of the Steps

Step What Happens
1. Setup URLs Configure login and logout URLs using Django's built-in views.
2. Create Login Template Create login.html to display the login form.
3. Create Logged Out Template Create logged_out.html for the logout confirmation.
4. Configure Redirect Set LOGIN_REDIRECT_URL in settings.py to redirect after login.
5. Protect Views Use @login_required to protect views from unauthorized access.
6. Testing Test login and logout in the development server.

⚠️ **GitHub.com Fallback** ⚠️