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

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

    You can use the proxy model for this with a dummy content type.

    from django.contrib.auth.models import Permission
    from django.contrib.contenttypes.models import ContentType
    
    
    class CustomPermission(Permission):
    
        class Meta:
            proxy = True
    
        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(CustomPermission, self).save(*args)
    

    Now you can create the permission with just name and codename of the permission from the CustomPermission model.

     CustomPermission.objects.create(name='Can do something', codename='can_do_something')
    

    And you can query and display only the custom permissions in your templates like this.

     CustomPermission.objects.filter(content_type__model='custom permission')
    

提交回复
热议问题