Django 1.6 用户验证机制

参考:

https://docs.djangoproject.com/en/1.6/ref/contrib/auth/

1. 校验一个用户名和密码(不登录)

from django.contrib.auth import authenticate user = authenticate(username='john', password='secret') if user is not None: # the password verified for the user if user.is_active: print("User is valid, active and authenticated") else: print("The password is valid, but the account has been disabled!") else: # the authentication system was unable to verify the username and password print("The username and password were incorrect.")

2. 登录一个用户(事实上不需要密码)

from django.contrib.auth import authenticate, login

def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) # Redirect to a success page. else: # Return a 'disabled account' error message else: # Return an 'invalid login' error message.

3. 注销(登出)用户

from django.contrib.auth import logout

def logout_view(request): logout(request) # Redirect to a success page.

4. 获取当前登录的用户

通过 request.user 可以获取当前登录的用户;

如果没有登录,那么获取的是一个 AnonymousUser 对象,可以通过下面的方式检查是否已经登录:

from django.shortcuts import redirect

def my_view(request): if not request.user.is_authenticated(): return redirect('/login/?next=%s' % request.path)

5. 修改/验证一个用户的密码

参见本文开头的文档链接

 


【转载请附】愿以此功德,回向 >>

原文链接:https://www.huangwenchao.com.cn/2014/03/django-auth.html【Django 1.6 用户验证机制】

发表评论

电子邮件地址不会被公开。 必填项已用*标注