如何在 djangotests.py 中创建管理员用户

发布于 2024-09-14 05:33:54 字数 5293 浏览 8 评论 0原文

我正在尝试创建一个管理员用户作为我的tests.py 的一部分来检查权限。

更新: test.py 是 TestCase 子类的标准格式,下面的代码在 setUp() 函数中调用。

我可以创建普通用户,但不能创建管理员用户。如果我尝试这个:

    self.adminuser = User.objects.create_user('admin', '[email protected]', 'pass')
    self.adminuser.save()
    self.adminuser.is_staff = True
    self.adminuser.save()

或者 self.adminuser = User.objects.create_superuser('admin', '[电子邮件受保护]< /a>', '通过') self.adminuser.save()

我得到:

Warning: Data truncated for column 'name' at row 1

如果我删除 is_staff 行,一切都很好(除了我无法进行测试!)

我是否必须将管理员用户加载为固定装置?

UserProfile 定义如下:

class UserProfile(models.Model):

    user = models.ForeignKey(User, unique=True)
    organisation = models.ForeignKey(Organisation, null=True, blank=True)
    telephone = models.CharField(max_length=20, null=True, blank=True)

完整的错误回溯是:

    Traceback (most recent call last):
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 242, in __call__
        self._pre_setup()
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 217, in _pre_setup
        self._fixture_setup()
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 440, in _fixture_setup
        return super(TestCase, self)._fixture_setup()
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 222, in _fixture_setup
        call_command('flush', verbosity=0, interactive=False)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/__init__.py", line 166, in call_command
        return klass.execute(*args, **defaults)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/base.py", line 222, in execute
        output = self.handle(*args, **options)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/base.py", line 351, in handle
        return self.handle_noargs(**options)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/commands/flush.py", line 61, in handle_noargs
        emit_post_sync_signal(models.get_models(), verbosity, interactive)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/sql.py", line 205, in emit_post_sync_signal
        interactive=interactive)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/dispatch/dispatcher.py", line 166, in send
        response = receiver(signal=self, sender=sender, **named)
      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})
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/manager.py", line 123, in get_or_create
        return self.get_query_set().get_or_create(**kwargs)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/query.py", line 335, in get_or_create
        obj.save(force_insert=True)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/base.py", line 410, in save
        self.save_base(force_insert=force_insert, force_update=force_update)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/base.py", line 495, in save_base
        result = manager._insert(values, return_id=update_pk)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/manager.py", line 177, in _insert
        return insert_query(self.model, values, **kwargs)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/query.py", line 1087, in insert_query
        return query.execute_sql(return_id)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/sql/subqueries.py", line 320, in execute_sql
        cursor = super(InsertQuery, self).execute_sql(None)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/sql/query.py", line 2369, in execute_sql
        cursor.execute(sql, params)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/backends/mysql/base.py", line 84, in execute
        return self.cursor.execute(query, args)
      File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py", line 175, in execute
      File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py", line 89, in _warning_check
      File "/usr/lib64/python2.4/warnings.py", line 61, in warn
        warn_explicit(message, category, filename, lineno, module, registry)
      File "/usr/lib64/python2.4/warnings.py", line 96, in warn_explicit
        raise message
    Warning: Data truncated for column 'name' at row 1

答案似乎是您无法在 setUp 中创建管理员用户,但您可以在任何其他函数中创建管理员用户,因此如果您想要在中创建管理员用户测试,使用夹具!

I'm trying to create an admin user as part of my tests.py to check on persmissions.

UPDATE:
The tests.py is standard format that subclasses TestCase and the code below is called in the setUp() function.

I can create a normal user but not an admin user. If I try this:

    self.adminuser = User.objects.create_user('admin', '[email protected]', 'pass')
    self.adminuser.save()
    self.adminuser.is_staff = True
    self.adminuser.save()

OR
self.adminuser = User.objects.create_superuser('admin', '[email protected]', 'pass')
self.adminuser.save()

I get:

