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

后端 未结 4 1028
我寻月下人不归
我寻月下人不归 2021-02-12 15:53

in django by default when syncdb is run with django.contrib.auth installed, it creates default permissions on each model... like foo.can_change , foo.can_delete and foo.can_add.

4条回答
  •  难免孤独
    2021-02-12 16:32

    You could do something like this:

    in the __init__.py of your Django app add:

    from django.db.models.signals import post_syncdb
    from django.contrib.contenttypes.models import ContentType
    from django.contrib.auth import models as auth_models
    from django.contrib.auth.models import Permission
    
    # custom user related permissions
    def 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)
    

提交回复
热议问题