Tworzenie odpowiedzi JSON za pomocą Django i Pythona
Próbuję przekonwertować skrypt odpowiedzi Ajax po stronie serwera na Django HttpResponse, ale najwyraźniej nie działa.
To jest skrypt po stronie serwera:
/* 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.
}
}
}
A to jest konwertowany kod
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))
Używam simplejson do kodowania listy Pythona(więc zwróci tablicę JSON). Nie mogłem jeszcze rozgryźć problemu. Ale myślę, że zrobiłem coś nie tak z "echo".
16 answers
Zwykle używam słownika, a nie Listy do zwracania zawartości JSON.
import json
from django.http import HttpResponse
response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'
Pre-Django 1.7 zwróciłbyś to tak:
return HttpResponse(json.dumps(response_data), content_type="application/json")
Dla Django 1.7+, użyj JsonResponse
Jak pokazano w to tak odpowiedz Jak Tak:
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 10:31:36
Nowość w django 1.7
Możesz użyćjsonresponse obiektów.
From the docs:
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-25 14:41:22
Używam tego, działa dobrze.
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')
Alternatywa:
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,
)
W Django 1.7 jsonresponse obiekty zostały dodane do samego frameworka Django, co czyni to zadanie jeszcze łatwiejszym:
from django.http import JsonResponse
def some_view(request):
return JsonResponse({"key": "value"})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-11 00:36:08
Od Django 1.7 masz standardowy JsonResponse właśnie tego potrzebujesz:
from django.http import JsonResponse
...
return JsonResponse(array_to_js, safe=False)
Nie musisz nawet json.wyrzuć swoją tablicę.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-30 12:29:12
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)
I w widoku:
resp_data = {'my_key': 'my value',}
return JsonResponse(resp_data)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-01 15:51:09
Dla tych, którzy używają Django 1.7 +
from django.http import JsonResponse
def your_view(request):
json_object = {'key': "value"}
return JsonResponse(json_object)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-08 20:12:30
Będziesz chciał użyć serializera django do pomocy z 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")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-13 12:14:10
Z widokami bazującymi na klasach Django możesz napisać:
from django.views import View
from django.http import JsonResponse
class JsonView(View):
def get(self, request):
return JsonResponse({'some': 'data'})
I z Django-Rest-Framework możesz napisać:
from rest_framework.views import APIView
from rest_framework.response import Response
class JsonView(APIView):
def get(self, request):
return Response({'some': 'data'})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-08 06:37:52
Jest to bardzo wygodne z Django w wersji 1.7 lub wyższej, ponieważ masz klasę JsonResponse, która jest podklasą HttpResponse.
from django.http import JsonResponse
def profile(request):
data = {
'name': 'Raghav',
'location': 'India',
'is_active': False,
'count': 28
}
return JsonResponse(data)
Dla starszych wersji Django, musisz użyć obiektu 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')
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-06 18:51:17
Jak korzystać z google app engine z ajax (json)?
Kod Javascript z 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)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-10-03 04:30:42
Kod Django views.py
:
def view(request):
if request.method == 'POST':
print request.body
data = request.body
return HttpResponse(json.dumps(data))
Kod 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>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-12 15:49:15
Najpierw zaimportuj to:
from django.http import HttpResponse
Jeśli masz już JSON:
def your_method(request):
your_json = [{'key1': value, 'key2': value}]
return HttpResponse(your_json, 'application/json')
Jeśli otrzymasz JSON z innego żądania HTTP:
def your_method(request):
response = request.get('https://www.example.com/get/json')
return HttpResponse(response, 'application/json')
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-20 05:55:57
To jest moja preferowana wersja używająca widoku opartego na klasach. Wystarczy podklasować Widok podstawowy i nadpisać metodę get ().
import json
class MyJsonView(View):
def get(self, *args, **kwargs):
resp = {'my_key': 'my value',}
return HttpResponse(json.dumps(resp), mimetype="application/json" )
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-12 18:53:25
Użyj JsonResponse
from django.http import JsonResponse
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-03 08:12:20
W widoku użyj tego:
form.field.errors|striptags
Do pobierania wiadomości walidacyjnych bez html
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-15 16:47:29
Większość z tych odpowiedzi jest nieaktualna. JsonResponse nie jest zalecany, ponieważ ucieka znakom, co zwykle jest niepożądane. Oto czego używam:
Views.py (zwraca 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 (zwraca 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')
Bonus dla użytkowników Vue
Jeśli chcesz wprowadzić swój Queryset Django do Vue, możesz wykonać następujące czynności.
Szablon.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>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-30 17:58:38