2016-12-14 41 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

什麼部分不工作?我可以看到消息嗎?謝謝 –