Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,

like image 965
Christos Hayward Avatar asked Dec 09 '13 20:12

Christos Hayward


2 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))
]
like image 155
radtek Avatar answered Sep 21 '22 08:09

radtek


Set the LOGIN_URL in your settings. The default value is '/accounts/login/'

The decorator also takes an optional login_url argument:

@login_required(login_url='/accounts/login/')

And, from the docs:

Note that if you don’t specify the login_url parameter, you’ll need to ensure that the settings.LOGIN_URL and your login view are properly associated. For example, using the defaults, add the following line to your URLconf:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),
like image 45
keyser Avatar answered Sep 18 '22 08:09

keyser