Django 认证
from django.contrib import auth
1.authenticate()
提供了用户认证,即验证用户名以及密码是否正确,一般需要username和password两个关键字参数
如果通过认证,authenticate()
函数会返回一个User对象,没通过返回None
user=authenticate(username="uaername",password="password"
2.login(request)登陆用户
这个函数使用Django
的session
框架给某个已认证的用户附加上session_id
信息。
使用:
from django.shortcuts import render,redirect,HttpResponse from django.contrib.auth import authenticate,login def auth_view(request): username=request.POST.GET("usernmae") # 获取用户名 password=request.POST.GET("password") # 获取用户的密码 user=authenticate(username=username,password=password) # 验证用户名和密码,返回用户对象 if user: # 如果用户对象存在 login(request,user) # 用户登陆 return redirect("/index/") else: return HttpResponse("用户名或密码错误")
3.logout(request)注销用户
这个函数接受一个HttpResponse
对象,无返回值。
当调用该函数时,当前请求的session信息全部被清除。
即使当前用户没有登陆,调用该函数也不会报错。
from django.shortcuts import render,redirect,HttpResponse from django.contrib.auth import authenticate,login,logout def logout_view(request): logout(request) # 注销用户 return redirect("/index/")
4.user对象
User对象属性:username,password为必填项
- is_staff:判断用户是否拥有网站的管理权限
- is_active:判断是否允许用户登陆,设置为“False”时可以不用删除用户来禁止用户登陆
- User对象的属性值可以在template里取得,如:request.user.username request.user.mobile request.user.is_staff
5.user对象的is_authenticated()
要求:
- 用户登陆后才能访问某些页面
- 如果用户没有登陆就访问本应登陆才能访问的页面时会直接跳转到登陆页面
- 用户在登陆页面登陆后,又会自动跳转到之前访问的页面
方法一:
def view1(request): if not request.user.is_authenticated(): return redirect("/login/")
方法二:
# login_required装饰器 from django.contrib.auth.decorators import login_required @login_required def views(request): pass
如果用户没有登陆,则会跳转到Django默认的登陆URL的"/accountss/login/"
login视图函数可以在settings.py文件中通过LOGIN_URL修改默认
6.创建用户 create_user
from django.contrib.auth.models import User user=User.objects.get(username="username") # 获取用户对象 user.set_password(password="password") # 设置对象的密码 user.save()
7.修改密码check_password(password)
from django.shortcuts import render,redirect,HttpResponse from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User @login_required def change_passwd(request): user=request.user # 获取用户名 msg=None if request.method=='POST': old_password=request.POST.get("old_password","") # 获取原来的密码,默认为空字符串 new_password=request.POST.get("new_password","") # 获取新密码,默认为空字符串 confirm=request.POST.get("confirm_password","") # 获取确认密码,默认为空字符串 if user.check_password(old_password): # 到数据库中验证旧密码通过 if new_password or confirm: # 新密码或确认密码为空 msg="新密码不能为空" elif new_password != confirm: # 新密码与确认密码不一样 msg="两次密码不一致" else: user.set_password(new_password) # 修改密码 user.save() return redirect("/index/") else: msg="旧密码输入错误" return render(request,"change_passwd.html",{"msg":msg})
7.修改密码check_password(password)
方式一
from django.shortcuts import render,redirect,HttpResponse from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User @login_required def change_passwd(request): user=request.user # 获取用户名 msg=None if request.method=='POST': old_password=request.POST.get("old_password","") # 获取原来的密码,默认为空字符串 new_password=request.POST.get("new_password","") # 获取新密码,默认为空字符串 confirm=request.POST.get("confirm_password","") # 获取确认密码,默认为空字符串 if user.check_password(old_password): # 到数据库中验证旧密码通过 if new_password or confirm: # 新密码或确认密码为空 msg="新密码不能为空" elif new_password != confirm: # 新密码与确认密码不一样 msg="两次密码不一致" else: user.set_password(new_password) # 修改密码 user.save() return redirect("/index/") else: msg="旧密码输入错误" return render(request,"change_passwd.html",{"msg":msg})
方式二
# 通过form检测和认证 # 认证forms表单 from django import forms class ChangePasswordForm(forms.Form): old_password = forms.CharField(label=u'原密码', error_messages={'required': '请输入原始密码'}, widget=forms.PasswordInput(attrs={'class': 'form-control', 'style': 'width:500px;'})) new_password1 = forms.CharField(label=u'新密码', error_messages={'required': '请输入新密码'}, widget=forms.PasswordInput(attrs={'class': 'form-control', 'style': 'width:500px;'})) new_password2 = forms.CharField(label=u'新密码', error_messages={'required': '请重复新输入密码'}, widget=forms.PasswordInput(attrs={'class': 'form-control', 'style': 'width:500px;'})) def __init__(self, user, *args, **kwargs): self.user = user super(ChangePasswordForm, self).__init__(*args, **kwargs) def clean_old_password(self): old_password = self.cleaned_data["old_password"] if not self.user.check_password(old_password): raise forms.ValidationError(u'原密码错误') return old_password def clean_new_password2(self): password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if len(password1)<6: raise forms.ValidationError(u'密码必须大于6位') if password1 and password2: if password1 != password2: raise forms.ValidationError(u'两次密码输入不一致') return password2 def save(self, commit=True): self.user.set_password(self.cleaned_data['new_password1']) if commit: self.user.save() return self.user # 改密码html <form class="form-horizontal" role="form" method="post" action={% url "change_password" %}> {% csrf_token %} <div class="box-body"> {% for item in form %} <div class="form-group"> <label class="col-sm-1 control-label">{{item.label}}</label> <div class="col-ms-8" style="margin-left: 10px;"> {{item}} </div> <div class="col-ms-8" style="margin-left: 10px;"> {{item.errors}} </div> </div> {% endfor %} <div class="form-group"> <div class="box-footer" style="margin-left: 10px;width: 530px;"> <button type="submit" class="btn btn-primary pull-left" style="width: 120px">更新密码</button> </div> </div> </div> </form> # 更改密码函数 @login_required() def change_password(request): if request.method == 'POST': form = ChangePasswordForm(user=request.user, data=request.POST) u = form.user if form.is_valid(): form.save() return HttpResponse(str(u)+"密码更新成功!") else: form = ChangePasswordForm(user=request.user) kwargs = { 'form': form, 'request': request, } return render(request, 'accounts/change_password.html', kwargs)
8.引用用户模型get_user_model()
get_user_model().objects可以操作用户表user
#显示所有用户 get_user_model().objects.all() #删除用户 get_user_model().objects.filter(id=用户id).delete() #随机生成10位数密码 get_user_model().objects.make_random_password(length=10, allowed_chars='abcdefghjklmnpqrstuvwxyABCDEFGHJKLMNPQRSTUVWXY3456789')
CP https://www.cnblogs.com/ccorz/p/Django-zi-ding-yi-yong-hu-ren-zheng-xi-tong-zhi-zi.html
https://www.cnblogs.com/renpingsheng/p/7629997.html
https://www.cnblogs.com/ccorz/p/6358074.html