[英]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 裝飾器執行其通常的行為?
謝謝,
在 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.