djangopermissionscontenttype

Adding permission to User model in Django


I'm trying to add a permission 'view_user' to User model in Django. I added a proxy model:

from django.contrib.auth.models import User, Permission
from django.db import models


class RodanUser(User):
    class Meta:
        proxy = True
        permissions = (
            ('view_user', 'View User'),
        )

but I get the error :

ContentType matching query does not exist.

which in my opinion is because the app_label of Django's User is auth but app_label of RodanUser is rodan So I changed the model and added app_label:

from django.contrib.auth.models import User, Permission


class RodanUser(User):
    class Meta:
        proxy = True
        permissions = (
            ('view_rodanuser', 'View User'),
        )
        app_label = 'auth'

now I get the error:

MixedContentTypeError at /users/

Strangest thing is that I actually was able to get this to work by first adding a none-proxy model:

from django.contrib.auth.models import User, Permission
from django.db import models


class RodanUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    class Meta:
        permissions = (
            ('view_rodanuser', 'View Rodan User'),
        )

and then changing it into the proxy model from above(without the app_label) because the none-proxy model will add the permission in DB where the content_type_id points to RodanUser instead of User.

I found this which explains why I cannot use proxy with permission. Any other suggestions?


Solution

  • I solved this problem by using another approach: in __init__.py of my project I added:

    @receiver(post_migrate)
    def add_user_view_permissions(sender, **kwargs):
        content_type = ContentType.objects.get(app_label='auth', model='user')
        Permission.objects.get_or_create(codename='view_user', name='View User', content_type=content_type)
    

    Which adds the permission after migration.