Creating a JSON response using Django and Python

后端 未结 15 2156
温柔的废话
温柔的废话 2020-11-22 06:02

I\'m trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it\'s not working.

This is the server-side script:



        
相关标签:
15条回答
  • 2020-11-22 06:28

    For those who use Django 1.7+

    from django.http import JsonResponse
    
    def your_view(request):
        json_object = {'key': "value"}
        return JsonResponse(json_object)
    

    official docs

    0 讨论(0)
  • 2020-11-22 06:28

    Its very convenient with Django version 1.7 or higher as you have the JsonResponse class, which is a subclass of HttpResponse.

    from django.http import JsonResponse
        def profile(request):
            data = {
                'name': 'Raghav',
                'location': 'India',
                'is_active': False,
                'count': 28
            }
            return JsonResponse(data)
    

    For older versions of Django, you must use an HttpResponse object.

    import json
    from django.http import HttpResponse
    
    def profile(request):
        data = {
            'name': 'Raghav',
            'location': 'India',
            'is_active': False,
            'count': 28
        }
        dump = json.dumps(data)
        return HttpResponse(dump, content_type='application/json')
    
    0 讨论(0)
  • 2020-11-22 06:32

    With Django Class-based views you can write:

    from django.views import View
    from django.http import JsonResponse
    
    class JsonView(View):
        def get(self, request):
            return JsonResponse({'some': 'data'})
    

    and with Django-Rest-Framework you can write:

    from rest_framework.views import APIView
    from rest_framework.response import Response
    
    class JsonView(APIView):
        def get(self, request):
            return Response({'some': 'data'})
    
    0 讨论(0)
  • 2020-11-22 06:36

    How to use google app engine with ajax (json)?

    Code Javascript with JQuery:

    $.ajax({
        url: '/ajax',
        dataType : 'json',
        cache: false,
        success: function(data) {
            alert('Load was performed.'+data.ajax_resp);
        }
    });
    

    Code Python

    class Ajax(webapp2.RequestHandler):
        def get(self):
            my_response = {'ajax_resp':'Hello, webapp World!'}
            datos = json.dumps(my_response)
    
            self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
            self.response.out.write(datos)
    
    0 讨论(0)
  • 2020-11-22 06:36

    This is my preferred version using a class based view. Simply subclass the basic View and override the get()-method.

    import json
    
    class MyJsonView(View):
    
        def get(self, *args, **kwargs):
            resp = {'my_key': 'my value',}
            return HttpResponse(json.dumps(resp), mimetype="application/json" )
    
    0 讨论(0)
  • 2020-11-22 06:39

    Django code views.py:

    def view(request):
        if request.method == 'POST':
            print request.body
            data = request.body
            return HttpResponse(json.dumps(data))
    

    HTML code view.html:

    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("#mySelect").change(function(){
            selected = $("#mySelect option:selected").text()
            $.ajax({
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                url: '/view/',
                data: {
                        'fruit': selected
                      },
                success: function(result) {
                            document.write(result)
                        }
        });
      });
    });
    </script>
    </head>
    <body>
    
    <form>
        {{data}}
        <br>
    Select your favorite fruit:
    <select id="mySelect">
      <option value="apple" selected >Select fruit</option>
      <option value="apple">Apple</option>
      <option value="orange">Orange</option>
      <option value="pineapple">Pineapple</option>
      <option value="banana">Banana</option>
    </select>
    </form>
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题