How does python add custom permissions to the user model in django

  • 2020-12-13 19:01:00
  • OfStack

django own authentication system can achieve good such as login, logout, create a user, create super user, change passwords, such as complicated operations, and implement the user group, group permissions, user permissions and other complex structure, use the built-in authentication system can help us do the custom permission system to achieve the purpose of access control.

By default in django,syncdb runs with django.contrib.auth installed, which creates default permissions for each model, such as foo.can_change, foo.can_delete, and foo.can_add. To add custom permissions to the model, add the class Meta: under the model and define permissions in it, as described above

My question is, what if I want to add custom permissions to the user model? Like foo. can_view. I can do this with the following code snippet,


ct = ContentType.objects.get(app_label='auth', model='user')
perm = Permission.objects.create(codename='can_view', name='Can View Users', 
                 content_type=ct)
perm.save()

But I wanted something that would play nicely with syncdb1, such as the Meta class in my custom model. I should have these in class Meta: under UserProfile, because that's how you extend the user model. But is it the right way? Won't you bind it to the UserProfile model?

Here's what you can do:

Per ___ Add to Django applying with init__.py:


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)

The original address: http: / / stackoverflow com/questions / 7724265 / how - to - add - custom - permission - to - the - user - model in -- django


Related articles: