简体   繁体   中英

.getlist() is not returning anything in django / html form checkbox input

I have a 2 forms within my list view for a model. The first one is a search bar which works fine with GET and the next is to select items displayed and collect them to edit. I haven't gotten to the editing because I cannot get a list of the selected objects.

View.py

@login_required

def ex_list(request):
    context = {}
    if request.GET:
        #code for search bar
        if request.POST:
            selected_values = request.POST.getlist('exlist[]')
            print(selected_values)
        return render(
            request,
            'ex/list.html',
            context
        )

List.html

<form method="POST" action="">
    {% csrf_token %}
    <table id="exs" class="table table-hover table-striped">
       <tbody>
         {% for ex in exs %}
          <tr>
          <td>
            <center><input type="checkbox" name="exlist[]" value="{{ex.esid}}"/></center>
          </td>
          {% endfor %}
          <input type="submit" class="btn btn-primary" value="Edit Selected Items" name="edit">
         </form>

Although I have print(selected_values), all that is being returned is empty brackets {}. I at least know that we are getting inside of the if statement.

Firstly, in your list.html you haven't specified action and just left it blank change it to

<form method = "post" action = "{% url 'ex_list' %}">
...
</form>

Also, you are passing empty context to the rendering template that's why you are getting {} change it to

context = {
    "selected_values" = selected_values,
}
return render(request, "...", context)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM