Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context Aware Browsable API Rendering in Django REST

Is there an easy way to create hyperlinks in the Django Rest Browsable API, but not in the other API renderings. To be clear I would like to render certain fields as hyperlinks when viewing the page through the browsable API but to only render the text component when rendering through JSON.

An example of this use case is to render the pk in the list view as hyperlink to the detail view (similar to: http://chibisov.github.io/drf-extensions/docs/#resourceurifield) but to do this only when viewing the list view in browsable API mode. In regular json GET, I would like to render just the pk.

My hope is to make the browsable API more useable/navigable when accessing through a browser.

Is this in any way relevant: http://www.django-rest-framework.org/api-guide/renderers#browsableapirenderer?

More generally, is there anyway to set the excludes to be dependent on the rendering mode?

like image 997
Alex Rothberg Avatar asked Aug 07 '26 23:08

Alex Rothberg


1 Answers

You can return different serializers in different context, by overriding the get_serializer method on GenericAPIView or any of its subclasses.

Something like this would be about right...

def get_serializer(self, ...):
    if self.request.accepted_renderer.format == 'api':
        # Browsable style
    else:
        # Standard style

If you code that behaviour as a mixin class you'd then be able to easily reuse it throughout your views.

like image 132
Tom Christie Avatar answered Aug 10 '26 00:08

Tom Christie