django用户账号密码/登陆状态验证

Django用户登陆验证

再学习django 的框架去制作一个web网站过程中,由于设计到了用户一说,所以不可避免的需要涉及到用户登陆及登陆的安全性验证,通过查看官方文档,学习到了两种验证密码的方法

第一种,使用 user.is_authenticated

Read-only attribute which is always True (as opposed to AnonymousUser.is_authenticated which is always False). This is a way to tell if the user has been authenticated. This does not imply any permissions and doesn’t check if the user is active or has a valid session. Even though normally you will check this attribute on request.user to find out whether it has been populated by the AuthenticationMiddleware (representing the currently logged-in user), you should know this attribute is True for any User

user.is_authenticated:始终返回True。这是判断用户是否已通过身份验证的一种方式。这并不意味着任何权限,也不会检查用户是否处于活动状态 –它仅表示用户提供了有效的用户名和密码

在后端验证的方式

if request.user.is_authenticated():
    # Do something for authenticated users.
    ...
else:
    # Do something for anonymous users.
    ...

或者指定验证的账号密码来进行验证

user = authenticate(username=user_name,password=pass_word)

前端验证的方式:由于django原生的支持在前端使用一些后台逻辑的语法,所以可以在前端进行验证判断

{% if request.user.is_authenticated %}
    Do anything....
{% else %}
    Do anything....
{% endif %}

通过user.is_authenticated返回一个bool值,来判断用户是否登陆,但是需要注意的是

<!--在django前端只能通过直接调用结果值调取结果-->
<!--django可能不支持前端调用方法-->
{{request.user.is_authenticated}}

但是在后台is_authenticated无论如何返回都是ture

<!--下面这个判断体肯定会进入的-->
if is_authenticated:
    pass

<!--正确的用法是-->
if is_authenticated():
    pass
<!--这种情况下,才能判断用户是否登陆-->

第二种,使用is_anonymous

is_anonymous:总是返回False。这是区分User和AnonymousUser对象的一种方式。通常,您应该更喜欢使用is_authenticated()来使用此方法。

扫描二维码关注公众号,回复: 1216410 查看本文章

猜你喜欢

转载自blog.csdn.net/newbietan/article/details/79887893