【问题标题】:Django JsonResponse with context带有上下文的 Django JsonResponse
【发布时间】:2020-04-18 20:10:34
【问题描述】:

我可以使用函数 JsonResponse 并返回带有 dict 上下文的 .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>

views.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 加载这个站点,他就找不到上下文并显示错误函数。

【问题讨论】:

    标签: json django ajax


    【解决方案1】:

    JsonResponse 不将上下文作为参数。

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

    第一个参数 data 应该是一个 dict 实例。如果安全参数设置为 False(见下文),它可以是任何 JSON 可序列化对象。

    >>> 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)
    

    【讨论】:

    • 我在思考和思考,但我不知道如何在我的代码中包含 :( 我需要添加 response = JsonResponse({'Messags: Messages}) ?
    • @MateuszBiałas 我编辑了答案以包含更具体的示例:)
    • 不幸的是,我已经尝试过了 :( Ajax 返回错误函数。
    • 您可能还需要将消息作为字典获取,使用值:docs.djangoproject.com/en/3.0/ref/models/querysets/#valuesNewsMessage.objects.all().order_by('-Data').values()
    • 对不起,我很忙。使用 values() 我已经尝试过。也许我会在 py 中创建函数,该函数将创建代码 html 并在 dict 中作为字符串发送。我没有任何其他想法。
    猜你喜欢
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 2018-07-27
    • 2015-08-20
    • 2017-02-25
    • 2019-12-05
    • 2011-04-21
    相关资源
    最近更新 更多