Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass django rest framework response to html?

Tags:

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.

like image 479
Girish Ns Avatar asked Aug 16 '13 13:08

Girish Ns


People also ask

How do I return a response in Django REST Framework?

core. servers. basehttp import FileWrapper ... if format == 'raw': zip_file = open('C:\temp\core\files\CDX_COMPOSITES_20140626. zip', 'rb') response = HttpResponse(FileWrapper(zip_file), content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="%s"' % 'CDX_COMPOSITES_20140626.

How do I upload to Django REST Framework?

So you have two choices: let ModelViewSet and ModelSerializer handle the job and send the request using content-type=multipart/form-data; set the field in ModelSerializer as Base64ImageField (or) Base64FileField and tell your client to encode the file to Base64 and set the content-type=application/json.

How do you pass extra context data to Serializers in Django REST Framework?

In function based views we can pass extra context to serializer with "context" parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with "self. context". From example, to get "exclude_email_list" we just used code 'exclude_email_list = self.

Why do we need Serializers in Django REST Framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.


2 Answers

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') 
like image 128
Lucas H Avatar answered Oct 04 '22 23:10

Lucas H


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.

like image 22
GrvTyagi Avatar answered Oct 04 '22 22:10

GrvTyagi