[Django]-How to use a custom decorator with default Django auth login view

5👍

You can insert your decorated view before your include and get desired behaviour.

from django.contrib.auth import auth_views

from your_app import example_decorator

urlpatterns = [
    ...
    path('login/', example_decorator(auth_views.LoginView.as_view()), name='login'),
    path('', include('django.contrib.auth.urls')),
    ...
]

1👍

If by default login view you mean the login system, the login function; you can indeed decorate it simply with:

from django.contrib.auth import login

def decorator(f):
    pass

login = decorator(login)

def my_view(request):
    login()

Otherwise if you are talking about a clasview just comment so I can explain it as well.

——- Class Based View ——–

from django.contrib.auth.views import LoginView
from django.utils.decorators import method_decorator

def decorator(f):
    #your decorator

@method_decorator(decorator, name='dispatch')
class MyClass(LoginView):
    pass

As far as the docs go, this should do the trick; although you have to have to write this url yourself, you cannot simply include the auth.urls I’m afraid. Hope this helps.

Leave a comment