简体   繁体   中英

Django JsonResponse with context

Can I use function JsonResponse and return.json file with dict context? I have only one.html and if I click in href ajax will get.json file and switch div's.

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

});

So, if I first load main.html {{ News.title }} etc. work. But If ajax/django load this site from.txt he can't find context and display error function.

JsonResponse doesn't take context as a parameter.

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

The first parameter, data, should be a dict instance. If the safe parameter is set to False (see below) it can be any JSON-serializable 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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