如何在django中为用户模型添加自定义权限? [英] How to add custom permission to the User model in django?
问题描述
我的问题是我该怎么办如果我要添加一个自定义的权限给用户模型?像foo.can_view。我可以使用以下代码片段来执行此操作:
ct = ContentType.objects.get(app_label ='auth',model ='用户')
perm = Permission.objects.create(codename ='can_view',name ='可以查看用户',
content_type = ct)
perm.save()
但是我想要一些可以很好地使用syncdb的东西,比如我的自定义模型下的Meta类。我应该在类Meta中有这些:在UserProfile下,因为这是扩展用户模型的方式。但是是否正确的方式呢?不会把它绑定到UserProfile模型吗?解决方案你可以这样做:
您的Django应用程序的 __ init __。py
中的
添加:
从django.db.models.signals导入post_syncdb
从django.contrib.contenttypes.models导入ContentType
从django.contrib.auth导入模型作为auth_models
从django。 contrib.auth.models import Permission
#自定义用户相关权限
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)
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. To add custom permissions to models one can add class Meta: under the model and define permissions there, as explained here https://docs.djangoproject.com/en/dev/topics/auth/#custom-permissions
My question is that what should I do if I want to add a custom permission to the User model? like foo.can_view. I could do this with the following 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 want something that plays nicely with syncdb, for example the class Meta under my custom models. Should I just have these in class Meta: under UserProfile since that is the way to extend the user model. but is that the RIGHT way to do it? Wouldn't that tie it to UserProfile model?
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)
这篇关于如何在django中为用户模型添加自定义权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!