You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django测试:通过Admin面板创建Item模型失败,报AssertionError

Django Admin测试创建Item失败:AssertionError排查

针对你遇到的测试用例无法创建Item、抛出AssertionError: False is not true的问题,从几个常见方向排查:

1. 检查多选字段types的提交格式

如果types是多对多字段或外键多选,Django Admin接受的是对应模型的主键ID,而不是显示的文本值。你提交的["КБТ", "МБТ"]是显示文本,需要先创建对应的Type实例,再传递它们的ID:

# 在setUp中提前创建types实例
self.type_kbt = Type.objects.create(name="КБТ")
self.type_mbt = Type.objects.create(name="МБТ")

# POST请求中替换为ID列表
'types': [self.type_kbt.id, self.type_mbt.id],

2. 验证POST请求是否真的成功

Django Admin创建成功后会返回302重定向,先加断言确认请求状态:

self.assertEqual(response.status_code, 302)

如果返回200,说明表单验证失败,打印response.content可以看到Admin页面的错误提示,比如字段缺失、格式错误等。

3. 确认ItemAdmin包含所有提交字段

检查你的ItemAdmin类,确保fields或fieldsets中包含了所有你提交的字段(title、description、price等)。如果某个字段不在Admin的可编辑列表中,提交时会被直接忽略。

4. 强制确认登录状态

虽然你认为登录成功,还是可以加一行断言验证:

login_success = self.client.login(email='admin@example.com', password='admin')
self.assertTrue(login_success)

修改后的测试代码示例

class ItemAdminTest(TestCase):
    serialized_rollback = True

    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_superuser(email='admin@example.com', password='admin')
        # 提前创建types实例
        self.type_kbt = Type.objects.create(name="КБТ")
        self.type_mbt = Type.objects.create(name="МБТ")

    def test_create_item_admin(self):
        # 验证登录成功
        login_success = self.client.login(email='admin@example.com', password='admin')
        self.assertTrue(login_success)

        response = self.client.post('/admin/product/item/add/', {
            'title': 'Test Item',
            'description': 'Test Description',
            'price': 10.00,
            'code': 123456,
            'color': 'Red',
            'weight': 1.5,
            'height': 10.0,
            'width': 5.5,
            'types': [self.type_kbt.id, self.type_mbt.id],
            'amount': 5,
        })

        # 确认请求重定向成功
        self.assertEqual(response.status_code, 302)
        # 检查Item是否创建
        self.assertTrue(Item.objects.filter(title='Test Item').exists())

内容的提问来源于stack exchange,提问作者Mir1a

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:09:52