python - Django:如何通过 django.template.context.RequestContext 进行搜索
问题描述
我正在 Django 中进行测试并面临 <class 'django.template.context.RequestContext'>,我试图遍历并在其中找到 <class 'ecom.models.Product'> 对象。
测试.py
def test_ProductDetail_object_in_context(self):
response = self.client.get(reverse('product_detail', args=[1]))
# assertEqual - test passes
self.assertEqual(response.context[0]['object'], Product.objects.get(id=1))
# assertIn - test fails
self.assertIn(Product.objects.get(id=1), response.context[0])
视图.py
class ProductDetailView(DetailView):
model = Product
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
data = cartData(self.request)
cartItems = data['cartItems']
context['cartItems'] = cartItems
return context
response.context 里面有什么:
[
[
{'True': True, 'False': False, 'None': None},
{'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x7fd80>>,
'request': <WSGIRequest: GET '/1/'>,
'user': <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7fd820>>, '
perms': <django.contrib.auth.context_processors.PermWrapper object at 0x7fd80>,
'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7fd8290>,
'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}
},
{},
{'object': <Product: Pen>,
'product': <Product: Pen>,
'view': <ecom.views.ProductDetailView object at 0x7fd8210>,
'cartItems': 0}
],
[
{'True': True, 'False': False, 'None': None},
{'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at 0x7fd8240>>,
'request': <WSGIRequest: GET '/1/'>,
'user': <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7fd8250>>,
'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x7fd8250>,
'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7fd8290>,
'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}
},
{},
{'object': <Product: Pen>,
'product': <Product: Pen>,
'view': <ecom.views.ProductDetailView object at 0x7fd8210>,
'cartItems': 0}
]
]
response.context 的类型:
<class 'django.template.context.RequestContext'>
Product.objects.get(id=1) 里面的内容是:Pen
Product.objects.get(id=1) 的类型是:<class 'ecom.models.Product'>
我不明白为什么:
它在 self.assertEqual(response.context[0]['object'], Product.objects.get(id=1)) 中找到 Product 对象,但在 self.assertIn(Product.objects.get(id=1) 中找不到, response.context[0]['object']) - 说 TypeError: 'Product' 类型的参数不可迭代
它也没有在 self.assertIn(Product.objects.get(id=1), response.context[0]) 中找到它 - 说“AssertionError: <Product: Pen> not found in [....here go response.context[0]....] 的内容
它也没有在 self.assertIn(Product.objects.get(id=1), response.context[0][3]) 中找到它 - 说“在getitem raise KeyError (key), KeyError: 3”
如何使用 RequestContext 类?JSON之类的?
抱歉有点混淆问题,只是想了解如何使用 RequestContext。先感谢您!
解决方案
我认为您的测试失败了,因为assertIn
查看的是 KEYS 而不是值。解决方案是:
self.assertIn(Product.objects.get(id=1), response.context[0].values())
多一点解释:response.context[0]
似乎它是一些键值存储,即字典。当你这样做时response.context[0]["object"]
,你刚刚访问了response.context[0]
dict 所在的键“object”处的值。对字典进行一些in
查询只会查找字典的键。
推荐阅读
- laravel - 注销路由是否应该受到保护?
- android - Kotlin Flow:带有回调对象延迟初始化器的 callbackFlow
- php - 如何在 symfony 5.2 中将实体依赖注入到控制器中?
- r - 如何绘制具有不连续 y 轴的构面
- oracle - 在 Oracle 中在另一个视图上创建物化视图而不会过时/需要编译状态
- netsuite - Suitescript 2.0 获取子列表上的按钮
- r - R:改变稀疏矩阵的对角线非常慢
- bots - 如何使用 ID 添加对特定消息的反应?(discord.py)
- javascript - 将 API 中的 JSON 数据保存到数据库中并缓存请求,因此我不需要再次从 API 请求 - Node.js / Express.js
- c# - 我有 ac# 一个控制台应用程序,我需要将其转换为 Azure 函数