Search code examples
javascriptjquerypythondjangorender-to-string

Python3 + Django : How to use Jquery in render_to_string template?


My sauce is below.

Elements in the template created using render_to_string are not Jquery controls.

▶ index.html

{% extends 'common/base.html' %}
{% block contents %}
<section>
    <div class="main-goods-area">
        <div class="container" id="prod_list">
        </div>
    </div>
</section>
{% endblock %}

{% block jquery %}
    <script src="{% static 'js/index.js' %}"></script>
{% endblock %}

▶ index.js

$(function() {
    show_inf_list('0','0','0','0','0');
    function show_inf_list(section, selection, ordering, start, limit){
        $.ajax({
            url:'/campaign/list/',
            data:{
                'campaign_section': section,
                'selection_type': selection,
                'ordering_type': ordering,
                'start': start,
                'limit': limit
            },
            dataType:'json',
            success: function (data) {
                $('#prod_list').html(data.campaign_list);
            }
        });
    }

    $('a[name=btn_like]').on('click', function (e) {
        e.preventDefault()
        console.log('a');
        return false;
    });
});

▶ views.py

def ...
    data['campaign_list'] = render_to_string(
        'main/include/prod_list.html',
        context=context,
        request=request
    )
    return JsonResponse(data)

▶ prod_list.html

<div class="ic-area">
    <ul>
        <li>
            <a href="" name="btn_like" data-id="{{ campaign.id }}">
                {% if user.influencer in campaign.like_users.all %}
                    <i class="ic_heart_small active"></i>
                {% else %}
                    <i class="ic_heart_small"></i>
                {% endif %}
            </a>
        </li>
    </ul>
</div>

I want control 'btn_like' element

But, I can't control the 'a[name=btn_like]'

How to use Jquery Control in element of render_to_string template?


Solution

  • The issue is that you have set the handler on 'a[name=btn_like]' but it is assigned on DOM ready; so new elements loaded via Ajax won't be linked to the handler. Instead, assign the handler to a higher element and use delegation.

    $('#prod_list').on('click', 'a[name=btn_like]', function(data) ...