Skip to main content

Django Authentication Views

Introduction​

When building web applications, implementing a robust user authentication system is crucial. Django provides a set of pre-built views that handle common authentication tasks, saving you time and ensuring security best practices.

In this guide, we'll explore Django's authentication views, which handle operations like:

  • User login and logout
  • Password changes
  • Password resets
  • Account registration (with some customization)

These views connect directly to Django's authentication system and can be quickly integrated into your application with minimal setup.

Understanding Django Authentication Views​

Django's built-in authentication views are located in django.contrib.auth.views. These views provide ready-made functionality for common authentication tasks, complete with forms and templates.

Key Benefits of Django Authentication Views​

  1. Security: Implements security best practices by default
  2. Time-saving: Eliminates the need to write authentication logic from scratch
  3. Customizable: Can be extended or modified to suit your application's needs
  4. Well-tested: Thoroughly tested by the Django community

Setting Up Authentication URLs​

To use Django's authentication views, you first need to include them in your URL configuration. Here's how to set them up:

  1. First, let's create a new file called urls.py in your application directory or update your project's main urls.py:
python
from django.urls import path, include
from django.contrib.auth import views as auth_views

urlpatterns = [
# Your other URL patterns...
path('accounts/', include('django.contrib.auth.urls')),

# If you prefer to define URLs individually:
# path('login/', auth_views.LoginView.as_view(), name='login'),
# path('logout/', auth_views.LogoutView.as_view(), name='logout'),
# path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'),
# path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'),
# path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'),
# path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'),
# path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
# path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]

By including django.contrib.auth.urls, Django automatically sets up all the standard authentication URLs. Alternatively, you can define them individually for more control.

Available Authentication Views​

Let's explore the built-in authentication views Django provides:

LoginView​

The LoginView handles user authentication:

python
from django.contrib.auth.views import LoginView

# In your urls.py
path('login/', LoginView.as_view(), name='login'),

Default behavior:

  • Renders login form template (registration/login.html)
  • Processes form submission
  • Redirects to settings.LOGIN_REDIRECT_URL after successful login (defaults to /accounts/profile/)
  • URL: /accounts/login/

Template Example (registration/login.html):

html
{% extends 'base.html' %}

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

Customization Example:

python
path('login/', LoginView.as_view(
template_name='custom_login.html',
redirect_authenticated_user=True,
extra_context={'title': 'Sign In'}
), name='login'),

LogoutView​

The LogoutView handles user logout:

python
from django.contrib.auth.views import LogoutView

# In your urls.py
path('logout/', LogoutView.as_view(), name='logout'),

Default behavior:

  • Logs the user out
  • Redirects to settings.LOGOUT_REDIRECT_URL if set, otherwise to '/'
  • URL: /accounts/logout/

Customization Example:

python
path('logout/', LogoutView.as_view(
next_page='login',
template_name='custom_logout.html',
), name='logout'),

Password Change Views​

Django provides two views for handling password changes:

PasswordChangeView​

python
from django.contrib.auth.views import PasswordChangeView

# In your urls.py
path('password_change/', PasswordChangeView.as_view(), name='password_change'),

Default behavior:

  • Renders password change form (registration/password_change_form.html)
  • Validates current password and new password
  • Redirects to password_change_done on success
  • URL: /accounts/password_change/

PasswordChangeDoneView​

python
from django.contrib.auth.views import PasswordChangeDoneView

# In your urls.py
path('password_change/done/', PasswordChangeDoneView.as_view(), name='password_change_done'),

Default behavior:

  • Renders success message template (registration/password_change_done.html)
  • URL: /accounts/password_change/done/

Password Reset Views​

Django provides four views for handling password resets:

PasswordResetView​

python
from django.contrib.auth.views import PasswordResetView

# In your urls.py
path('password_reset/', PasswordResetView.as_view(), name='password_reset'),

Default behavior:

  • Renders password reset form (registration/password_reset_form.html)
  • Processes the form to send a reset email
  • Redirects to password_reset_done on success
  • URL: /accounts/password_reset/

Email Configuration Example:

First, make sure you have email settings in your settings.py:

python
# Email settings for development (use a proper email backend in production)
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

Template Example (registration/password_reset_email.html):

html
{% autoescape off %}
Hello,

You're receiving this email because you requested a password reset for your user account at {{ site_name }}.

Please go to the following page and choose a new password:

{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}

Your username, in case you've forgotten: {{ user.get_username }}

Thanks!
{% endautoescape %}

PasswordResetDoneView​

python
from django.contrib.auth.views import PasswordResetDoneView

# In your urls.py
path('password_reset/done/', PasswordResetDoneView.as_view(), name='password_reset_done'),

Default behavior:

  • Renders confirmation message template (registration/password_reset_done.html)
  • URL: /accounts/password_reset/done/

PasswordResetConfirmView​

python
from django.contrib.auth.views import PasswordResetConfirmView

# In your urls.py
path('reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'),

Default behavior:

  • Validates the token from the reset link
  • Renders password reset form (registration/password_reset_confirm.html)
  • Redirects to password_reset_complete on success
  • URL: /accounts/reset/<uidb64>/<token>/

PasswordResetCompleteView​

python
from django.contrib.auth.views import PasswordResetCompleteView

# In your urls.py
path('reset/done/', PasswordResetCompleteView.as_view(), name='password_reset_complete'),

Default behavior:

  • Renders success message template (registration/password_reset_complete.html)
  • URL: /accounts/reset/done/

Creating Required Templates​

Django's authentication views need templates to render. By default, they look for templates in a registration directory within your templates folder.

Here's how to create the required templates:

  1. Create a directory structure in your project:
your_project/
├── templates/
│ └── registration/
│ ├── login.html
│ ├── logged_out.html
│ ├── password_change_form.html
│ ├── password_change_done.html
│ ├── password_reset_form.html
│ ├── password_reset_done.html
│ ├── password_reset_confirm.html
│ ├── password_reset_complete.html
│ └── password_reset_email.html
  1. Make sure your settings.py has templates configured:
python
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'], # Make sure this is included
'APP_DIRS': True,
# ... other settings ...
},
]

