我需要在django应用中测试我的一个视图,这需要admin user
具有某些权限
如何创建test user
并设置一些权限,例如staff status
或group permissions
?
我可以使用工厂吗。
答案 0 :(得分:1)
要创建裸超级用户,请执行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