gpt4 book ai didi

python - 从 Django django-rest-framework 的 View 有条件地返回 JSON 或 HTML 响应

转载 作者:太空狗 更新时间:2023-10-30 03:01:12 25 4
gpt4 key购买 nike

如何从 Django django-rest-framework 的 View 有条件地返回 JSON 或 HTML 响应?

  1. djangorestframework == 2.3.10

  2. 我的settings.py:

REST_FRAMEWORK = {
'PAGINATE_BY': 10,
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.TemplateHTMLRenderer',
'rest_framework.renderers.JSONRenderer',
)
}
  1. 在我的 url.py 中,我将其添加为最后一行:
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
  1. 我的观点是这样的:
def myview(request, id, format='json'):
if format == 'json' or format is None:
return Response(my_dict, status=status.HTTP_200_OK)
else:
return Response(my_dict, template_name='myhtml.html')

如果我在 url 请求中明确使用 .html.json format_prefix ,一切正常。但如果我不指定任何格式,它会给我以下错误。

ImproperlyConfigured at /objects/29
Returned a template response with no template_name attribute set oneither the view or response
Request Method: GET
Request URL: localhost:8000/objects/29
Django Version: 1.7
Exception Type: ImproperlyConfigured
Exception Value: Returned a template response with no template_nameattribute set on either the view or response
Exception Location: D:\WORKSPACE\user...\lib\site-

我也试过:

urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html', 'None'])

但是好像也没用。

有人可以帮忙吗?谢谢!

最佳答案

这对我有用:

class MyView(ListAPIView):
renderer_classes = (JSONRenderer, TemplateHTMLRenderer,)

def get(self, request, *args, **kwargs):
data = SomerSerializer([]).data
if request.accepted_renderer.format == 'html':
return Response(data, template_name='blah.html')

return Response(data)

仅供引用,我以前遇到过这个错误,但这不是因为它配置正确 - 这是因为在它出错之前一些不相关的代码 - 所以寻找任何其他可能失败的地方。另请注意,您的“其他”是多余的。

关于python - 从 Django django-rest-framework 的 View 有条件地返回 JSON 或 HTML 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26329614/

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