Python 如何将 django rest 框架响应传递给 html?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18273966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass django rest framework response to html?
提问by Girish Ns
How to pass django restframework response for any request to html. Example: A list which contains objects, and html be articles.html.
如何将 django restframework 响应传递给 html 的任何请求。示例:包含对象的列表,html 为articles.html。
I tried by using rest framework Response :
我尝试使用休息框架响应:
data= {'articles': Article.objects.all() }
return Response(data, template_name='articles.html')
I am getting this error :
我收到此错误:
""" AssertionError at /articles/
.accepted_renderer not set on Response """
Where i went wrong, please suggest me.
我哪里出错了,请给我建议。
回答by Tom Christie
Have you added TemplateHTMLRenderer
in your settings?
你TemplateHTMLRenderer
在你的设置里加了吗?
http://www.django-rest-framework.org/api-guide/renderers/#setting-the-renderers
http://www.django-rest-framework.org/api-guide/renderers/#setting-the-renderers
回答by Lucas H
If it's a function based view, you made need to use an @api_view decorator to display properly. I've seen this particular error happen for this exact reason (missing API View declaration in function based views).
如果它是基于函数的视图,则需要使用 @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')
回答by Pedro Vagner
You missed TemplateHTMLRenderer
decorator:
你错过了TemplateHTMLRenderer
装饰器:
@api_view(('GET',)) @renderer_classes((TemplateHTMLRenderer,)) def articles(request, format=None): data= {'articles': Article.objects.all() } return Response(data, template_name='articles.html')
回答by GrvTyagi
In my case just forgot to set @api_view(['PUT']) on view function.
就我而言,只是忘记在视图函数上设置 @api_view(['PUT']) 。
So,
.accepted_renderer
The renderer instance that will be used to render the response not set for view.
Set automatically by the APIView or @api_view immediately before the response is returned from the view.
因此,
.accepted_renderer
将用于呈现未为视图设置的响应的渲染器实例。
在从视图返回响应之前立即由 APIView 或 @api_view 自动设置。