[Answer]-Django templates: optimizing the update of a template

1👍

Use jquery and ajax to update just the specific part of your template, suppose:

<div>
    <span id="data_1"> Display results of complex_calculation_1 + </span>
    <button class="data_btn" span_id="data_1">Update</button>
<\div>

<script>
 $('.data_btn').click(function(){
    // send post data which you need in `data` variable
    $.ajax({
        type: 'POST',
        url: '{% url 'url_name_for_your_view_here' %}',
        data: {'csrfmiddlewaretoken': '{{csrf_token}}'},
        dataType: "text",
        success: function(response) {
            $($(this).attr('span_id')).text(response.data);
            //where response.data is the data which you want to display
        },
        error: function(rs, e) {
            alert(rs.responseText);
            alert('Oops! something went worng..');
         }
     });
  });
</script>

0👍

If you can assume, that site visitor has JavaScript enabled, you could use ajax,
to send your data, perform calculations in separate view and post it back to your site – that way the whole page won’t be reloaded, and it will look very elegant.

Of course, any visitor should be able to use your site even if his browser doesn’t support JavaScript, but then, if it’s only minority of visitors, then I wouldn’t bother optimizing it for these rare cases, just leaving it as it is.

I’m not sure about caching mechanisms in Django, so I won’t propose anything if you really can’t rely on Ajax.

Leave a comment