How to have a view determine renderer (i.e. enable content negotiation) based on format= query param when Accept headers aren't set

59 views
Skip to first unread message

Ben

unread,
Nov 18, 2012, 2:29:20 AM11/18/12
to django-res...@googlegroups.com
I've almost got my API put back together in DRF 2. One final (hopefully) snag: 

I assume this used to work in pre 2.X (since its what my client apps are sending, and production works), but it seems to not work out of the box now with the new DRF version.  

My client is GET'ing something like the following URL in a json-p based ajax request:


The Accept headers aren't correct.  (i.e. don't include JSON-P or JSON) .

I have the renderer_classes = (JSONPRenderer, ...) in my view. So, I'm wondering how to get things to render as JSONP based on the format= querystring param.  I thought I may have seen this in the docs, but can't find anything about it.  Currently, it 404's. 

I'm loving the new framework, guys!

Ben Roberts
Nutrislice


Tom Christie

unread,
Nov 18, 2012, 1:01:08 PM11/18/12
to django-res...@googlegroups.com
I think that changed from 'json-p' to 'jsonp' somewhere down the road to 2.0.  [apologies]

Ben

unread,
Nov 19, 2012, 5:33:47 PM11/19/12
to django-res...@googlegroups.com
Its all good, it is after all a backwards incompatible update.  

A little more digging and it was a super easy override.  I just made a custom JSONPRenderer class that extends the DRF one, and declared " format='json-p' "  and that was all it needed. So far the new framework has been very friendly to customization. 

Thanks,

Ben

Joann Prescott-Roy

unread,
Nov 20, 2014, 9:57:21 AM11/20/14
to django-res...@googlegroups.com
I'm doing a similar thing.  I'm receiving GETs in which the Accept-headers aren't correct, either.  Based on the parameters I receive, I am transforming string data into various chemical data types or images.  I have custom renderers to handle the data types I am using.  In my view, I am attempted to set the accepted_renderer to the correct renderer.  I have tried setting accepted_renderer on the request and the response without success.  My results still come back as JSON.

Code snippets
------------------------------------
In renderers.py 

class MolRenderer(BaseRenderer):
    media_type = 'chemical/x-mdl-molfile'
    format = 'mol'
    
    def render(self, data, accepted_media_type=None, renderer_context=None):
        return data
----------------------------------------
In my view:

if serializer.data['output_type'] == 'mol':
         request.accepted_renderer = MolRenderer()

-------------
I know this has to do with content negotiation, but, I'm not keen to write my own content negotiation unless absolutely necessary.

Thanks for any advice/help.

-Joann
Reply all
Reply to author
Forward
0 new messages