How to get the value of selected checkboxes from HTML into my Django Views?

Viewed 30

Working for the first time on HTML and Djnago. I wrote a custom HTML

excluded_leagues.html

<h1>Excluded Leagues</h1>
<div class="excluded_leagues">
    <form action="/superprofile/save_excluded_leagues/" method="POST">{% csrf_token %}
    <table id="excluded_leagues_list">
        <thread>
            <tr>
                <th scope="col">
                    <div class="text">
                        <span>Excluded</span>
                    </div>
                </th>
                <th scope="col">
                    <div class="text">
                        <span>League ID</span>
                    </div>
                </th>
                <th scope="col">
                    <div class="text">
                        <span>League Name</span>
                    </div>
                </th>
                <th scope="col">
                    <div class="text">
                        <span>Sport</span>
                    </div>
                </th>
            </tr>
        </thread>
        <tbody>
        {% for league in object_list %}
             {% if league.status == 'Active' %}
            <tr>
                <td><input type="checkbox" value="{{ league.id }}" name="selected_league"></td>
                <td>{{ league.id }}</td>
                <td>{{ league.name }}</td>
                <td>{{ league.sport }}</td>
            </tr>
            {% else %}
            {% endif %}
        {% endfor %}
        </tbody>
    </table>
    <div>
      <button type="submit" name="apply">Save changes</button>
    </div>
</div>
<ul>

I am trying to grab the league.id of all the selected checkboxes and use them in my views

views.py

def save_excluded_leagues(request):
    if 'apply' in request.POST:
        league_id_selected = request.POST.getlist('selected_league')
        info_log.info(f"{league_id_selected }  xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 1")
    return HttpResponse("Hello")

I need to grab the values league.id of all the selected checkboxes, but I am unable to grab the value in my views.py file. Right now it is not returning anything for the value request.POST.getlist('selected_league')

1 Answers

This is solved. I wrapped the checkbox part in

                <td>
                    <div>
                        <input type="checkbox" value="{{ league.id }}" name="selected_league" {% if user_profile.is_free_money %} checked{% endif %}>
                    </div>
                </td>
                <td>{{ league.id }}</td>
                <td>{{ league.name }}</td>
                <td>{{ league.sport }}</td>
Related