覆盖 Django 权限并修改 auth_permission

Overwrite Django permission and modify auth_permission

我想在视图中动态创建权限而不是在模型中创建默认权限

我创建了一个名为 CreatorView

的主要 class
from django.views.generic import View
from django.forms.models import modelform_factory
class CreatorView(View):
    model = None
    fields = None
    exclude = None
    form = None
    page_title = ''
    
    def create_form(self):
        default =dict()
        if self.fields == None:
            if self.exclude == None:
                default['fields'] = self.fields = self.model._meta.fileds
            else:
                default['exclude'] = self.exclude
        else:
            if self.exclude:
                raise Exception('error')
            default['fields'] = self.fields
             

        return modelform_factory(self.model,**default)
    def get(self,request,*args,**kwargs):
        return render('','base.html')
    def post(self,request,*args,**kwargs):
      ... and so on

主要网址是:

urlpatterns = [
path('%s/%s' % (cls.model._meta.app_label, cls.__name__.lower()), cls.as_view(),
     name='%s/%s' % (cls.model._meta.app_label, cls.__name__.lower())) for cls
in CreatorView.__subclasses__()]

如果我从 CreatorView 继承,那么我的 class 应该创建一个页面 例如:

class Login(CreatorView):
    model = Users
    """ my overwrite methods and actions """

class Configurations(CreatorView):
    model = Configure
    """ my overwrite methods and actions """

class Teachers(CreatorView):
    model = Teachers
    """ my overwrite methods and actions """

class Students(CreatorView):
    model = Students
    """ my overwrite methods and actions """

and so on

此代码将为我创建四个页面 我想创建 table semi to django content_type 模型如下:

id app_label page
1 myapp login
2 myapp configurations
3 myapp teachers
4 myapp students

我可以修改 Django 中的 auth_permission table 来使 content_type 外键来自我的content_type? 如果我可以如何防止插入默认权限并使我的插入成为默认权限?

您可以根据文档手动创建权限here

from myapp.models import BlogPost
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get_for_model(BlogPost)
permission = Permission.objects.create(
    codename='can_publish',
    name='Can Publish Posts',
    content_type=content_type,
)

一个增强的权限库,使基于逻辑的权限系统能够处理 Django 中的复杂权限。 here