Django

⌘K
  1. Home
  2. Django
  3. chat
  4. User To User Chat
  5. Part 2: Setting Up User Authentication

Part 2: Setting Up User Authentication

In this part, we’ll configure user authentication for your project. We’ll set up user registration, login, and logout functionality and display a list of all users except the currently logged-in user.


Step-by-Step Instructions


Step 1: Create URLs for User Authentication

  1. Inside the chat app, create a urls.py file:
touch chat/urls.py

Add the following code to chat/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('register/', views.register, name='register'),
    path('login/', views.login_user, name='login'),
    path('logout/', views.logout_user, name='logout'),
    path('users/', views.user_list, name='user_list'),
]

Include these URLs in the main urls.py:

from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('chat.urls')),  # Include chat app URLs
]

Step 2: Create Views for Authentication

  1. Open chat/views.py and add the following imports:
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required

Add the registration view:

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('login')
    else:
        form = UserCreationForm()
    return render(request, 'chat/register.html', {'form': form})

Add the login view:

def login_user(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('user_list')
    else:
        form = AuthenticationForm()
    return render(request, 'chat/login.html', {'form': form})

Add the logout view:

def logout_user(request):
    logout(request)
    return redirect('login')

Add the user list view:

@login_required
def user_list(request):
    users = User.objects.exclude(id=request.user.id)  # Exclude the current user
    return render(request, 'chat/user_list.html', {'users': users})

Step 3: Create Templates

  1. Create a templates folder in the chat app:
mkdir chat/templates
mkdir chat/templates/chat

Create the register.html template:

<h2>Register</h2>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Register</button>
</form>
<p>Already have an account? <a href="{% url 'login' %}">Login here</a>.</p>

Create the login.html template:

<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 'register' %}">Register here</a>.</p>

Create the user_list.html template:

<h2>Users</h2>
<ul>
    {% for user in users %}
        <li>{{ user.username }}</li>
    {% endfor %}
</ul>
<p><a href="{% url 'logout' %}">Logout</a></p>

Step 4: Test the Authentication System

  1. Run the development server:
python manage.py runserver

Navigate to the following URLs to test:

Outcome of Part 2

By the end of this step:

  • Users can register, log in, and log out.
  • The logged-in user can view a list of all other users.

Proceed to Part 3: Setting Up Channels when you’re ready! Let me know if you encounter any issues.

How can we help?