django用户和权限管理
1、定义User模型
from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin from django.contrib.auth import get_user_model class UserManager(BaseUserManager): def _create_user(self , telephone, username, password, **kwargs): if not telephone: raise ValueError("必须要传递手机号码!") if not password: raise ValueError("必须要传递密码") user = self.model( telephone = telephone, username= username , **kwargs) user.set_password( password ) user.save() return user def create_user(self, telephone, username, password, **kwargs): kwargs['is_superuser'] = False return self._create_user( telephone = telephone, username=username, password = password, **kwargs ) def create_superuser(self, telephone, username, password, **kwargs): kwargs['is_superuser'] = True return self._create_user( telephone = telephone, username=username, password = password, **kwargs ) class User(AbstractBaseUser, PermissionsMixin): telephone = models.CharField(max_length=11, unique=True) email = models.CharField(max_length=100, unique=True) username = models.CharField(max_length=100) is_active = models.BooleanField(default=True) USERNAME_FIELD = "telephone" #USERNAME_FIELD作用,是执行authenticate验证, username参数传入后,实际校验的是telephone字段 REQUIRED_FIELDS = [] objects = UserManager() def get_full_name(self): return self.username def get_short_name(self): return self.username class Article(models.Model): title = models.CharField(max_length=100) content = models.TextField() # author = models.ForeignKey( User, on_delete= models.CASCADE ) #get_user_model()会自动获取settings.py里面 AUTH_USER_MODEL,这样不管你定义的那个User,都可以自动获取,更安全 author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) class Meta: permissions =[ ('view_article', '看文章的权限!'), ]
2、视图里面调用
from django.shortcuts import render, HttpResponse, reverse,redirect from django.db import connection from app01.models import User, Article from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import Permission, ContentType from app01.forms import LoginForm def test(request): #创建用户 User.objects.create_user( telephone="15555655555", password="555555", username="zhiliao5" ) #用认证 # user = authenticate(request, username="15555655555", password="555555") # if user: # print(user.username) # print("验证成功!") # else: # print("验证失败!") return HttpResponse("继承AbstractUser扩展用户") def my_login(request): if request.method == "GET": return render(request, "login.html") else: print("提交的数据为:"); print(request.POST) form = LoginForm(request.POST) if form.is_valid(): telephone = form.cleaned_data.get("telephone") password = form.cleaned_data.get("password") remember = form.cleaned_data.get("remember") user = authenticate(request, username =telephone, password=password) if user and user.is_active: login(request, user) if remember: request.session.set_expiry(None) else: request.session.set_expiry(0) return HttpResponse("登录成功!") else: return HttpResponse("手机号码或者密码错误!") else: print(form.errors) return redirect( reverse("login") ) def my_logout(request): logout(request) return HttpResponse("成功退出") @login_required(login_url="/login/") def profile(request): return HttpResponse("这是个人中心,只有登录了以后才能查看到!") #添加权限 def add_permission(request): content_type = ContentType.objects.get_for_model( Article) permission = Permission.objects.create( codename="black_article", name="拉黑文章", content_type=content_type ) return HttpResponse("权限创建成功") #用户与权限 def operate_permission(request): user = User.objects.first() content_type = ContentType.objects.get_for_model(Article) permissions = Permission.objects.filter( content_type = content_type ) for permission in permissions: print(permission) return HttpResponse("操作权限的视图!")
3、定义路由
from django.contrib import admin from django.urls import path from app01 import views as app01_views urlpatterns = [ path('admin/', admin.site.urls), path("test/", app01_views.test), path("login/", app01_views.my_login, name = "login"), path("logout/", app01_views.my_logout, name = "logout"), path("profile/", app01_views.profile, name="profile"), path("add_permission/", app01_views.add_permission, name="add_permission" ), path("oper_permission/", app01_views.operate_permission, name="oper_permission" ), ]
4、访问URL:http://127.0.0.1:8080/oper_permission/, 打印结果如下:
app01 | article | Can add article app01 | article | 拉黑文章 app01 | article | Can change article app01 | article | Can delete article app01 | article | 看文章的权限!
5、视图里,给用户添加权限
#用户与权限 def operate_permission(request): user = User.objects.first() content_type = ContentType.objects.get_for_model(Article) permissions = Permission.objects.filter( content_type = content_type ) for permission in permissions: print(permission) user.user_permissions.set(permissions) return HttpResponse("操作权限的视图!")
app01_user_user_permissions表里面,用户1 多了19-26的权限
6、set、add添加权限, clear、remove删除权限, has_perm判断是否有权限
#用户与权限 def operate_permission(request): user = User.objects.first() content_type = ContentType.objects.get_for_model(Article) permissions = Permission.objects.filter( content_type = content_type ) for permission in permissions: print(permission) #set([])添加权限 user.user_permissions.set(permissions) #清空权限 # user.user_permissions.clear() #add(*[])添加权限 # user.user_permissions.add(* permissions) #remove(*[])删除权限 # user.user_permissions.remove(*permissions) if user.has_perm('app01.view_article'): print("这个用户拥有view_article权限") else: print("这个用户没有view_article权限") print( user.get_all_permissions()) return HttpResponse("操作权限的视图!")
访问http://127.0.0.1:8080/oper_permission/后打印结果如下:
这个用户拥有view_article权限 {'app01.change_article', 'app01.delete_article', 'app01.black_article', 'app01.add_article', 'app01.view_article'}