在Django中,@login_required
裝飾器用于確保用戶在訪問某個視圖時已經登錄。如果用戶未登錄,那么Django會自動重定向用戶到登錄頁面。默認情況下,Django使用/accounts/login/
作為登錄URL。如果用戶試圖訪問一個需要登錄的視圖,比如/myblog/post/new/
,但未登錄,Django會將用戶重定向到/accounts/login/?next=/myblog/post/new/
。
這里的 next
參數告訴登錄視圖,在用戶成功登錄后,應將其重定向回到他們最初試圖訪問的頁面。
如果你想自定義登錄URL,可以在Django的設置文件settings.py
中更改LOGIN_URL
配置項。例如:
LOGIN_URL = '/custom_login/'
這樣,當未登錄用戶試圖訪問需要登錄的視圖時,他們會被重定向到/custom_login/
而不是默認的/accounts/login/
。
示例
展示如何使用@login_required
以及如何自定義登錄URL:
1. views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required@login_required
def post_new(request):# Your view logic herereturn render(request, 'post_new.html')
2. settings.py
# Ensure you have the following setting
LOGIN_URL = '/custom_login/'
3. urls.py
from django.urls import path
from . import viewsurlpatterns = [path('myblog/post/new/', views.post_new, name='post_new'),path('custom_login/', views.custom_login_view, name='custom_login'),
]
通過這些設置,未登錄用戶在訪問/myblog/post/new/
時,將會被重定向到/custom_login/?next=/myblog/post/new/
。
局部指定
直接在view裝飾器指定url地址。
from django.shortcuts import render
from django.contrib.auth.decorators import login_required@login_required(login_url='/custom_login/login')
def post_new(request):# Your view logic herereturn render(request, 'post_new.html')