[Django]-How to create admin user in django tests.py

6👍

Update 2

Executed the snippet to create the superuser from within a test case (subclass of django.test.TestCase). Everything went fine. Also created and saved an instance of UserProfile with user = self.adminuser. That too worked.

Update

This line is interesting:

File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/contrib/auth/management/__init__.py", line 28, in create_permissions
        defaults={'name': name, 'content_type': ctype})

Looks like execution fails when creating permissions.

Original Answer

Warning: Data truncated for column ‘name’ at row 1

Strange. I tried this from the Django shell and it worked for me. I am using Postgresql 8.3 and Django 1.2.1 on Ubuntu Jaunty. Can you give more details about which version of Django/database are you using?

Also User does not have a name attribute. Can you double check if you are using auth.User?

Do I have to load admin users as fixtures?

You don’t have to. But if you are creating this admin user solely for testing purposes then it would be a good idea to add a Fixture. That is what I do in my projects.

73👍

I’d use the built-in create_superuser and log the user in before making any requests. The following should work:

from django.contrib.auth.models import User
from django.test.client import Client

# store the password to login later
password = 'mypassword' 

my_admin = User.objects.create_superuser('myuser', 'myemail@test.com', password)

c = Client()

# You'll need to log him in before you can send requests through the client
c.login(username=my_admin.username, password=password)

# tests go here

Leave a comment