Note that there are some explanatory texts on larger screens.

plurals
  1. PORendering JSON objects using a Django template after an Ajax call
    text
    copied!<p>I've been trying to understand what's the optimal way to do <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> in <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="noreferrer">Django</a>. By reading stuff here and there I gathered that the common process is: </p> <ol> <li><p>formulate your Ajax call using some <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> library (e.g., <a href="http://en.wikipedia.org/wiki/JQuery" rel="noreferrer">jQuery</a>), set up a URL pattern in Django that catches the call and passes it to a view function</p></li> <li><p>in the <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="noreferrer">Python</a> view function retrieve the objects you are interested in and send them back to the client in JSON format or similar (by using the built in serializer module, or <a href="http://code.google.com/p/simplejson/" rel="noreferrer">simplejson</a>)</p></li> <li><p>define a callback function in JavaScript that receives the JSON data and parses them, so to create whatever HTML is needed to be displayed. Finally, the JavaScript script puts the HTML wherever it should stay.</p></li> </ol> <p>Now, what I still don't get is <em>how are Django templates related to all of this?</em> Apparently, we're not making use of the power of templates at all. Ideally, I thought it'd be nice to pass back a JSON object and a template name, so that the data could be iterated over and an HTML block is created. But maybe I'm totally wrong here...</p> <p>The only resource I found that goes in this direction is <a href="http://www.djangosnippets.org/snippets/769/" rel="noreferrer">this snippet (769)</a> but I haven't tried it yet. Obviously, what's going to happen in this case is that all the resulting HTML is created on the server side, then passed to the client. The JavaScript-callback function only has to display it in the right place.</p> <p>Does this cause performance problems? If not, even without using the snippet above, why not formatting the HTML directly in the backend using Python instead of the front-end?</p> <p>Many thanks! </p> <p><strong>UPDATE: please use <a href="http://www.djangosnippets.org/snippets/942/" rel="noreferrer">snippet 942</a> because it is an enhanced version of the one above!</strong> I found that the inheritance support works much better this way..</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload