django - 总结 - 用户认证组件

用户认证组件

django - 总结 - 用户认证组件


 from django.contrib import auth

 从auth_user表中获取对象,没有返回None,其中密码为密文,使用了加密算法
user = auth.authenticate(username=user, password=pwd) 让上边找到的user对象赋给request.user使其成为全局变量,方便以后调用
给已认证的用户附加上seession id 等信息
auth.login(request, user) # request.user:当前登录对象 from django.contrib.auth import logout
注销用户:删除session表对应的记录
logout(request)
User对象
用于检查用户是否已经登录True/False(user/)
user.is_authenticated
user.is_amonymous  # 是否是匿名用户 如果没有登录,跳转到登录界面,登陆成功在跳转回来
1、自定义
def my_view(request):
if not request.user.is_authenticated:
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
2、django内置 from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
... 我们需要配置登录界面路径LOGIN_URL="/login/"
auth_user表操作
 from django.contrib.auth.models import User
-------------创建新用户-------------------
user = User.objects.create_user(username='',password='',email='')
User.objects.create_superuser()
---------------------检查密码正误-----
用户需要修改密码的时候 首先要让他输入原来的密码 ,如果给定的字符串通过了密码检查,返回 True
7 print("raw_pwd", user.check_password(pwd))
-------------------------修改密码--------
9 user = User.objects.get(username='')
user.set_password(password='')
user.save 

 def sign_up(request):

     state = None
if request.method == 'POST': password = request.POST.get('password', '')
repeat_password = request.POST.get('repeat_password', '')
email=request.POST.get('email', '')
username = request.POST.get('username', '')
if User.objects.filter(username=username):
state = 'user_exist'
else:
new_user = User.objects.create_user(username=username, password=password,email=email)
new_user.save() return redirect('/book/')
content = {
'state': state,
'user': None,
}
return render(request, 'sign_up.html', content) 

注册:

 @login_required
def set_password(request):
user = request.user
state = None
if request.method == 'POST':
old_password = request.POST.get('old_password', '')
new_password = request.POST.get('new_password', '')
repeat_password = request.POST.get('repeat_password', '')
if user.check_password(old_password):
if not new_password:
state = 'empty'
elif new_password != repeat_password:
state = 'repeat_error'
else:
user.set_password(new_password)
user.save()
return redirect("/log_in/")
else:
state = 'password_error'
content = {
'user': user,
'state': state,
}
return render(request, 'set_password.html', content)

修改密码:


扩展auth表
from django.contrib.auth.models import AbstractUser

class UserInfo(AbstractUser):
tel = models.CharField(max_length=32) 在setting配置AUTH_USER_MODEL = "app01.UserInfo"
from django.contrib.auth.models import User

class UserInfo(User):
tel = models.CharField(max_length=)
   class Meta:
     super(User.Meta)
     。。。。  
      
不用再配置里更改了

上一篇:javascript按中文首字母排序


下一篇:Django之路——11 Django用户认证组件 auth