gpt4 book ai didi

Django 测试失败,通用 CreateView 中的 get_inital 中的 request.user

转载 作者:行者123 更新时间:2023-11-28 21:33:41 25 4
gpt4 key购买 nike

我有一个像这样的通用 View :

class SaveView(CreateView):

def get_initial(self):
# Get the initial dictionary from the superclass method
initial = super(SaveView, self).get_initial()
# Copy the dictionary so we don't accidentally change a mutable dict
initial = initial.copy()
initial['user'] = self.request.user
return initial

此 View 具有 login_required 装饰器,因此 self.request.user 始终有效。

当我使用浏览器访问页面时,一切正常,但我的测试失败了。我有以下测试设置:

from django.test import TestCase, client

class MyTest(TestCase):
def setUp(self):
self.client = client.Client()
def test1(self):
self.assertTrue(self.client.login(username='user1',password='password1'))
data = {'name':'test 1'}
response = self.client.post('/app/save/', data)
self.assertEqual(response.status_code, 302)

'/app/save/' 是调用该 View 的 url(它在浏览器上运行良好我的模型有 2 个必填字段“名称”和“用户”,因此这应该发出重定向到创建的对象页面,因为我已经通过数据传递了名称并且应该从 get_initial 方法获取用户。

确实这就是“现实生活”中发生的事情,即浏览器。

我能让这个测试成功通过数据字典中的“用户”的唯一方法。

这是 django.test 模块中的错误还是这是预期的行为,为什么?

提前致谢

最佳答案

这是预期的行为。来自初始数据的 Django 文档:

The initial argument lets you specify the initial value to use when rendering this Field in an unbound Form.

当您在测试中发布数据时,您使用的是绑定(bind)表单,因此不使用初始数据。表单无效,因为缺少必需的 user 字段,因此返回显示表单错误的 200 响应。这与清除浏览器中的用户字段并提交表单时会发生的情况相同。

您需要将用户包含在您的post 数据中,然后测试才会通过。

关于Django 测试失败,通用 CreateView 中的 get_inital 中的 request.user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9033980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com