表題の件の通りなのですが、jangoで思ったようにjsonファイルを表示できません。
問題となっているのは下記3件です。
1)「Object of type 'QuerySet' is not JSON serializable」が発生しているのですが、直し方が正しいかどうか。
2)画面が遷移してしまう。
3)取得したデータのタイトルをループさせて表示させたい。
test.html
{% extends 'mutual/base.html' %} {% block content %} <h2>TEST PAGE</h2> <div id="posts"> {% for property in propertys %} <p>{{property.title}}</p> {% endfor %} </div> <form id="test" action="{% url 'mutual:ajax_post_select' %}" method="POST"> <button type="submit">activate</button> {% csrf_token %} </form> {% endblock %}
sample.js
function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $('#test').on('submit', e => { e.preventDefault(); $.ajax({ 'url': '{% url "mutual:ajax_post_select" %}', 'type': 'POST', 'dataType': 'json' }).done( response => { const p = $('<p>', {text: response.property}); $('#posts').prepend(p); $('#test').val(''); }); });
views
def ajax_post_select(request): logging.debug('aaaaaa') propertys = Property.objects.all().order_by('-create_date') context={ 'propertys': propertys, } return JsonResponse(context)
まず上記の状態でtest.htmlからボタンを押すと下記のようなエラーページが出ます。
Django Version: 2.2.4 Exception Type: TypeError Exception Value: Object of type 'QuerySet' is not JSON serializable Exception Location: /lib64/python3.6/json/encoder.py in default, line 180
loggingを確認すると「aaaaaa」がメッセージにあるので、ajax_post_selectは一応呼ばれているようです。
「serializable」のエラーを消すために今度はviewsのORMの部分を下記の通りに変更いたします。
propertys = serializers.serialize('json', Property.objects.all().order_by('-create_date'), fields=('id',))
上記のように変更するとブラウザに下記のようなデータが表示されます。
{"propertys": "[{\"model\": \"mutual.property\", \"pk\": 13, \"fields\": {}}, {\"model\": \"mutual.property\", \"pk\": 12, \"fields\": {}}, {\"model\": \"mutual.property\", \"pk\": 8, \"fields\": {}}]"}
ここで改めて質問させていただきたい部分なのですが、
1)
「serializers.serialize」を使用してjasonファイルにするのは正しいのでしょうか?
日本語のサイトではこれを使っているのが見つかりませんでした。
下記の記述でページ遷移をキャンセルしているような記事を見つけたのですが、ページが切り替わっているので
どこか間違えがあるのでしょうか?
e.preventDefault();
とりあえず取得したpropertyのカラム名titleを回して表示したいのですが、下記のような出力になってしまっています。
{"propertys": "[{\"model\": \"mutual.property\", \"pk\": 13, \"fields\": {}}, {\"model\": \"mutual.property\", \"pk\": 12, \"fields\": {}}, {\"model\": \"mutual.property\", \"pk\": 8, \"fields\": {}}]"}
質問が多くて申し訳ございませんがどこを直していけばよいのでしょうか。
ご回答いただければ幸いです。
以上よろしくお願いいたします。
※参考にしたサイトは下記のサイトです。
■https://narito.ninja/blog/detail/88/
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。