Real-World Example: Complete Authentication System​

Let's build a complete authentication system for a simple blog application:

Project Structure​

blog_project/
├── blog/
│ └── views.py
├── templates/
│ ├── base.html
│ ├── home.html
│ └── registration/
│ └── (auth templates)
└── blog_project/
├── settings.py
└── urls.py

1. Configure settings.py​

python
# Add these settings to your settings.py

# Authentication settings
LOGIN_REDIRECT_URL = 'home' # Redirect to home page after login
LOGOUT_REDIRECT_URL = 'home' # Redirect to home page after logout

# For password reset functionality to work, configure email
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # Development only

2. Set up URLs in urls.py​

python
from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView

urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
path('', TemplateView.as_view(template_name='home.html'), name='home'),
]

3. Create base.html template​

html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{% block title %}My Blog{% endblock %}</title>
<style>
body { padding: 20px; font-family: Arial, sans-serif; }
nav { margin-bottom: 20px; padding: 10px; background-color: #f5f5f5; }
.messages { color: green; }
.errorlist { color: red; }
</style>
</head>
<body>
<header>
<nav>
<a href="{% url 'home' %}">Home</a> |
{% if user.is_authenticated %}
Hello, {{ user.username }}! |
<a href="{% url 'password_change' %}">Change Password</a> |
<a href="{% url 'logout' %}">Logout</a>
{% else %}
<a href="{% url 'login' %}">Login</a> |
<a href="{% url 'password_reset' %}">Reset Password</a>
{% endif %}
</nav>
</header>
<main>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}

{% block content %}{% endblock %}
</main>
</body>
</html>

4. Create home.html template​

html
{% extends 'base.html' %}

{% block title %}Home{% endblock %}

{% block content %}
<h1>Blog Home</h1>
{% if user.is_authenticated %}
<p>Welcome to your dashboard, {{ user.username }}!</p>
<p>You can now create and manage your blog posts.</p>
{% else %}
<p>Welcome to our blog!</p>
<p>Please <a href="{% url 'login' %}">login</a> to access your dashboard.</p>
{% endif %}
{% endblock %}

