[英]django-registration: how do I check whether the user is logged in before displaying a page
我按照這個頁面建立了一個 django 注冊站點。 它非常棒,注冊和身份驗證都很好地包裝了。
但是,它沒有告訴我,在顯示網頁之前,我如何檢查用戶是否已登錄,該用戶是誰? 以及如何在登錄后將用戶定向到新頁面?
謝謝!
在一個視圖中,可以使用if request.user.is_authenticated():
並且當前用戶的變量是request.user
在模板中,您可以使用{% if user.is_authenticated %}
並且當前用戶的變量是user
為了在登錄后重定向用戶,您可以在settings.py
中settings.py
LOGIN_REDIRECT_URL
變量
在 .py 文件中
您可以在每個視圖中使用它
if not request.user.is_authenticated:
#do something
或者這只是在每個視圖之前
@login_required
請記住,這需要from django.contrib.auth.decorators import login_required
你可能還需要寫入LOGIN_URL = "/loginurl/"
在你的settings.py
獲得非登錄用戶重定向到一個特定的URL,而不是默認的一個accounts/login
)
在 .html 文件中
{% if not user.is_authenticated %}
Login is required
{% endif %}
登錄后重定向
您可以在settings.py
修改LOGIN_REDIRECT_URL
或在用戶登錄后redirect("/indexpage")
。
最后一個需要from django.shortcuts import redirect
您還可以在視圖之前使用需要登錄的裝飾器:
@login_required()
如果未登錄的用戶嘗試訪問您的視圖,它會將用戶重定向到登錄頁面
您將在此頁面上找到更多信息: https : //docs.djangoproject.com/en/dev/topics/auth/default/#topic-authorization
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.