Django.fun

How to change table data with Django and Ajax

I have a pandas dataframe that I am displaying in a Django Template as follows

views.py

def display(request):
    if request.method == 'POST':

        temp_df_path = './temp_match.csv'
        option = 'all'
        animals_data = helper(temp_df_path, options=option)
        
        json_records = animals_data.reset_index().to_json(orient='records') 

        data = []
        data = json.loads(json_records)
        
        context = {'d': data, 'data_columns': animals_data.columns}

        return render(request, 'results.html', context=context)

Here I am displaying a DataFrame filtered using the helper function. In the template I have a set of radio buttons with which I can change the option variable. Here is my template

<div class="container center">
    <div class="table_options action_panel_centered">
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio3" value="option3"
                checked>
            <label class="form-check-label" for="inlineRadio3">Show all animals</label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" value="option1">
            <label class="form-check-label" for="inlineRadio1">Show only carnivores</label>
        </div>
        <div class="form-check form-check-inline">
            <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="option2">
            <label class="form-check-label" for="inlineRadio2">Show only herbivores</label>
        </div>
    </div>
</div>

<div class="container-fluid root center">
    <div class="table_container">
        <table class="table table-hover" id='results_table'>
            <tr>
                <th class="index_th">#</th>
                {% for col in data_columns %}
                <th>{{col}}</th>
                {% endfor %}
                <th class='action_cell'>Actions</th>
            </tr>
            {% if d %}
            {% for i in d %}
            <tr>
                <th scope="row">
                    {{forloop.counter}}
                </th>
                ...
        </table>
    </div>
</div>

I want to change the content using Ajax. How do I do that? I have an Ajax function as follows

function change_content(event) {
    $.post(
         url : {% url 'display' %},
         success: function(data, status, xhr){
            //do something with your data
        }
    );
    return false;
}

$(function () {
    $('.form-check-input').click(change_content);
});

Answers: 0