5. Create login.html template​

html
{% extends 'base.html' %}

{% block title %}Login{% endblock %}

{% block content %}
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
<p><a href="{% url 'password_reset' %}">Forgot your password?</a></p>
{% endblock %}

6. Testing​

After setting up these files:

  1. Run migrations: python manage.py migrate
  2. Create a superuser: python manage.py createsuperuser
  3. Run the server: python manage.py runserver
  4. Visit http://127.0.0.1:8000/ and try:
    • Logging in with your superuser credentials
    • Logging out
    • Changing your password
    • Requesting a password reset

Customizing Authentication Views​

Django's authentication views can be customized in several ways:

1. Custom Template Paths​

python
from django.contrib.auth.views import LoginView

urlpatterns = [
path('login/', LoginView.as_view(
template_name='custom/my_login.html'
), name='login'),
]

2. Custom Form Classes​

python
from django.contrib.auth.views import PasswordResetView
from .forms import CustomPasswordResetForm

urlpatterns = [
path('password_reset/', PasswordResetView.as_view(
form_class=CustomPasswordResetForm
), name='password_reset'),
]

3. Custom Success URLs​

python
from django.contrib.auth.views import LoginView

urlpatterns = [
path('login/', LoginView.as_view(
success_url='/dashboard/' # or reverse_lazy('dashboard')
), name='login'),
]

4. Adding Extra Context​

python
from django.contrib.auth.views import LoginView

urlpatterns = [
path('login/', LoginView.as_view(
extra_context={'title': 'Sign In', 'site_name': 'My Awesome Blog'}
), name='login'),
]

5. Complete Subclassing​

For more extensive customization, you can subclass the view:

python
from django.contrib.auth.views import LoginView
from django.urls import reverse_lazy

class CustomLoginView(LoginView):
template_name = 'custom/login.html'
redirect_authenticated_user = True

def get_success_url(self):
# Custom logic to determine where to redirect
if self.request.user.is_staff:
return reverse_lazy('admin:index')
return reverse_lazy('dashboard')

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = 'Sign in to your account'
return context

# In urls.py
urlpatterns = [
path('login/', CustomLoginView.as_view(), name='login'),
]

Creating a User Registration View​

Django doesn't provide a built-in view for user registration, but you can easily create one:

python
# views.py
from django.contrib.auth.forms import UserCreationForm
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy

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

# urls.py
from .views import SignUpView

urlpatterns = [
# Other URL patterns...
path('accounts/signup/', SignUpView.as_view(), name='signup'),
]

Template Example (registration/signup.html):

html
{% extends 'base.html' %}

{% block title %}Sign Up{% endblock %}

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

Summary​

Django's built-in authentication views offer a secure, feature-rich foundation for user authentication in your web applications. Key points to remember:

  1. Authentication views handle user login, logout, password changes, and password resets
  2. Include django.contrib.auth.urls in your URL configuration for quick setup
  3. Create templates in the registration/ directory for the views to render
  4. Customize views by passing parameters or subclassing them
  5. Configure settings like LOGIN_REDIRECT_URL to control behavior

These views follow Django's "batteries included" philosophy, giving you professional-grade authentication functionality with minimal effort.

Additional Resources​

Exercises​

  1. Basic Authentication Setup: Create a new Django project and implement login and logout functionality using Django's built-in authentication views.

  2. Password Reset Flow: Implement a complete password reset flow, including setting up a real email backend (like Gmail) to send password reset emails.

  3. Custom User Registration: Create a custom registration form that extends UserCreationForm to collect additional user information (e.g., email address, first name, last name).

  4. Template Customization: Customize all the authentication templates with a consistent design and user-friendly messages.

  5. Authentication Integration: Build a simple blog application where only logged-in users can create posts, but anyone can read them. Use authentication views and the @login_required decorator.



If you spot any mistakes on this website, please let me know at feedback@compilenrun.com. I’d greatly appreciate your feedback! :)