Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
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>
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!