How to add custom permission to the User model in django? How to add custom permission to the User model in django? python python

How to add custom permission to the User model in django?


You could do something like this:

in the __init__.py of your Django app add:

from django.db.models.signals import post_syncdbfrom django.contrib.contenttypes.models import ContentTypefrom django.contrib.auth import models as auth_modelsfrom django.contrib.auth.models import Permission# custom user related permissionsdef add_user_permissions(sender, **kwargs):    ct = ContentType.objects.get(app_label='auth', model='user')    perm, created = Permission.objects.get_or_create(codename='can_view', name='Can View Users', content_type=ct)post_syncdb.connect(add_user_permissions, sender=auth_models)


I don't think there is a "right" answer here, but i used the exact same code as you except i changed Permission.objects.create to Permission.objects.get_or_create and that worked find to sync with syncdb


An updated answer for Django 1.8. The signal pre_migrate is used instead of pre_syncdb, since syncdb is deprecated and the docs recommend using pre_migrate instead of post_migrate if the signal will alter the database. Also, @receiver is used to connect add_user_permissions to the signal.

from django.db.models.signals import pre_migratefrom django.contrib.contenttypes.models import ContentTypefrom django.contrib.auth import models as auth_modelsfrom django.contrib.auth.models import Permissionfrom django.conf import settingsfrom django.dispatch import receiver# custom user related permissions@receiver(pre_migrate, sender=auth_models)def add_user_permissions(sender, **kwargs):    content_type = ContentType.objects.get_for_model(settings.AUTH_USER_MODEL)    Permission.objects.get_or_create(codename='view_user', name='View user', content_type=content_type)