3

我需要在 django 应用程序中测试我的一个视图,该应用程序需要admin user具有某些权限

如何创建 atest user 并设置它的一些权限,例如staff statusor group permissions

我可以使用工厂这样做吗?

4

1 回答 1

2

要创建裸超级用户,请执行python manage.py createsuperuser https://docs.djangoproject.com/en/dev/ref/django-admin/#createsuperuser

要最初设置权限,请创建自定义 django-admin 命令 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

进而:

python manage.py create_test_user admin1 qwe123
于 2013-03-28T09:17:36.013 回答