2016-12-14 42 views
0

我想通过for(django模板)for循环生成django布尔表单(复选框),并将其调用(视图)以删除选中的数据。 我所著的一些代码: (但它不会在if request.POST['id_checkbox{}'.format(b.id)]:在视图中工作)在Django模板中生成和调用布尔字段形式

我的代码:

模板

<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来了解的复选框(True或False)的值是什么?

回答

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.MultiValueDi如果密钥不存在,则ctKeyError。 必须设置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)

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

这是行不通的。 – amirhoseinnnn

+0

什么部分不工作?我可以看到消息吗?谢谢 –