第十章——Auth 认证系统
内置USER 实现用户管理
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
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的拓展和使用
编写拓展模型
from django.db import models
from django.contrib.auth.models import AbstractUser
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 = '用户信息'
AUTH_USER_MODEL = 'user1.MyUser'
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import gettext_lazy as _
from .models import MyUser
@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')})
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1bb3188a8998d884f1e46e0bd586bab7.png)
forms.py
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')
自定义用户权限
from django.db import models
from django.contrib.auth.models import AbstractUser
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'),
)
views.py
def registerView_1(request):
userLogin = False
if request.method == 'POST':
user = MyUserCreationForm(request.POST)
if user.is_valid():
user.save()
tips = '注册成功'
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]
if user.has_perm('user1.vip_myuser'):
print('has')
else:
print('not has')
return render(request, 'info.html', locals())
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">
{
{
{% 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>
{
{% if perms.user1.vip_myuser %}
<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',
],
},
},
]