ValueError:Content-Type 标头是“text/html”,而不是“application/json” Django 蟒蛇
我正在尝试对我的视图之一运行测试,但我不断收到此错误 raise ValueError( ValueError: Content-Type header is "text/html", not "application/json"
这是查看函数
def add_to_cart(request):
cart = Cart(request)
if request.POST.get("action") == "post":
product_id = int(request.POST.get("productid"))
product_qty = int(request.POST.get("productqty"))
product = get_object_or_404(Product, id=product_id)
cart.add(product=product, qty=product_qty)
product_qty = cart.__len__()
response = JsonResponse({"qty": product_qty})
return response
这是 URL 路径
from django.urls import path
from . import views
app_name = "cart"
urlpatterns = [
path("add/", views.add_to_cart, name="add_to_cart"),
]
最后是测试
def test_add_to_cart(self):
response = self.client.post(reverse('cart:add_to_cart'), {
"productid": 3,
"productqty": 1,
"action":'post',
}, xhr=True)
print(response.status_code)
self.assertTrue(response.json(), {'qty':4})
response = self.client.post(reverse('cart:add_to_cart'), {
"productid": 2,
"productqty": 1,
"action":'post',
}, xhr=True)
self.assertTrue(response.json(), {'qty':3})
I am trying to run a test for one of my views but I keep getting this error raise ValueError( ValueError: Content-Type header is "text/html", not "application/json"
Here is the view function
def add_to_cart(request):
cart = Cart(request)
if request.POST.get("action") == "post":
product_id = int(request.POST.get("productid"))
product_qty = int(request.POST.get("productqty"))
product = get_object_or_404(Product, id=product_id)
cart.add(product=product, qty=product_qty)
product_qty = cart.__len__()
response = JsonResponse({"qty": product_qty})
return response
Here is the URL path
from django.urls import path
from . import views
app_name = "cart"
urlpatterns = [
path("add/", views.add_to_cart, name="add_to_cart"),
]
And lastly the test
def test_add_to_cart(self):
response = self.client.post(reverse('cart:add_to_cart'), {
"productid": 3,
"productqty": 1,
"action":'post',
}, xhr=True)
print(response.status_code)
self.assertTrue(response.json(), {'qty':4})
response = self.client.post(reverse('cart:add_to_cart'), {
"productid": 2,
"productqty": 1,
"action":'post',
}, xhr=True)
self.assertTrue(response.json(), {'qty':3})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上一切都工作正常,错误来自我使用的 self.assertTrue ;
我实际上是想使用 self.assertEqual
Everything is actually working fine, the error came from the
self.assertTrue
that I used;I was actually meant to use
self.assertEqual