1
votes

I want to generate django boolean form(checkbox) by for loop(of django Templates) and call it(to views) to delete checked data. I writed some codes: (but it don't work at if request.POST['id_checkbox{}'.format(b.id)]: in views)

my codes:

Template

<form role="form" method="post">
    {% csrf_token %}
    {% render_field form.action %}
  <button type="submit" class="btn btn-default">Submit</button>
<table class="table table-striped text-right nimargin">
    <tr>
      <th class="text-right"> </th>
      <th class="text-right">row</th>
      <th class="text-right">title</th>
      <th class="text-right">publication_date</th>
    </tr>
    {% for b in obj %}
    <tr>
      <td><input type="checkbox" name="id_checkbox_{{ b.id }}"></td>
      <td>{{ b.id }}</td>
      <td>{{ b.title }}</td>
      <td>{{ b.publication_date }}</td>
    </tr>
    {% endfor %}
</table>
</form>

Views

class book_showForm(forms.Form):
    action = forms.ChoiceField(label='go:', choices=(('1', '----'), ('2', 'delete'), ))
    selection = forms.BooleanField(required=False, )


def libra_book(request):
    if request.method == 'POST':
        sbform = book_showForm(request.POST)
        if sbform.is_valid():
            for b in Book.objects.all():
                if request.POST['id_checkbox_{}'.format(b.id)]:
                    Book.objects.filter(id=b.id).delete()
                    return HttpResponseRedirect('/libra/book/')

    else:
        sbform = book_showForm()
    return render(request, 'libra_book.html', {'obj': Book.objects.all(), 'form': sbform})

Model

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.CharField(max_length=20)
    publication_date = models.DateField()

how can i use request.POST to understand that what is value of the checkbox(True or False)?

2

2 Answers

0
votes

try to change your checkbox to this

<input type="checkbox" name="checks[]" value="{{ b.id }}">

then on your view,something like this

list_of_checks = request.POST.getlist('checks')     # output should be list
for check_book_id in list_of_checks:                # loop it
   b = Book.objects.get(id=check_book_id)           # get the object then 
   b.delete()     # delete it
0
votes

I find the answer that i must use request.POST.get('id_checkbox_{}'.format(b.id), default=False) Instead of request.POST['id_checkbox_{}'.format(b.id)]

because request.POST['id_checkbox_{}'.format(b.id)] [or request.POST.__getitem__('id_checkbox_{}'.format(b.id))] Raises django.utils.datastructures.MultiValueDictKeyError if the key does not exist. and must set defout request.POST.get('id_checkbox_{}'.format(b.id), default=False)

see HttpRequest.POST here

and see QueryDict.get(key, default=None) and QueryDict.__getitem__(key) QueryDict.get(key, default=None)