Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-rest-framework: set default renderer not working?

I'm trying to build a Django-rest-framework REST API that outputs JSON by default, but has XML available too.

I have read the Renderers chapter of the documentation section on default ordering, and have put this in my settings file:

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework_xml.renderers.XMLRenderer',
    )
}

However, this outputs XML by default. Switching the order makes no difference.

I do get JSON if I append format=json to the URL, and if I remove the XMLRenderer line altogether.

How can I set JSON to be the default?

I'm using v1.7 of Django and v3.1.1 of Django-rest-framework.

UPDATE: As requested here is the code for my views:

class CountyViewSet(viewsets.ModelViewSet):
    queryset = County.objects.all()
    serializer_class = CountySerializer

And the serializer:

from rest_framework import serializers
class CountySerializer(serializers.ModelSerializer):
    class Meta:
        model = County
        fields = ('id', 'name', 'name_slug', 'ordering')

And then finally from my urls file:

router = routers.DefaultRouter()
router.register(r'county', CountyViewSet)
urlpatterns = [
    url(r'^', include(router.urls)),
]
like image 646
Richard Avatar asked Apr 04 '15 22:04

Richard


1 Answers

my solution: file renderers.py

from rest_framework.negotiation import DefaultContentNegotiation

class IgnoreClientContentNegotiation(DefaultContentNegotiation):

    logger = logging.getLogger(__name__)
    def select_renderer(self, request, renderers, format_suffix):
        """
        Select the first renderer in the `.renderer_classes` list.
        """
        # Allow URL style format override.  eg. "?format=json
        format_query_param = self.settings.URL_FORMAT_OVERRIDE
        format = format_suffix or request.query_params.get(format_query_param)
        request.query_params.get(format_query_param), format))

        if format is None:
            return (renderers[0], renderers[0].media_type)
        else:
            return DefaultContentNegotiation.select_renderer(self, request, renderers, format_suffix)

Now just need add to settings.py in

REST_FRAMEWORK = { 
 (...)
'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.renderers.IgnoreClientContentNegotiation',
}
like image 158
Sérgio Avatar answered Sep 18 '22 17:09

Sérgio