django - set user permissions when user is automatically created using get_or_create

后端 未结 2 1452
太阳男子
太阳男子 2020-12-23 13:21

Django 1.5, python 2.6

The model automatically creates a user under certain conditions:

User.objects.get_or_create(username=new_user_name, is_staff=T         


        
相关标签:
2条回答
  • 2020-12-23 13:35

    Andrew M. Farrell's answer is correct. I only add the use of get_user_model() and a full example.

    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)
    
    0 讨论(0)
  • 2020-12-23 13:54

    Use add and remove methods:

     from django.contrib.auth.models import Permission
     permission = Permission.objects.get(name='Can view poll')
     u.user_permissions.add(permission)
    
    0 讨论(0)
提交回复
热议问题