Python django - 在使用 get_or_create 自动创建用户时设置用户权限
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20361235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
django - set user permissions when user is automatically created using get_or_create
提问by billrichards
Django 1.5, python 2.6
Django 1.5,蟒蛇 2.6
The model automatically creates a user under certain conditions:
模型在特定条件下自动创建用户:
User.objects.get_or_create(username=new_user_name, is_staff=True)
u = User.objects.get(username=new_user_name)
u.set_password('temporary')
In addition to setting the username, password, and is_staff status, I would like to set the user's permissions - something like:
除了设置用户名、密码和 is_staff 状态之外,我还想设置用户的权限——比如:
u.user_permissions('Can view poll')
or
或者
u.set_permissions('Can change poll')
Is this possible? Thank you!
这可能吗?谢谢!
采纳答案by alko
Use addand removemethods:
用途add及remove方法:
from django.contrib.auth.models import Permission
permission = Permission.objects.get(name='Can view poll')
u.user_permissions.add(permission)
回答by juanmhidalgo
Andrew M. Farrell's answer is correct. I only add the use of get_user_model()and a full example.
Andrew M. Farrell 的回答是正确的。我只添加了get_user_model()的使用和一个完整的例子。
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
u = get_user_model().get(username=new_user_name)
To get the permission you can use
要获得您可以使用的许可
permission = Permission.objects.get(name='Can view poll')
or
或者
permission = Permission.objects.get(codename='can_view_poll')
then add it to the user permissions set
然后将其添加到用户权限集
u.user_permissions.add(permission)

