Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh <div> element generated by a django template

How do I refresh a certain element within a django template?
Example:

{% if object.some_m2m_field.all %}
    <h3>The stuff I want to refresh is below</h3>
    <div id="the-div-that-should-be-refreshed">
    {% for other_object in object.some_m2m_field.all %}
        <a href="www.example.com">{{ other_object.title }}</a>
        &nbsp;
    {% endfor %}
    </div>
{% endif %}

Lets say some other element in the page triggers a javascript that should refresh the div above. Is there a way to cause django to refresh this specific element within the template?

If not, I'll have to monkey-patch the div using regular JS or jQuery methods and not use the great power of django's template layer. Also, the above code is a simplification of the actual template, I use much of the template's power, so monkey-patching the resulting html will be a nightmare...

like image 868
Jonathan Livni Avatar asked Aug 27 '10 11:08

Jonathan Livni


2 Answers

You could use an async request to fill the div element. The async request is answered by Django using the template engine.

In this case, you would have to outsource the template code of the div element into a separate template file.

UPDATED WITH EXAMPLE:

Javascript:
For refreshing the view asynchronously, use JQuery for example:

$.ajax({
  url: '{% url myview %}',
  success: function(data) {
  $('#the-div-that-should-be-refreshed').html(data);
  }
});

Async View:

def myview(request):
    object = ...
    return render_to_response('my_template.html', { 'object': object })

Template:

{% for other_object in object.some_m2m_field.all %}
    <a href="www.example.com">{{ other_object.title }}</a>
    &nbsp;
{% endfor %}
like image 57
o.elias Avatar answered Oct 09 '22 16:10

o.elias


You can have a look at eg. this Ajax with Django tutorial. Anyways as mentioned above you can always use django's template engine, no matter if the view is called in a normal or an ajax request! If you have to use ajax with django more frequently it makes sense to have a look at something like dajax, which is an ajax library for django (have a look at the tutorials there).

like image 27
Bernhard Vallant Avatar answered Oct 09 '22 16:10

Bernhard Vallant