【问题标题】:generate and calling boolean field forms in django template在 django 模板中生成和调用布尔字段表单
【发布时间】:2017-04-30 08:01:57
【问题描述】:

我想通过 for 循环(django 模板)生成 django 布尔表单(复选框)并调用它(到视图)以删除检查的数据。 我写了一些代码: (但它不适用于视图中的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 来了解复选框的值(真或假)是什么?

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

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

    <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
    

    【讨论】:

    • 哪个部分不工作?我可以看到消息吗?谢谢
    【解决方案2】:

    我发现我必须使用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。 并且必须设置默认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)

    【讨论】:

      猜你喜欢
      • 2018-11-20
      • 1970-01-01
      • 2022-08-14
      • 2015-06-13
      • 1970-01-01
      • 2013-07-17
      • 2011-06-06
      • 2018-07-05
      • 1970-01-01
      相关资源
      最近更新 更多