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
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')