billrichards billrichards - 1 year ago 39
Python Question

django - set user permissions when user is automatically created

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=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:

u.user_permissions('Can view poll')


or

u.set_permissions('Can change poll')


Is this possible? Thank you!

Answer Source

Use add and remove methods:

 permission = Permission.objects.get(name='Can view poll')
 u.user_permissions.add(permission)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download