[英]Django JsonResponse with context
我可以在字典上下文中使用 function JsonResponse 和 return.json 文件嗎? 我只有一個。html 如果我點擊href ajax 將得到.json 文件並切換div。
html:
<form id='FormSite' method="POST">
{% csrf_token %}
<div id='Bilboard'>
<div id='Pic'>
<video id='VideoStart' style="width: 100%; height: 100%;" autoplay preload="true" loop >
<source src="static/video/mainVideo.mp4"poster="static/img/facebook.png" type='video/mp4'>
Your browser does not support the video tag.
</video>
</div>
<div id='Wpis'>
<h1 id='HeaderWpis'>Aktualności:</h1>
<div id='WpisChild'>
{% for News in Messags %}
<div id='NewsPapper'>
<p style="font-size: 200% !important;">{{ News.title }}</p>
<img src="static/img/line.png" style="width: 5%; height: 5%; position: relative !important; left: 50%; transform: translateX(-50%);">
<p style="font-size: 150% !important;">{{ News.text |linebreaksbr }}</p>
<img src="static/img/line.png" style="width: 5%; height: 5%; position: relative !important; left: 50%; transform: translateX(-50%);">
<p style="font-size: 150% !important;">{{ News.Data }}</p>
</div>
{% endfor %}
</div>
</div>
</div>
</form>
視圖.py
def FirstStart(request):
if request.method == 'POST':
respone = {}
UrlCut = request.GET.get('site','')
if(len(UrlCut) > 0):
File_read_to_div = open('templemates/'+UrlCut+'.txt','r')
else:
File_read_to_div = open('templemates/Main.txt','r')
respone['Pic'] = str(File_read_to_div.readline())
respone['h1'] = str(File_read_to_div.readline())
respone['WpisChild'] = str(File_read_to_div.readline())
#r
Messages = NewsMessage.objects.all().order_by('-Data')
context = {
"Messags" : Messages
}
return JsonResponse(respone, context)
Messages = NewsMessage.objects.all().order_by('-Data')
context = {
"Messags" : Messages
}
return render(request, 'main.html', context)
ajax
$.ajax({
url: url,
data: $('#FormSite').serialize(),
type: "POST",
async:false,
success: function(response) {
$($("#Pic").first()).replaceWith($(response['Pic']));
$("#HeaderWpis").text(response['h1'])
$($("#WpisChild").first()).replaceWith($(response['WpisChild']))
},
error: function()
{
alert('Bad connection');
}
});
所以,如果我首先加載 main.html {{ News.title }} 等工作。 但是如果 ajax/django 從.txt 加載這個站點,他找不到上下文並顯示錯誤 function。
JsonResponse 不將上下文作為參數。
https://docs.djangoproject.com/en/3.0/ref/request-response/#jsonresponse-objects
第一個參數 data 應該是一個 dict 實例。 如果安全參數設置為 False(見下文),它可以是任何 JSON 可序列化 object。
>>> from django.http import JsonResponse
>>> response = JsonResponse({'foo': 'bar'})
>>> response.content
b'{"foo": "bar"}'
在您的情況下,您應該能夠將消息添加到您的字典中:
respone['messages'] = NewsMessage.objects.all().order_by('-Data')
return JsonResponse(respone)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.