Gdzie są moje dane JSON w moim przychodzącym żądaniu Django?
Próbuję przetworzyć przychodzące żądania JSON / Ajax za pomocą Django / Pythona.
request.is_ajax()
jest True
na żądanie, ale nie mam pojęcia, gdzie jest ładunek z danymi JSON.
request.POST.dir
zawiera:
['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
'__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding',
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding',
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues',
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update',
'urlencode', 'values']
Nie ma widocznie żadnych kluczy w kluczach postów żądania.
Kiedy patrzę na POST w Firebug , w zapytaniu są wysyłane dane JSON.
12 answers
Jeśli publikujesz JSON do Django, myślę, że chcesz request.body
(request.raw_post_data
na Django
Oto przykład użycia JavaScript, jQuery , jquery-json i Django.
JavaScript:
var myEvent = {id: calEvent.id, start: calEvent.start, end: calEvent.end,
allDay: calEvent.allDay };
$.ajax({
url: '/event/save-json/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: $.toJSON(myEvent),
dataType: 'text',
success: function(result) {
alert(result.Result);
}
});
Django:
def save_events_json(request):
if request.is_ajax():
if request.method == 'POST':
print 'Raw Data: "%s"' % request.body
return HttpResponse("OK")
Django
def save_events_json(request):
if request.is_ajax():
if request.method == 'POST':
print 'Raw Data: "%s"' % request.raw_post_data
return HttpResponse("OK")
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-07-14 15:58:35
Miałem ten sam problem. Wysłałem złożoną odpowiedź JSON i nie mogłem odczytać moich danych za pomocą żądania.Słownik pocztowy.
Moje dane postu JSON to:
//JavaScript code:
//Requires json2.js and jQuery.
var response = {data:[{"a":1, "b":2},{"a":2, "b":2}]}
json_response = JSON.stringify(response); // proper serialization method, read
// http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
$.post('url',json_response);
W tym przypadku należy użyć metody dostarczonej przez aurealus. Przeczytaj prośbę.body i deserialize go z JSON stdlib.
#Django code:
import json
def save_data(request):
if request.method == 'POST':
json_data = json.loads(request.body) # request.raw_post_data w/ Django < 1.4
try:
data = json_data['data']
except KeyError:
HttpResponseServerError("Malformed data!")
HttpResponse("Got json 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
2016-05-10 23:12:38
Metoda 1
Klient: Wyślij jako JSON
$.ajax({
url: 'example.com/ajax/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
processData: false,
data: JSON.stringify({'name':'John', 'age': 42}),
...
});
//Sent as a JSON object {'name':'John', 'age': 42}
Serwer:
data = json.loads(request.body) # {'name':'John', 'age': 42}
Metoda 2
Klient: Wyślij jako x-www-form-urlencoded
(Uwaga: contentType
& processData
zostały zmienione, JSON.stringify
nie jest potrzebne)
$.ajax({
url: 'example.com/ajax/',
type: 'POST',
data: {'name':'John', 'age': 42},
contentType: 'application/x-www-form-urlencoded; charset=utf-8', //Default
processData: true,
});
//Sent as a query string name=John&age=42
Serwer:
data = request.POST # will be <QueryDict: {u'name':u'John', u'age': 42}>
Zmieniony w 1.5+: https://docs.djangoproject.com/en/dev/releases/1.5/#non-form-data-in-http-requests
Dane inne niż formularze w żądaniach HTTP :
Prośba.Post will no dłużej zawierać dane wysyłane za pośrednictwem żądań HTTP z typy treści w nagłówku, które nie są specyficzne dla form. W poprzednich wersjach dane posted with content-types other than multipart/form-data or application / x-www-form-urlencoded nadal będzie reprezentowany w Prośba.Atrybut POST. Deweloperzy chcący uzyskać dostęp do surowego posta dane w tych przypadkach, należy użyć żądania.zamiast tego atrybut body.
Prawdopodobnie związane
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-03-13 05:05:15
Ważne jest, aby pamiętać, że Python 3 ma inny sposób reprezentacji łańcuchów-są to tablice bajtowe.
Używając Django 1.9 i Pythona 2.7 i wysyłając dane JSON w głównej części (nie nagłówka), użyjesz czegoś takiego jak:
mydata = json.loads(request.body)
Ale dla Django 1.9 i Pythona 3.4 użyłbyś:
mydata = json.loads(request.body.decode("utf-8"))
Właśnie przeszedłem przez tę krzywą uczenia się, tworząc moją pierwszą aplikację PY3 Django!
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-12-28 14:11:44
request.raw_response
jest obecnie przestarzały. Zamiast tego użyj request.body
do przetwarzania niekonwencjonalnych danych formularzy, takich jak ładunki XML, obrazy binarne itp.
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-06-22 23:40:28
On django 1.6 python 3.3
Klient
$.ajax({
url: '/urll/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(json_object),
dataType: 'json',
success: function(result) {
alert(result.Result);
}
});
Serwer
def urll(request):
if request.is_ajax():
if request.method == 'POST':
print ('Raw Data:', request.body)
print ('type(request.body):', type(request.body)) # this type is bytes
print(json.loads(request.body.decode("utf-8")))
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-07-24 17:06:46
Ładunek HTTP POST to tylko płaska kupa bajtów. Django (jak większość frameworków) dekoduje je do słownika z parametrów zakodowanych URL lub kodowania MIME-multipart. Jeśli wrzucisz dane JSON do zawartości posta, Django nie zdekoduje ich. Albo dekoduje JSON z pełnej zawartości posta (nie ze słownika); albo umieszcza dane JSON w opakowaniu typu MIME-multipart.
W skrócie, Pokaż kod JavaScript. Wydaje się, że problem tam jest.
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-06-22 23:37:33
request.raw_post_data
został zdeprecjonowany. Użyj request.body
zamiast
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
2013-11-21 13:28:39
Coś w tym stylu. Udało się.: Żądanie danych od klienta
registerData = {
{% for field in userFields%}
{{ field.name }}: {{ field.name }},
{% endfor %}
}
var request = $.ajax({
url: "{% url 'MainApp:rq-create-account-json' %}",
method: "POST",
async: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(registerData),
dataType: "json"
});
request.done(function (msg) {
[alert(msg);]
alert(msg.name);
});
request.fail(function (jqXHR, status) {
alert(status);
});
Żądanie przetwarzania na serwerze
@csrf_exempt
def rq_create_account_json(request):
if request.is_ajax():
if request.method == 'POST':
json_data = json.loads(request.body)
print(json_data)
return JsonResponse(json_data)
return HttpResponse("Error")
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-09-24 14:52:55
html code
file name : 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>
<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>
Django code:
Inside views.py
def view(request):
if request.method == 'POST':
print request.body
data = request.body
return HttpResponse(json.dumps(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-12-22 09:07:32
Używając Angular powinieneś dodać nagłówek do żądania lub dodać go do konfiguracji modułu
Nagłówki: {'Content-Type': 'application/x-www-form-urlencoded'}
$http({
url: url,
method: method,
timeout: timeout,
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
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-03-26 08:52:41
Prośba.POST jest tylko obiektem podobnym do słownika, więc po prostu indeksuj do niego za pomocą składni dict.
Zakładając, że Twoje pole formularza to fred, możesz zrobić coś takiego:
if 'fred' in request.POST:
mydata = request.POST['fred']
Alternatywnie, użyj obiektu formularza do obsługi danych POST.
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
2009-07-30 17:31:31