3

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You actually have to compare against a format of 'api' not HTML.
1

I created this mixin to use the serializer_class_api when in API mode:

class SerializerAPI(object):
    def get_serializer_class(self, *args, **kwargs):
        parent = super(SerializerAPI, self).get_serializer_class(*args, **kwargs)
        if (hasattr(self.request, 'accepted_renderer') and 
          self.request.accepted_renderer.format == 'api'):
            return self.serializer_class_api
        else:
            return parent

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.