Warning: Data truncated for column 'name' at row 1

If I remove the is_staff line all is well (except I can't do my test!)

Do I have to load admin users as fixtures?

UserProfile is defined as follows:

class UserProfile(models.Model):

    user = models.ForeignKey(User, unique=True)
    organisation = models.ForeignKey(Organisation, null=True, blank=True)
    telephone = models.CharField(max_length=20, null=True, blank=True)

and full error traceback is:

    Traceback (most recent call last):
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 242, in __call__
        self._pre_setup()
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 217, in _pre_setup
        self._fixture_setup()
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 440, in _fixture_setup
        return super(TestCase, self)._fixture_setup()
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/test/testcases.py", line 222, in _fixture_setup
        call_command('flush', verbosity=0, interactive=False)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/__init__.py", line 166, in call_command
        return klass.execute(*args, **defaults)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/base.py", line 222, in execute
        output = self.handle(*args, **options)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/base.py", line 351, in handle
        return self.handle_noargs(**options)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/commands/flush.py", line 61, in handle_noargs
        emit_post_sync_signal(models.get_models(), verbosity, interactive)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/core/management/sql.py", line 205, in emit_post_sync_signal
        interactive=interactive)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/dispatch/dispatcher.py", line 166, in send
        response = receiver(signal=self, sender=sender, **named)
      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})
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/manager.py", line 123, in get_or_create
        return self.get_query_set().get_or_create(**kwargs)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/query.py", line 335, in get_or_create
        obj.save(force_insert=True)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/base.py", line 410, in save
        self.save_base(force_insert=force_insert, force_update=force_update)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/base.py", line 495, in save_base
        result = manager._insert(values, return_id=update_pk)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/manager.py", line 177, in _insert
        return insert_query(self.model, values, **kwargs)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/query.py", line 1087, in insert_query
        return query.execute_sql(return_id)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/sql/subqueries.py", line 320, in execute_sql
        cursor = super(InsertQuery, self).execute_sql(None)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/models/sql/query.py", line 2369, in execute_sql
        cursor.execute(sql, params)
      File "/usr/lib/python2.4/site-packages/Django-1.1.1-py2.4.egg/django/db/backends/mysql/base.py", line 84, in execute
        return self.cursor.execute(query, args)
      File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py", line 175, in execute
      File "build/bdist.linux-x86_64/egg/MySQLdb/cursors.py", line 89, in _warning_check
      File "/usr/lib64/python2.4/warnings.py", line 61, in warn
        warn_explicit(message, category, filename, lineno, module, registry)
      File "/usr/lib64/python2.4/warnings.py", line 96, in warn_explicit
        raise message
    Warning: Data truncated for column 'name' at row 1

The answer seems to be that you can't create an admin user in setUp but you can in any other function so if you want an admin user in testing, use a fixture!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凉世弥音 2024-09-21 05:33:54

我会使用内置的 create_superuser 并在发出任何请求之前让用户登录。以下应该有效:

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', '[email protected]', 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

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', '[email protected]', 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
残月升风 2024-09-21 05:33:54

更新 2

执行代码片段以从测试用例(django.test.TestCase 的子类)中创建超级用户。一切都很顺利。还使用 user = self.adminuser 创建并保存了 UserProfile 的实例。那也有效。

更新

这行很有趣:

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})

看起来创建权限时执行失败。

原始答案

警告:第 1 行“名称”列的数据被截断

奇怪。我从 Django shell 尝试了这个,它对我有用。我在 Ubuntu Jaunty 上使用 Postgresql 8.3 和 Django 1.2.1。您能提供有关您使用的 Django/数据库版本的更多详细信息吗?

此外,User 没有 name 属性。您可以仔细检查一下您是否正在使用 auth.User 吗?

我必须将管理员用户加载为固定装置吗?

您不必必须。但是,如果您仅出于测试目的创建此管理员用户,那么添加一个 Fixture 是个好主意。这就是我在项目中所做的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文