Django User Authentication: Registration, Login, and Logout Guide

3D isometric illustration of users registering, logging in, and logging out at a secure digital gate, representing Django authentication.

A website isn’t much fun if you can’t have users. Django User Authentication provides a robust solution for managing users and access. Building a secure login system from scratch is incredibly difficult and dangerous.

Thankfully, Django comes with a battle-tested authentication system built right in.

Step 1: The URLs

Django already has views for Login and Logout. We just need to give them URLs. Open config/urls.py and add django.contrib.auth.urls.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    # This one line adds login/, logout/, password_change/, etc.
    path('accounts/', include('django.contrib.auth.urls')),
    path('', include('pages.urls')),
]

Step 2: The Templates

Django’s built-in views look for templates in a specific folder: registration/. Create a new top-level folder called templates, and inside it, create registration. (You'll need to tell Django about this new templates folder in settings.py under TEMPLATES -> 'DIRS')

Create templates/registration/login.html:

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

Step 3: Redirects

Where should a user go after they log in? Tell Django in settings.py:

LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'

Step 4: Registration (Sign Up)

Login is built-in, but Registration is not. We need a standard View for it. We use Django’s generic CreateView and the built-in UserCreationForm.

# pages/views.py
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic

class SignUpView(generic.CreateView):
    form_class = UserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'

Now you just need to add a URL for this view, and a signup.html template (which looks just like the login one)!

Similar Posts

Leave a Reply