django.contrib.auth.decorators login_required Example Python Code (2024)

Django'slogin_requiredfunction is used to secure views in your web applications by forcingthe client to authenticate with a valid logged-in User. This decoratoris a handy shortcut that can reduce the amount of code in your viewfunctions and eliminate the need for every function to haveboilerplate like if not request.user.is_authenticated:.

Example 1 from dccnsys

dccnsys is a conference registrationweb app built in Django. The code is open source under theMIT license.

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

dccnsys / wwwdccn / registration / views.py

from django.contrib.auth import get_user_modelfrom django.contrib.auth.decorators import login_requiredfrom django.shortcuts import render, redirectfrom users.models import generate_avatarfrom users.forms import (PersonalForm, ProfessionalForm, SubscriptionsForm)User = get_user_model()@login_requireddef personal(request): profile = request.user.profile if request.method == 'POST': form = PersonalForm(request.POST, instance=profile) if form.is_valid(): form.save() profile.avatar = generate_avatar(profile) profile.save() return redirect('register-professional') else: form = PersonalForm(instance=profile) return render(request, 'registration/personal.html', { 'form': form })@login_requireddef professional(request): profile = request.user.profile if request.method == 'POST': form = ProfessionalForm(request.POST, instance=profile) if form.is_valid(): form.save() return redirect('register-subscriptions') else: form = ProfessionalForm(instance=profile) return render(request, 'registration/professional.html', { 'form': form })@login_requireddef subscriptions(request): subscriptions = request.user.subscriptions if request.method == 'POST': form = SubscriptionsForm(request.POST, instance=subscriptions) if form.is_valid(): form.save() request.user.has_finished_registration = True request.user.save() return redirect('home') else: 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 ofDjango. The code for the project is available opensource under acustom license written by Tangent Communications PLC.

The following login_required example is one that surprised mea bit because I had not previously seen login_required appliedon the parameter to the urlfunction. Typically the decorator is used on view function whereit is defined, but this way works as well as long as you areconsistent about where you apply the decorator in your code base.

django-oscar / src / oscar / apps / customer / apps.py

from django.conf.urls import urlfrom django.contrib.auth.decorators import login_requiredfrom django.utils.translation import gettext_lazy as _from django.views import genericfrom oscar.core.application import OscarConfigfrom oscar.core.loading import get_classclass 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', 'AccountSummaryView') self.order_history_view = get_class('customer.views', 'OrderHistoryView') self.order_detail_view = get_class('customer.views', 'OrderDetailView') ## ... 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(), name='login'), url(r'^logout/$', self.logout_view.as_view(), name='logout'), url(r'^register/$', self.register_view.as_view(), name='register'), url(r'^$', login_required(self.summary_view.as_view()), name='summary'), url(r'^change-password/$', login_required(self.change_password_view.as_view()), name='change-password'), # Profile url(r'^profile/$', login_required(self.profile_view.as_view()), name='profile-view'), url(r'^profile/edit/$', login_required(self.profile_update_view.as_view()), name='profile-update'), url(r'^profile/delete/$', login_required(self.profile_delete_view.as_view()), name='profile-delete'),## the file continues with further examples that show the same usage
django.contrib.auth.decorators login_required Example Python Code (2024)
Top Articles
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 5954

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.