简体   繁体   English

Django JsonResponse with context

[英]Django JsonResponse with context

Can I use function JsonResponse and return.json file with dict context?我可以在字典上下文中使用 function JsonResponse 和 return.json 文件吗? I have only one.html and if I click in href ajax will get.json file and switch div's.我只有一个。html 如果我点击href ajax 将得到.json 文件并切换div。

html: 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>

views.py视图.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

 $.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');
    }

});

So, if I first load main.html {{ News.title }} etc. work.所以,如果我首先加载 main.html {{ News.title }} 等工作。 But If ajax/django load this site from.txt he can't find context and display error function.但是如果 ajax/django 从.txt 加载这个站点,他找不到上下文并显示错误 function。

JsonResponse doesn't take context as a parameter. JsonResponse 不将上下文作为参数。

https://docs.djangoproject.com/en/3.0/ref/request-response/#jsonresponse-objects https://docs.djangoproject.com/en/3.0/ref/request-response/#jsonresponse-objects

The first parameter, data, should be a dict instance.第一个参数 data 应该是一个 dict 实例。 If the safe parameter is set to False (see below) it can be any JSON-serializable object.如果安全参数设置为 False(见下文),它可以是任何 JSON 可序列化 object。

>>> from django.http import JsonResponse
>>> response = JsonResponse({'foo': 'bar'})
>>> response.content
b'{"foo": "bar"}'

In your case, you should be able to add messages to your dictionary:在您的情况下,您应该能够将消息添加到您的字典中:

respone['messages'] = NewsMessage.objects.all().order_by('-Data')

return JsonResponse(respone)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM