如何将django rest框架响应传递给html?

Gir*_* Ns 20 python django django-rest-framework

如何将任何请求的django restframework响应传递给html.示例:包含对象的列表,html为articles.html.

我尝试使用rest框架Response:

data= {'articles': Article.objects.all() }
return Response(data, template_name='articles.html')
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

""" AssertionError at /articles/

.accepted_renderer not set on Response """
Run Code Online (Sandbox Code Playgroud)

哪里出错了,请建议我.

小智 51

如果它是基于函数的视图,则需要使用@api_view装饰器来正确显示.我已经看到这个特定的错误发生在这个确切的原因(在基于函数的视图中缺少API视图声明).

from rest_framework.decorators import api_view
# ....

@api_view(['GET', 'POST', ])
def articles(request, format=None):
    data= {'articles': Article.objects.all() }
    return Response(data, template_name='articles.html')
Run Code Online (Sandbox Code Playgroud)


Grv*_*agi 8

在我的情况下,只是忘了在视图函数上设置@api_view(['PUT']).

因此,
.accepted_renderer
将用于呈现未为视图设置的响应的渲染器实例.
在从视图返回响应之前,立即由APIView或@api_view自动设置.