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

后端 未结 6 1089
小鲜肉
小鲜肉 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:21

    Fix for Chewie's answer in Django 1.8, which as been requested in a few comments.

    It says in the release notes:

    The name field of django.contrib.contenttypes.models.ContentType has been removed by a migration and replaced by a property. That means it’s not possible to query or filter a ContentType by this field any longer.

    So it's the 'name' in reference in ContentType that the uses not in GlobalPermissions.

    When I fix it I get the following:

    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_queryset(self):
            return super(GlobalPermissionManager, self).\
                get_queryset().filter(content_type__model='global_permission')
    
    
    class GlobalPermission(Permission):
        """A global permission, not attached to a model"""
    
        objects = GlobalPermissionManager()
    
        class Meta:
            proxy = True
            verbose_name = "global_permission"
    
        def save(self, *args, **kwargs):
            ct, created = ContentType.objects.get_or_create(
                model=self._meta.verbose_name, app_label=self._meta.app_label,
            )
            self.content_type = ct
            super(GlobalPermission, self).save(*args)
    

    The GlobalPermissionManager class is unchanged but included for completeness.

提交回复
热议问题