Python – DJANGO : Update div with AJAX

ajaxdjangodjango-templatesjquerypython

I am building a chat application. So far I am adding chat messages with jquery $.post() and this works fine.

Now I need to retrieve the latest chat message from the table and append the list on the chat page.
I am new to Django, so please go slow.

So how do I get data from the chat table back to the chat page?

Thanks in advance!

Best Answer

My favorite technique for this kind of thing is to use an inclusion tag

basically you make a separate template for rendering the individual objects in the page template

page template:

{% load message_tags %}    

<h3>Messages</h3>
<div class="message_list">
    {% for message in messages %}
        {% render_message message %}
    {% endfor %}
</div>

templatetags/message_tags.py:

from django import template

register = template.Library()

@register.inclusion_tag('individual_message.html')
def render_message(message):
    context_for_rendering_inclusion_tag = {'message': message}
    return context_for_rendering_inclusion_tag

now you can use the same template to render the the additional messages you want to add to the message_list div in a separate view which you can call from your ajax code

def ajax_retrieve_latest_message(request):
    # ... Get the lastest message
    render_to_response('individual_message.html', ... 

And your jQuery will look something like...

$.post(url_of_ajax_view, request_data, function(data, status) {
    if (status == 'success') {
        $(".message_list").append(data);
    }
});

For completeness, your individual_message.html file would contain all the markup for displaying the actual message on the page...

Hope this all helps :)