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

后端 未结 4 1036
我寻月下人不归
我寻月下人不归 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:25

    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_migrate
    from django.contrib.contenttypes.models import ContentType
    from django.contrib.auth import models as auth_models
    from django.contrib.auth.models import Permission
    from django.conf import settings
    from 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)
    

提交回复
热议问题