在django模板中生成并调用布尔字段表单

时间:2016-12-14 20:51:58

标签: django django-forms

我想通过for循环(django模板)生成django boolean form(复选框)并调用它(到视图)来删除已检查的数据。 我写了一些代码: (但它不能在if request.POST['id_checkbox{}'.format(b.id)]:视图中工作)

我的代码:

模板

<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>

浏览

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})

模型

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

如何使用request.POST了解复选框的(真或假)?

2 个答案:

答案 0 :(得分:0)

尝试将您的复选框更改为此

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

然后在你的观点上,像这样

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

答案 1 :(得分:0)

我找到了必须使用的答案request.POST.get('id_checkbox_{}'.format(b.id), default=False)而不是request.POST['id_checkbox_{}'.format(b.id)]

因为request.POST['id_checkbox_{}'.format(b.id)] [或request.POST.__getitem__('id_checkbox_{}'.format(b.id))]如果密钥不存在则引发 django.utils.datastructures.MultiValueDictKeyError 。 并且必须设置defout request.POST.get('id_checkbox_{}'.format(b.id), default=False)

请参阅HttpRequest.POST此处

并查看QueryDict.get(key, default=None)QueryDict.__getitem__(key) QueryDict.get(key, default=None)