Refresh
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...

14
задан Jonathan 27 August 2010 в 11:06
поделиться

2 ответа

Вы можете использовать асинхронный запрос для заполнения элемента div. На асинхронный запрос отвечает django, используя механизм шаблонов.

В этом случае вам придется передать код шаблона элемента div в отдельный файл шаблона.

ОБНОВЛЕНО ПРИМЕРОМ:

Javascript:
Для асинхронного обновления представления используйте, например, JQuery:

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

Асинхронное представление:

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

Шаблон:

{% for other_object in object.some_m2m_field.all %}
    <a href="www.example.com">{{ other_object.title }}</a>
    &nbsp;
{% endfor %}

С уважением!

29
ответ дан 1 December 2019 в 08:51
поделиться

Вы можете посмотрите напр. этот учебник по Ajax с Django. В любом случае, как упоминалось выше, вы всегда можете использовать механизм шаблонов django, независимо от того, вызывается ли представление в обычном или ajax-запросе! Если вам нужно чаще использовать ajax с django, имеет смысл взглянуть на что-то вроде dajax, которая является библиотекой ajax для django (посмотрите там учебники).

2
ответ дан 1 December 2019 в 08:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: