ChatGPT解决这个技术问题 Extra ChatGPT

使用 Django 和 Python 创建 JSON 响应

我正在尝试将服务器端 Ajax 响应脚本转换为 Django HttpResponse,但显然它不起作用。

这是服务器端脚本:

/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];

/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
$arrayToJs[1] = $validateError;

if($validateValue =="Testuser"){  // Validate??
    $arrayToJs[2] = "true";       // RETURN TRUE
    echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';  // RETURN ARRAY WITH success
}
else{
    for($x=0;$x<1000000;$x++){
        if($x == 990000){
            $arrayToJs[2] = "false";
            echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';   // RETURNS ARRAY WITH ERROR.
        }
    }
}

这是转换后的代码

def validate_user(request):
    if request.method == 'POST':
        vld_value = request.POST.get('validateValue')
        vld_id = request.POST.get('validateId')
        vld_error = request.POST.get('validateError')

        array_to_js = [vld_id, vld_error, False]

        if vld_value == "TestUser":
            array_to_js[2] = True
            x = simplejson.dumps(array_to_js)
            return HttpResponse(x)
        else:
            array_to_js[2] = False
            x = simplejson.dumps(array_to_js)
            error = 'Error'
            return render_to_response('index.html',{'error':error},context_instance=RequestContext(request))
    return render_to_response('index.html',context_instance=RequestContext(request))

我正在使用 simplejson 对 Python 列表进行编码(因此它将返回一个 JSON 数组)。我还没有弄清楚问题所在。但我认为我对“回声”做错了。

您还可以使用 django-annoying 视图装饰器 @ajax_request

C
Community

我通常使用字典而不是列表来返回 JSON 内容。

import json

from django.http import HttpResponse

response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'

Pre-Django 1.7 你会像这样返回它:

return HttpResponse(json.dumps(response_data), content_type="application/json")

对于 Django 1.7+,使用 this SO answer 中所示的 JsonResponse,如下所示:

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

应该让他陷入麻烦的是模仿类型,而不是列表。虽然大多数 JSON 通常是顶层的对象(“字典”),但 JSON 对顶层的数组非常满意。
抱歉,从我写的内容中不清楚,但我只是说我使用字典,因为将它序列化为 JSON 时它更干净/更容易。
旧版本的 IE 不正确支持“application/json”。以下是对问题 github.com/blueimp/jQuery-File-Upload/issues/123 的一些讨论
s
srj

Django 1.7 中的新功能

您可以使用 JsonResponse 对象。

来自文档:

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

一个缺点:它默认为 ensure_ascii,我还没有找到覆盖它的方法。为此创建了一个新问题:stackoverflow.com/q/34798703/854477
@int_ua:只需添加 json_dumps_params={"ensure_ascii": False} (需要 Django 1.9 或更高版本)
U
User

我用这个,效果很好。

from django.utils import simplejson
from django.http import HttpResponse

def some_view(request):
    to_json = {
        "key1": "value1",
        "key2": "value2"
    }
    return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')

选择:

from django.utils import simplejson

class JsonResponse(HttpResponse):
    """
        JSON response
    """
    def __init__(self, content, mimetype='application/json', status=None, content_type=None):
        super(JsonResponse, self).__init__(
            content=simplejson.dumps(content),
            mimetype=mimetype,
            status=status,
            content_type=content_type,
        )

在 Django 1.7 中,JsonResponse 对象已添加到 Django 框架本身,这使得这项任务更加容易:

from django.http import JsonResponse
def some_view(request):
    return JsonResponse({"key": "value"})

问题在于它没有从输入字段 vld_value = request.POST.get('validateValue')
使用 python 2.7,它应该只是“import json”
我认为 from django.utils import simplejson 是为了向后兼容。
JsonResponse(status=404, data={'status':'false','message':message})
A
Akhorus

从 Django 1.7 开始,您就有了一个标准的 JsonResponse,这正是您所需要的:

from django.http import JsonResponse
...
return JsonResponse(array_to_js, safe=False)

你甚至不需要 json.dump 你的数组。


A
Andres

对于那些使用 Django 1.7+ 的人

from django.http import JsonResponse

def your_view(request):
    json_object = {'key': "value"}
    return JsonResponse(json_object)

