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 / views.py

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 / apps.py