簡體   English   中英

我還需要做什么才能讓 Django 的 @login_required 裝飾器工作?

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

我正在嘗試使用 Django 的帳戶系統,包括 @login_required 裝飾器。 我的 settings.py 文件包含django.contrib.auth並且我已經完成了一個 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.

在嘗試@login_required-decorate 我的主視圖后,我看到了上述內容。

它似乎令人窒息,因為它被重定向到帳戶/登錄/,我在我的 urls.py 中沒有准備好。

我可以在 urls.py 或其他地方添加什么,以便 login_required 裝飾器執行其通常的行為?

謝謝,

在您的設置中設置LOGIN_URL 默認值為'/accounts/login/'

裝飾器還接受一個可選的login_url參數:

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

而且,從文檔

請注意,如果您不指定 login_url 參數,則需要確保 settings.LOGIN_URL 和您的登錄視圖正確關聯。 例如,使用默認值,將以下行添加到您的 URLconf:

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

在 Django 2.2.1 中對我有用的東西 - 在我的項目 urls.py 中包含re_path('^accounts/', admin.site.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),
]

在我的views.py中:

視圖.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'

希望有幫助。

更新:為了避免來自 django 的關於管理 url 被加載兩次的警告,我在 urls.py 中使用了重定向:

網址.py

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

更多關於重定向視圖的信息

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

將此行添加到您的urls.py項目文件夾中。 然后它會正常工作。

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

在您的views.py文件中添加以上兩行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM