What more do I need to do to have Django's @login_required decorator work?

Viewed 19182

I am trying to use Django's account system, including the @login_required decorator. My settings.py file includes django.contrib.auth and I have done a syncdb.

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/accounts/login/?next=/
Using the URLconf defined in dashboard.urls, Django tried these URL patterns, in this order:
^$ [name='home']
The current URL, accounts/login/, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

I see the above after trying to @login_required-decorate my home view.

It seems to be choking because it is redirected to accounts/login/, which I have not prepared for in my urls.py.

What can I add to urls.py or elsewhere so that the login_required decorator will do its usual behaviour?

Thanks,

3 Answers

What worked for me in Django 2.2.1 - include re_path('^accounts/', admin.site.urls), in my project urls.py:

urls.py

from django.conf import settings
from django.conf.urls import include
from django.conf.urls import re_path
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path('^accounts/', admin.site.urls),
]

And in my views.py:

views.py

from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView

@method_decorator(login_required, name='dispatch')
class HomePageView(TemplateView):
    """
    Home Page View
    """
    template_name = 'amp/home.html'

Hope that helps.

UPDATE: To avoid warnings from django in regards to admin urls being loaded twice, I used a redirect instead in urls.py:

urls.py

urlpatterns = [
    re_path('^accounts/', admin.site.urls),
    re_path(r'^admin/', RedirectView.as_view(url='/accounts/', permanent=True))
]

More on redirect view here.

path('accounts/login/', admin.site.urls),

Add this line in your urls.py project folder. Then it will work fine.

from django.contrib.auth.decorators import login_required
@login_required(login_url='/accounts/login/')

Add above two lines in your views.py file.

Related