django认证 auth
Posted lnrick
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django认证 auth相关的知识,希望对你有一定的参考价值。
auth的引入:
form django.contrib import auth
django自带了一个orm系统,可以注册数据库后
进行python manage.py createsuperuse 超级用户
python manage.py createuser 普通
auth认证:
from django.contrib import auth
注册用户,同上
认证用户
user =auth. authenticate(request, username=username, password=pwd) 获取到对象和数据库中的匹配
获取到user对象,没有返回None
保存登录状态:
写到session中
auth.login(request,user) 会自动生成
注销:
删除用户的session
auth.logout(request)
注意在执行命令前要先在setting中写入,自定义必须加上:
LOGIN_URL = ‘/login/‘ # 这里配置成你项目登录页面的路由
主页加装饰器,登录后方能查看,
from django.contrib.auth.decorators import login_required
给函数加上 login_required
print(request.user.is_authenticated()) #查看登录的状态flase 和true
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
@login_required
def my_view(request):
from django.contrib.auth.models import User,AbstractUser# 不加字段的时候用系统的
如果要加入新的字段,那么我们要将,扩展系统的表:
修改数据库:
from django.contrib.auth.models import AbstractUser #引入django的class
class UserInfo(AbstractUser): #必须要继承
phone = models.CharField(max_length=11,)
1,from app01.models import UserInfo #加了字段,使用自己定义的
2,在setting中加入:
AUTH_USER_MODEL = "app01.UserInfo" #这里的是自己定义的
create_user()
创建用户的方法:
from django.contrib.auth.models import User
user = User.objects.create_user(username=‘用户名‘,password=‘密码‘,email=‘邮箱‘,...)
user = User.objects.create_user(username=‘用户名‘,password=‘密码‘,email=‘邮箱‘,...)
create_superuser()
创建超级用户:
from django.contrib.auth.models import User
user = User.objects.create_superuser(username=‘用户名‘,password=‘密码‘,email=‘邮箱‘,...)
user = User.objects.create_superuser(username=‘用户名‘,password=‘密码‘,email=‘邮箱‘,...)
注意将邮箱加上,超级必须要加,设置成空即可
check_password(password)
密码是否正确,需要提供当前请求用户的密码
密码正确返回True 错误为False
ok = user.check_password(‘密码‘)
set_password(password):
修改密码的方法,接收要设置新的密码作为参数
设置完一定要调用用户的save方法
用法:"
user.set_password(password=‘‘)
user.save()
user.save()
一个修改密码功能的简单示例:
@login_required
def set_password(request):
user = request.user
err_msg = ‘‘
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:
err_msg = ‘新密码不能为空‘
elif new_password != repeat_password:
err_msg = ‘两次密码不一致‘
else:
user.set_password(new_password)
user.save()
return redirect("/login/")
else:
err_msg = ‘原密码输入错误‘
content = {
‘err_msg‘: err_msg,
}
return render(request, ‘set_password.html‘, content)
def set_password(request):
user = request.user
err_msg = ‘‘
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:
err_msg = ‘新密码不能为空‘
elif new_password != repeat_password:
err_msg = ‘两次密码不一致‘
else:
user.set_password(new_password)
user.save()
return redirect("/login/")
else:
err_msg = ‘原密码输入错误‘
content = {
‘err_msg‘: err_msg,
}
return render(request, ‘set_password.html‘, content)
user属性的问题:
user 对象属性:username,password
is_staff 用户是否有网站的管理权限
is_active:是否允许用户登录,设置为False,可以在不删除用户的前提下禁止用户登录
实例:
uls:
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^login/‘, views.login),
url(r‘^index/‘, views.index),
url(r‘^logout/‘, views.logout),
url(r‘^reg/‘, views.reg),
]
views:
from django.shortcuts import render, HttpResponse, redirect
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from app01.forms import RegForm
from django.contrib.auth.models import User,AbstractUser
def login(request):
error_msg = ‘‘
if request.method == ‘POST‘:
username = request.POST.get(‘username‘)
pwd = request.POST.get(‘pwd‘)
# 对提交的数据进行认证
obj = auth.authenticate(request, username=username, password=pwd)
if obj:
# 登录成功
auth.login(request, obj)
return redirect(‘/index‘)
else:
error_msg = ‘用户名或密码错误‘
# 返回一个页面让登录
return render(request, ‘login.html‘, {‘error_msg‘: error_msg})
@login_required
def index(request):
print(request.user.is_authenticated())
return render(request, ‘index.html‘)
def logout(request):
auth.logout(request)
return redirect(‘/login/‘)
def reg(request):
form_obj = RegForm()
if request.method == ‘POST‘:
form_obj = RegForm(request.POST)
if form_obj.is_valid():
form_obj.cleaned_data.pop(‘re_password‘)
# 创建普通用户
User.objects.create_user(**form_obj.cleaned_data)
# User.objects.create_superuser(**form_obj.cleaned_data,email=‘‘)
# return redirect(‘/login/‘)
obj = auth.authenticate(request, **form_obj.cleaned_data)
auth.login(request, obj)
return redirect(‘/index/‘)
return render(request, ‘reg.html‘, {‘form_obj‘: form_obj})
login.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body>
<form action="" method="post" autocomplete="off" novalidate>
{% csrf_token %}
<p>
用户名:
<input type="text" name="username">
</p>
<p>
密码:
<input type="password" name="pwd">
</p>
<p>
<button>登录</button>
</p>
<p>
<span>{{ error_msg }}</span>
</p>
</form>
</body>
</html>
setting:
LOGIN_URL = ‘/login/‘ # 这里配置成你项目登录页面的路由
AUTH_USER_MODEL = "app01.UserInfo"
models:
from django.db import models
from django.contrib.auth.models import AbstractUser
class UserInfo(AbstractUser):
phone = models.CharField(max_length=11, )
forms:
from django import forms
class RegForm(forms.Form):
username = forms.CharField(
label=‘用户名‘
)
password = forms.CharField(
label=‘密码‘,
widget=forms.widgets.PasswordInput()
)
re_password = forms.CharField(
label=‘确认密码‘,
widget=forms.widgets.PasswordInput()
)
reg.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form_obj.as_p }}
<button>注册</button>
</form>
</body>
</html>