note: 應該是這樣的結構,而且commands名字是固定的。 執行: python manage.py initgrouphtml
initgroup.pypython
# -*- coding: utf-8 -*- from django.core.management import BaseCommand from django.contrib.auth.models import Group, Permission, ContentType from apps.news.models import News, NewsCategory, Comment from apps.cms.models import Banners from apps.course.models import Course, CourseOrder, Category class Command(BaseCommand): def handle(self, *args, **options): # 編輯組/財務組/管理員組/超級管理員 # python manage.py initgroup # 編輯人員權限:編輯文章/輪播圖/付費資訊/課程 # 建立編輯組 # model對應的app名字 !!!get_for_model not is get_for_models edit_content_types = [ ContentType.objects.get_for_model(News), ContentType.objects.get_for_model(NewsCategory), ContentType.objects.get_for_model(Banners), ContentType.objects.get_for_model(Comment), ContentType.objects.get_for_model(Course), ContentType.objects.get_for_model(Category), ] # 添加權限 # 查找出這些models須要的權限 edit_permissions = Permission.objects.filter(content_type__in=edit_content_types) # 建立權限組的名字 editGroup = Group.objects.create(name='編輯') # 添加權限 editGroup.permissions.set(edit_permissions) # 2.建立財務組 finance_content_types = [ ContentType.objects.get_for_models(CourseOrder) ] finance_permissions = Permission.objects.filter(content_type__in=finance_content_types) finance_group = Group.objects.create(name='財務組') finance_group.permissions.set(finance_permissions) # 3.建立管理員,擁有財務和編輯權限 admin_permissions = edit_permissions.union(finance_permissions) admin_group = Group.objects.create(name='管理員') admin_group.permissions.set(admin_permissions) self.stdout.write(self.style.SUCCESS("初始化分組成功"))
權限分組完成,權限驗證場景: https://www.cnblogs.com/tangpg/p/9431620.htmldjango