zzbil
zzbil

Reputation: 357

Django - display Json or Httpresponse in template

I have something this in views.py:

return JsonResponse({'foo': 'bar'})

How would i display "bar" in the template? Something like:

   <h1 id="demo"></h1>
    <script>
    document.getElementById("demo").innerHTML = ?JsonResponse?;
    </script>

or could it be done with http response?

 return HttpResponse("Bar")

and html:

<h1 id="demo"></h1>
    <script>
    document.getElementById("demo").innerHTML = ?HttpResponse?;
    </script>

Upvotes: 3

Views: 6139

Answers (1)

Alex
Alex

Reputation: 1262

Ok. Let's assume you have a url /yourURL connected to a view function. Let's call this function index:

from django.shortcuts import render
def index(request):
    data = {foo:'bar'}
    render(request,'path/to/yourTemplate.html',data)

I use render as a shortcut. In yourTemplate.html, you can access the data as {{foo}} anywhere. For sending json objects to the template without rendering, consider the following template (yourTemplate.html):

<div id='initialData'>{{foo}}</div>
<div id='jsondata'></div>

You need a new view and an ajax request to grab information from it. You can do this in the same index view, or you can build a brand new url and associated view. Let's use the second option. It goes like this, you build a new URL /yourURL/download connected to a download view (views.py):

def download(request):
   data = {foo2:'bar2'}
   JsonResponse(data)

Then you need an ajax request to call this view and write the response on the div on success (yourTemplate.html):

<script>
$.ajax({
    url: "/yourURL/download",
    type: 'get',
    success: function (data) {
      alert("Success");
      var div = document.getElementById('jsondata');
      div.innerHTML = div.innerHTML + data.foo;       

    }
  });
 </script>

Voila! You will have both bar and bar2 in your screen. To elaborate further you need a button associated with the ajax call, so you can see that the page actually does not render again with the JsonResponse.

Upvotes: 2

Related Questions