3

I need to test one of my views in a django app which requires an admin user to have certain permissions

How do I create a test user and set some of its permissions like staff status or group permissions ?

Can I use factories to do so.

Deepankar Bajpeyi
  • 5,661
  • 11
  • 44
  • 64
  • isn't similar question? http://stackoverflow.com/questions/3495114/how-to-create-admin-user-in-django-tests-py – cadmi Mar 28 '13 at 06:04
  • yes but I dont want to user the User model itself with its create_superuser method. All my tests have used factories – Deepankar Bajpeyi Mar 28 '13 at 06:09

1 Answers1

2

To create bare superuser do python manage.py createsuperuser https://docs.djangoproject.com/en/dev/ref/django-admin/#createsuperuser

To initially set permissions create custom django-admin command app_name/commands/management/create_test_user.py

from django.contrib.auth.models import User, Group, Permission
from django.core.management.base import BaseCommand

class Command( BaseCommand ):

    help = "Creates test user"
    args = '<username> <password>'

    def handle( self, username, password ):

        user, created = User.objects.get_or_create( username=username ) 
        user.set_password( password )
        user.is_staff = True
        user.save()

        custom_perm = Permission.objects.get( codename='custom_perm_name' )
        user.user_permissions.add( custom_perm )

        if created:
            print "%s created" % username
        else:
            print "%s updated" % username

And then:

python manage.py create_test_user admin1 qwe123
Pawel Furmaniak
  • 4,648
  • 3
  • 29
  • 33