official docs


e
elim

使用基于 Django 类的视图,您可以编写:

from django.views import View
from django.http import JsonResponse

class JsonView(View):
    def get(self, request):
        return JsonResponse({'some': 'data'})

并且使用 Django-Rest-Framework 您可以编写:

from rest_framework.views import APIView
from rest_framework.response import Response

class JsonView(APIView):
    def get(self, request):
        return Response({'some': 'data'})

D
Dmitry Demidenko
from django.http import HttpResponse
import json

class JsonResponse(HttpResponse):
    def __init__(self, content={}, mimetype=None, status=None,
             content_type='application/json'):
        super(JsonResponse, self).__init__(json.dumps(content), mimetype=mimetype,
                                           status=status, content_type=content_type)

在视图中:

resp_data = {'my_key': 'my value',}
return JsonResponse(resp_data)

R
ReduxDJ

您需要使用 django 序列化程序来帮助处理 unicode 内容:

from django.core import serializers

json_serializer = serializers.get_serializer("json")()
    response =  json_serializer.serialize(list, ensure_ascii=False, indent=2, use_natural_keys=True)
    return HttpResponse(response, mimetype="application/json")

这是我的首选版本,但我意识到它eats only Django QuerySets
T
Tanmay D

使用 Django 1.7 或更高版本非常方便,因为您有 JsonResponse 类,它是 HttpResponse 的子类。

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

对于旧版本的 Django,您必须使用 HttpResponse 对象。

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')

完全正确!
h
hygull

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

使用 JQuery 编写 Javascript 代码:

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

代码 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)

N
Nick

首先导入这个:

from django.http import HttpResponse

如果您已经拥有 JSON:

def your_method(request):
    your_json = [{'key1': value, 'key2': value}]
    return HttpResponse(your_json, 'application/json')

如果您从另一个 HTTP 请求中获取 JSON:

def your_method(request):
    response = request.get('https://www.example.com/get/json')
    return HttpResponse(response, 'application/json')

d
droidballoon

这是我使用基于类的视图的首选版本。只需子类化基本视图并覆盖 get() 方法。

import json

class MyJsonView(View):

    def get(self, *args, **kwargs):
        resp = {'my_key': 'my value',}
        return HttpResponse(json.dumps(resp), mimetype="application/json" )

K
Kriti Singh

Django 代码 views.py

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

HTML 代码 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>

d
devdrc

这些答案中的大多数都已过时。不推荐使用 JsonResponse,因为它会转义字符,这通常是不受欢迎的。这是我使用的:

views.py(返回 HTML)

from django.shortcuts import render
from django.core import serializers

def your_view(request):
    data = serializers.serialize('json', YourModel.objects.all())
    context = {"data":data}
    return render(request, "your_view.html", context)

views.py(返回 JSON)

from django.core import serializers
from django.http import HttpResponse

def your_view(request):
    data = serializers.serialize('json', YourModel.objects.all())
    return HttpResponse(data, content_type='application/json')

Vue 用户的奖励

如果您想将您的 Django 查询集带入 Vue,您可以执行以下操作。

模板.html

<div id="dataJson" style="display:none">
{{ data }}
</div>

<script>
let dataParsed = JSON.parse(document.getElementById('dataJson').textContent);
var app = new Vue({
  el: '#app',
  data: {
    yourVariable: dataParsed,
  },
})
</script>

D
Deepak Sharma

在视图中使用这个:

form.field.errors|striptags

用于获取没有 html 的验证消息


N
NINSIIMA WILBER
def your_view(request):
    response = {'key': "value"}
    return JsonResponse(json.dumps(response), content_type="application/json",safe=False)

#指定content_type并使用json.dump()子作为不作为对象发送的内容


如果您调用 django.http.JsonResponse() 您不必转储内容,并且默认 content_type 已设置为 application/json
J
Joe Web

这样,可以将 json 内容下载为具有特定文件名的文件。

import json
from django.http import HttpResponse

def download_json(request):
    data = {'some': 'information'}

    # serialize data obj as a JSON stream 
    data = json.dumps(data)
    response = HttpResponse(data, content_type='application/json charset=utf-8')

    # add filename to response
    response['Content-Disposition'] = 'attachment; filename="filename.json"'
    return response