第十章------Auth 认证系统
内置USER 实现用户管理
python
复制代码
# 举例说明
def setpsView(request):
title = '修改密码'
pageTitle = '修改密码'
password2 = True
if request.method == 'POST':
u = request.POST.get('username', '')
p = request.POST.get('password', '')
p2 = request.POST.get('password2', '')
if User.objects.filter(username=u):
user = authenticate(username=u, password=p)
if user:
# 方式一
user.set_password(p2) 将该用户密码设置为p2
# 方式2
dj_ps = make_password(p2, salt=None, hasher='pbkdf2_sha256')
user.password = dj_ps
user.save()
tips = '密码修改成功'
else:
tips = '原始密码不正确'
else:
tips = '用户不存在'
return render(request, 'user.html', locals())
模型USER的拓展和使用
python
复制代码
# models.py
编写拓展模型
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class MyUser(AbstractUser):
qq = models.CharField('QQ号码', max_length=16)
wechat = models.CharField('微信账号', max_length=100)
mobile = models.CharField('手机号码', max_length=11)
def __str__(self):
return self.username
class Meta:
verbose_name = '用户信息'
verbose_name_plural = '用户信息'
python
复制代码
# settings.py
AUTH_USER_MODEL = 'user1.MyUser'
python
复制代码
# admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext_lazy as _
from .models import MyUser
# Register your models here.
@admin.register(MyUser)
class MyUserAdmin(UserAdmin):
list_display = ('username', 'email', 'mobile', 'qq', 'wechat')
fieldsets = list(UserAdmin.fieldsets)
fieldsets[1] = (_('Personal info'),
{'fields': ('first_name', 'last_name',
'email', 'mobile', 'qq', 'wechat')})
python
复制代码
forms.py
# Django 自带的用户表
from django.contrib.auth.forms import UserCreationForm
from .models import MyUser
class MyUserCreationForm(UserCreationForm):
class Meta:
model = MyUser
fields = UserCreationForm.Meta.fields
fields += ('email', 'mobile', 'wechat', 'qq')
自定义用户权限
python
复制代码
# models.py 在模型处的permissions 以元组的方式添加权限,清空原有的数据表,重新执行数据迁移
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class MyUser(AbstractUser):
qq = models.CharField('QQ号码', max_length=16)
wechat = models.CharField('微信账号', max_length=100)
mobile = models.CharField('手机号码', max_length=11)
def __str__(self):
return self.username
class Meta:
verbose_name = '用户信息'
verbose_name_plural = '用户信息'
# 自定义权限
permissions = (
('vip_myuser', 'Can vip user'),
)
python
复制代码
views.py
def registerView_1(request):
userLogin = False
if request.method == 'POST':
user = MyUserCreationForm(request.POST)
if user.is_valid():
user.save()
tips = '注册成功'
# 添加权限
# 由表单对象user 的 instance获取对应的模型对象
u = user.instance
p = Permission.objects.filter(codename='vip_myuser')[0]
print('pp', p)
u.user_permissions.add(p)
return redirect(reverse('user1:login_1'))
else:
tips = '注册失败'
user = MyUserCreationForm()
return render(request, 'user2.html', locals())
@login_required(login_url='/login_1.html')
@permission_required(perm='user1.vip_myuser', login_url='/login_1.html')
def infoView(request, user_id):
user = MyUser.objects.filter(id=user_id)[0]
# p = Permission.objects.filter(codename='vip_myuser')[0]
if user.has_perm('user1.vip_myuser'):
print('has')
else:
print('not has')
return render(request, 'info.html', locals())
python
复制代码
html
<!doctype html>
<html>
<head>
{% load static %}
<title>用户信息</title>
<link rel="stylesheet" href="{% static 'css/common.css' %}">
<link rel="stylesheet" href="{% static 'css/home.css' %}">
</head>
<body class="member">
<div class="mod_profile js_user_data">
<div class="section_inner">
{#模板上下文user是User或AnoymousUser对象#}
{#user由模型MyUser实例化#}
{% if user.is_authenticated %}
<div class="profile__cover_link">
<img src="{% static 'image/user.jpg' %}" class="profile__cover">
</div>
<h1 class="profile__tit">
<span class="profile__name">{{ user.username }}</span>
</h1>
{#模板上下文perms是模型Permission实例化对象#}
{% if perms.user1.vip_myuser %} # user1 应用名
<div class="profile__name">VIP会员111</div>
{% endif %}
<a href="{% url 'user1:logout_1' %}" style="color:white;">退出登录</a>
{% endif %}
</div>
</div>
</body>
</html>
PS:TEMPLATES 定义了处理器集合 context_processors,运行到处理器auth时,程序会生成变量user 和 perms , 并将该变量传入模板上下文TemplateContext中,所以才可以在模板中使用该变量。
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR, 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]