How can I use Django permissions without defining a content type or model?

后端 未结 6 1102
小鲜肉
小鲜肉 2021-01-29 18:56

I\'d like to use a permissions based system to restrict certain actions within my Django application. These actions need not be related to a particular model (e.g. access to sec

6条回答
  •  花落未央
    2021-01-29 19:02

    Following Gonzalo's advice, I used a proxy model and a custom manager to handle my "modelless" permissions with a dummy content type.

    from django.db import models
    from django.contrib.auth.models import Permission
    from django.contrib.contenttypes.models import ContentType
    
    
    class GlobalPermissionManager(models.Manager):
        def get_query_set(self):
            return super(GlobalPermissionManager, self).\
                get_query_set().filter(content_type__name='global_permission')
    
    
    class GlobalPermission(Permission):
        """A global permission, not attached to a model"""
    
        objects = GlobalPermissionManager()
    
        class Meta:
            proxy = True
    
        def save(self, *args, **kwargs):
            ct, created = ContentType.objects.get_or_create(
                name="global_permission", app_label=self._meta.app_label
            )
            self.content_type = ct
            super(GlobalPermission, self).save(*args, **kwargs)
    

提交回复
热议问题