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

前端 未结 9 1602
再見小時候
再見小時候 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:34

    Here's an example I needed for conditionally rendering json or html depending on the Request's Accept header

    # myapp/views.py
    from django.core import serializers                                                                                
    from django.http import HttpResponse                                                                                  
    from django.shortcuts import render                                                                                   
    from .models import Event
    
    def event_index(request):                                                                                             
        event_list = Event.objects.all()                                                                                  
        if request.META['HTTP_ACCEPT'] == 'application/json':                                                             
            response = serializers.serialize('json', event_list)                                                          
            return HttpResponse(response, content_type='application/json')                                                
        else:                                                                                                             
            context = {'event_list': event_list}                                                                          
            return render(request, 'polls/event_list.html', context)
    

    you can test this with curl or httpie

    $ http localhost:8000/event/
    $ http localhost:8000/event/ Accept:application/json
    

    note I opted not to use JsonReponse as that would reserialize the model unnecessarily.

提交回复
热议问题