django-registration:如何在显示页面之前检查用户是否已登录

时间:2013-01-08 16:39:13

标签: django django-authentication django-registration

我跟着this page建立了一个django注册网站。它非常棒,注册和身份验证很好。

但是,它没有告诉我,在显示网页之前,如何检查用户是否已登录,该用户是谁?以及如何在登录后将用户定向到新页面?

谢谢!

3 个答案:

答案 0 :(得分:12)

在视图中,您可以使用if request.user.is_authenticated():,当前用户的变量为request.user

在模板中,您可以使用{% if user.is_authenticated %},当前用户的变量为user

要在登录后重定向用户,您可以在LOGIN_REDIRECT_URL

中设置settings.py变量

答案 1 :(得分:7)

在.py文件中

您可以在每个视图中使用它

if not request.user.is_authenticated():
   #do something

或在每个视图之前

@login_required

请记住,这个需要导入from django.contrib.auth.decorators import login_required
并且您可能还想在LOGIN_URL = "/loginurl/"中编写settings.py,以便将未登录的用户重定向到特定的网址,而不是默认的accounts/login}

在.html文档中

{% if not user.is_authenticated %}
Login is required
{% endif %}

登录后重定向

您可以修改LOGIN_REDIRECT_URL

中的settings.py 用户登录后

redirect("/indexpage") 最后一个需要导入from django.shortcuts import redirect

答案 2 :(得分:4)

您还可以在视图之前使用需要登录的装饰器:

@login_required()

如果未登录的用户尝试访问您的视图,则会将用户重定向到登录页面

您可以在此页面上找到更多信息: https://docs.djangoproject.com/en/dev/topics/auth/default/#topic-authorization