django.contrib.auth.decorators login_required Example Python Code

Django's login_required function is used to secure views in your web applications by forcing the client to authenticate with a valid logged-in User. This decorator is a handy shortcut that can reduce the amount of code in your view functions and eliminate the need for every function to have boilerplate like if not request.user.is_authenticated:.

Example 1 from dccnsys

dccnsys is a conference registration web app built in Django. The code is open source under the MIT license.

The dccnsys project provides a typical login_required decorator usage example. The decorator is placed on a view function, in this case personal, to protect it from being accessible by unauthenticated users.

dccnsys / wwwdccn / registration /

from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect

from users.models import generate_avatar
from users.forms import (PersonalForm, ProfessionalForm, 

User = get_user_model()

def personal(request):
    profile = request.user.profile
    if request.method == 'POST':
        form = PersonalForm(request.POST, instance=profile)
        if form.is_valid():
            profile.avatar = generate_avatar(profile)
            return redirect('register-professional')
        form = PersonalForm(instance=profile)
    return render(request, 'registration/personal.html', {
        'form': form

def professional(request):
    profile = request.user.profile
    if request.method == 'POST':
        form = ProfessionalForm(request.POST, instance=profile)
        if form.is_valid():
            return redirect('register-subscriptions')
        form = ProfessionalForm(instance=profile)
    return render(request, 'registration/professional.html', {
        'form': form

def subscriptions(request):
    subscriptions = request.user.subscriptions
    if request.method == 'POST':
        form = SubscriptionsForm(request.POST, instance=subscriptions)
        if form.is_valid():
            request.user.has_finished_registration = True
            return redirect('home')
        form = SubscriptionsForm(instance=subscriptions)
    return render(request, 'registration/subscriptions.html', {
        'form': form

Example 2 from django-oscar

django-oscar (project website) is a framework for building e-commerce sites on top of Django. The code for the project is available open source under a custom license written by Tangent Communications PLC.

The following login_required example is one that surprised me a bit because I had not previously seen login_required applied on the parameter to the url function. Typically the decorator is used on view function where it is defined, but this way works as well as long as you are consistent about where you apply the decorator in your code base.

django-oscar / src / oscar / apps / customer /

from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.utils.translation import gettext_lazy as _
from django.views import generic

from oscar.core.application import OscarConfig
from oscar.core.loading import get_class

class CustomerConfig(OscarConfig):
    label = 'customer'
    name = 'oscar.apps.customer'
    verbose_name = _('Customer')

    namespace = 'customer'

    def ready(self):
        from . import receivers  # noqa
        from .alerts import receivers  # noqa

        self.summary_view = get_class('customer.views', 
        self.order_history_view = get_class('customer.views', 
        self.order_detail_view = get_class('customer.views', 

    ## ... abbreviating code not relevant to login_required ...

    def get_urls(self):
        urls = [
            # Login, logout and register doesn't require login
            url(r'^login/$', self.login_view.as_view(), 
            url(r'^logout/$', self.logout_view.as_view(), 
            url(r'^register/$', self.register_view.as_view(), 
            url(r'^$', login_required(self.summary_view.as_view()),

            # Profile

## the file continues with further examples that show the same usage
1. Introduction 2. Development Environments 3. Data 4. Web Development 5. Deployment 6. DevOps Changelog What Full Stack Means About the Author Future Directions Page Statuses Django ExtensionsDjango Example Codedjango.apps.config AppConfigdjango.conf settingsdjango.conf.urls.urldjango.contrib.admindjango.contrib.admin.filters SimpleListFilterdjango.contrib.admin.sites registerdjango.contrib.auth.decorators login_requireddjango.contrib.auth get_user_modeldjango.contrib.auth.hashers make_passworddjango.core.exceptions ImproperlyConfigureddjango.core.mail.messages BaseCommanddjango.db.models AutoFielddjango.db.models BooleanFielddjango.db.models CharFielddjango.db.models DateFielddjango.db.models DateTimeFielddjango.db.models FileFielddjango.db.models ForeignKeydjango.db.models GenericIPAddressFielddjango.db.models ImageFielddjango.db.models IntegerFielddjango.db.models Modeldjango.db.models PositiveIntegerFielddjango.db.models PositiveSmallIntegerFielddjango.db.models.signaldjango.db.models SlugFielddjango.db.models SmallIntegerFielddjango.db.models TextFielddjango.db OperationalErrordjango.dispatch Signaldjango.formsdjango.forms BooleanFielddjango.forms CharFielddjango.forms ChoiceFielddjango.forms DateFielddjango.forms DateTimeFielddjango.forms EmailFielddjango.forms IntegerFielddjango.forms TypedChoiceFielddjango.http Http404django.http HttpResponsedjango.http HttpResponseBadRequestdjango.http HttpResponseForbiddendjango.http HttpResponseNotModifieddjango.http HttpResponsePermanentRedirectdjango.http HttpResponseRedirectdjango.template.response SimpleTemplateResponsedjango.template.response TemplateResponsedjango.urls.pathdjango.urls reverse_lazydjango.urls.exceptions NoReverseMatchdjango.urls.exceptions Resolver404django.utils.html format_htmldjango.utils.timezone ...or view the full table of contents.

Full Stack Python

Full Stack Python is an open book that explains concepts in plain language and provides helpful resources for those topics.
Updates via Twitter & Facebook.

Matt Makai 2012-2020