How do I return JSON without using a template in Django?

前端 未结 9 1546
再見小時候
再見小時候 2020-12-04 07:01

This is related to this question: Django return json and html depending on client python


I have a command line Python API for a Django app. When I access the a

相关标签:
9条回答
  • 2020-12-04 07:41

    In Django 1.7 this is even easier with the built-in JsonResponse.

    https://docs.djangoproject.com/en/dev/ref/request-response/#jsonresponse-objects

    # import it
    from django.http import JsonResponse
    
    def my_view(request):
    
        # do something with the your data
        data = {}
    
        # just return a JsonResponse
        return JsonResponse(data)
    
    0 讨论(0)
  • 2020-12-04 07:41

    It looks like the Django REST framework uses the HTTP accept header in a Request in order to automatically determine which renderer to use:

    http://www.django-rest-framework.org/api-guide/renderers/

    Using the HTTP accept header may provide an alternative source for your "if something".

    0 讨论(0)
  • 2020-12-04 07:42

    You could also check the request accept content type as specified in the rfc. That way you can render by default HTML and where your client accept application/jason you can return json in your response without a template being required

    0 讨论(0)
提交回复
热议问题