How to pass django rest framework response to html

2020-05-26 00:25发布

问题:

How to pass django restframework response for any request to html. Example: A list which contains objects, and html be 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.

回答1:

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).

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')


回答2:

In my case just forgot to set @api_view(['PUT']) on view function.

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.



回答3:

Have you added TemplateHTMLRenderer in your settings?

http://www.django-rest-framework.org/api-guide/renderers/#setting-the-renderers



回答4:

You missed TemplateHTMLRenderer decorator:

@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer,))
def articles(request, format=None):
    data= {'articles': Article.objects.all() }
    return Response(data, template_name='articles.html')