gpt4 book ai didi

django - 如何在 Django 泛型 ListView 中返回 JsonResponse

转载 作者:行者123 更新时间:2023-12-04 12:50:23 27 4
gpt4 key购买 nike

我在 ListView 中返回有效的 HttpResponse 时遇到问题(并且收到了 ValueError: The view didn't return an HttpResponse object.. .。我重写了 get,因为我想返回一个 JsonResponse:

def get(self, requets, *args, **kwargs):
queryset = self.get_queryset()
data = serializers.serialize("json", queryset)
return JsonResponse(data, status=200, safe=False)

我已经检查过 querysetdata 以及 JsonResponse 不是 None。更改返回语句不起作用:

return HttpResponse(json.dumps(data), content_type="application/json", status=200)

以前,如果我需要重写 get,我会 return render(...),这很有效。

那么,根据本例中的错误,为什么我的 HttpResponseJsonResponse 不是可接受的 HttpResponse? GET 请求将是一个 ajax 请求,我确实需要提供一些合理的 json 作为回复。

编辑:全类

from django.core import serializers
from django.http import JsonResponse
@method_decorator(login_required, name='dispatch')
class AjaxQuestionList(ListView):
"""
Generic ListView for Question objects. Called by front-end app.
Requires hash url parameter to identify Survey.
Intended to be called via ajax. Returns serialized json list of Questions.
"""
http_method_names = ['get',]

def dispatch(self, request, *args, **kwargs):
#allow user to call this View if their Client owns the Survey
self.survey = get_object_or_404(Survey, hash=self.kwargs['hash'])
up = get_object_or_404(UserProfile, fk_user=self.request.user)
self.client = up.fk_client
if self.survey.fk_client != self.client:
raise Http404
super(AjaxQuestionList, self).dispatch(request, *args, **kwargs)

def get_queryset(self):
return Question.objects.filter(fk_survey=self.survey)

def get(self, request, *args, **kwargs):
queryset = self.get_queryset()
data = serializers.serialize("json", queryset)
return JsonResponse(data, status=200, safe=False)

回溯:

File "/webapps/escher/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request)

File "/webapps/escher/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request)

File "/webapps/escher/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 198. "returned None instead." % (callback.module, view_name)

Exception Type: ValueError at /si/survey/123456789/ajax-question-list/ Exception Value: The view myapp.views.survey.AjaxQuestionList didn't return an HttpResponse object. It returned None instead.

CBV flattened index 我只是假设 render_to_response()get() 之后自动调用,呈现返回的任何 HttpResponse get()。我错了吗?

最佳答案

您需要在您的调度方法中返回 super() 的结果。

def dispatch(self, request, *args, **kwargs):
...
return super(AjaxQuestionList, self).dispatch(request, *args, **kwargs)

如果没有 return 语句,该方法将返回 None,因此您会收到错误消息。

关于django - 如何在 Django 泛型 ListView 中返回 JsonResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39768671/

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