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
- Inside the
chatapp, create aurls.pyfile:
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
- Open
chat/views.pyand 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
- Create a
templatesfolder in thechatapp:
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
- Run the development server:
python manage.py runserver
Navigate to the following URLs to test:
- Registration: http://127.0.0.1:8000/register/
- Login: http://127.0.0.1:8000/login/
- Users List (after login): http://127.0.0.1:8000/users/
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.