如何检查用户是否已登录(如何正确使用user.is_authenticated)? [英] How to check if a user is logged in (how to properly use user.is_authenticated)?

查看:394
本文介绍了如何检查用户是否已登录(如何正确使用user.is_authenticated)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看此网站,但似乎无法弄清楚该怎么做,因为它不起作用.我需要检查当前的站点用户是否已登录(已验证),并且正在尝试:

I am looking over this website but just can't seem to figure out how to do this as it's not working. I need to check if the current site user is logged in (authenticated), and am trying:

request.user.is_authenticated

尽管确保用户已登录,但只会返回:

despite being sure that the user is logged in, it returns just:

>

我能够执行其他请求(来自上述网址的第一部分),例如:

I'm able to do other requests (from the first section in the url above), such as:

request.user.is_active

返回成功的响应.

推荐答案

针对Django 1.10+的更新:is_authenticated现在是Django 1.10中的一个属性.为了向后兼容,该方法仍然存在,但是将在Django 2.0中删除.

Update for Django 1.10+: is_authenticated is now an attribute in Django 1.10. The method still exists for backwards compatibility, but will be removed in Django 2.0.

对于Django 1.9和更早版本:

is_authenticated是一个函数.你应该这样称呼

is_authenticated is a function. You should call it like

if request.user.is_authenticated():
    # do something if the user is authenticated

正如Peter Rowell所指出的那样,可能让您感到困扰的是,在默认的Django模板语言中,您无需在括号内附加调用函数的功能.因此,您可能已经在模板代码中看到过类似的内容:

As Peter Rowell pointed out, what may be tripping you up is that in the default Django template language, you don't tack on parenthesis to call functions. So you may have seen something like this in template code:

{% if user.is_authenticated %}

但是,在Python代码中,它确实是User类中的方法.

However, in Python code, it is indeed a method in the User class.

这篇关于如何检查用户是否已登录(如何正确使用user.is_authenticated)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