Cannot display value on web page by using Django - django

I want to display some values which is queried out from mysql in the method within views.py on the web page, but I cannot see that on the web page. see my method in views.py:
def update_delete_customer(request, id):
if request.method == 'POST':
print("TODO")
else:
form = CustomerForm()
if id is None:
print("id is None")
return HttpResponseRedirect('AddressTableMaintain/')
print("----------------")
print(id)
customerList = Customer.objects.raw("select * from customers where customer_id = %s", [int(id)])
customer = list(customerList)[0]
print(customer)
form.customerId = customer.customerId
form.first_name = customer.first_name
form.last_name = customer.last_name
print(customer.customerId)
print(customer.first_name)
print(customer.last_name)
return render(request, 'EditCustomer.html', {'form': form})
return HttpResponseRedirect('AddressTableMaintain/')
I can see the output customer id, first name, last name that are generated by the print function in the console.
Below is the contents of my EditCustomer.html:
{% extends 'base.html' %}
{% block title %} Remove or Update customer {% endblock %}
{% block content %}
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
<form action="{% url 'RU_customer_post' %}" method="post">
{% csrf_token %}
<table width="50%" align="center">
<tr>
<td>Customer ID</td>
<td>
{{ form.customer_id }}
</td>
</tr>
<tr>
<td>First Name</td>
<td>
{{ form.first_name }}
</td>
</tr>
<tr>
<td>Last Name</td>
<td>
{{ form.last_name }}
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value = "OK" /></td>
</tr>
</table>
</form>
{% endblock %}
My expected result is the value should be bound to web page and displayed, but the actual effect is like below:
So, can someone tell me why and how to fix it?

Replace:
form = CustomerForm()
if id is None:
print("id is None")
return HttpResponseRedirect('AddressTableMaintain/')
print("----------------")
print(id)
customerList = Customer.objects.raw("select * from customers where customer_id = %s", [int(id)])
customer = list(customerList)[0]
with:
if id is None:
print("id is None")
return HttpResponseRedirect('AddressTableMaintain/')
print("----------------")
print(id)
customerList = Customer.objects.raw("select * from customers where customer_id = %s", [int(id)])
form = CustomerForm(list(customerList)[0])
Possibly related: Why are you using raw SQL instead of the much simpler:
customer = Customer.objects.get(pk=id)
which would return the one customer that you are looking for?

Related

How to get Django to redirect to the requested page with the LoginRequiredMixin after logging in?

Background:
I have an inventory application that scrapes through our VM and storage environments to index things for my team to have some quick references without having to log into vCenter/Storage systems directly to get info.
Since it's dealing with some potentially sensitive info, I put authentication on it by way of using the LoginRequiredMixin in my Views classes. The authentication part has been in for a while and it works without issues. The part where I get stuck on is I implemented the next parameter in the login form, and it shows up in the URL when it prompts to login. I have a different view class for each kind of thing I'm tracking.
Goal:
When someone clicks on a link that requires authentication (basically every page except the main page), it redirects them to the page they want after requiring them to login.
I've seen a few other questions, but the recommendations mentioned haven't worked in my case for whatever reason. I've tried various implements of the redirect_field_name but it still ends up trying to redirect to /accounts/profile if I don't have it overridden in the settings page. I don't have the login_url field set, but the login page redirect works as expected.
----Code Snippets----
LoginView - Using Django's LoginView and authentication form as a base, and just piecing them together to keep my search capability at the top of the page.
class LoginView(SearchMixin, auth_views.LoginView):
template_name = 'VMwareInventory/Registration/login.html'
form = AuthenticationForm
def get_context_data(self, **kwargs):
context = super(LoginView, self).get_context_data()
context['login_form'] = self.form
return context
Example view that requires logging in. The url ends up correctly: /accounts/login?next=/Clusters/
class StorageView(SearchMixin, LoginRequiredMixin, ListView):
model = StorageSystem
template_name = 'VMwareInventory/Storage_templates/cluster_list_page.html'
context_object_name = 'cluster_list'
queryset = StorageSystem.objects.all()
def get_context_data(self, *args, **kwargs):
context = super(StorageView, self).get_context_data()
clusters = StorageSystem.objects.all()
context['clusters'] = clusters
return context
def get(self, request, *args, **kwargs):
if self.request.is_ajax():
sorting_method = self.request.GET.get('sorting_method')
ascending = self.request.GET.get('ascending')
data = []
query = StorageSystem.objects.all()
results = None
if ascending == "true":
results = query.order_by(sorting_method)
elif ascending != "true":
results = query.order_by(sorting_method).reverse()
else:
query = None
data = serialize('json', None)
if query is not None:
for obj in results:
url_link = '' + obj.name + ''
json_data = {"name": url_link, "node_count": obj.node_count}
data.append(json_data)
return JsonResponse(data=data, safe=False)
else:
return render(self.request, self.template_name, context=self.get_context_data())
Login.html page:
<div class="login" style="vertical-align: middle; height: 100%; margin-top: 13%">
<table class="login" style="border: none; margin-top: auto; margin-bottom: auto">
<tr>
<td>
{% if form.errors %}
<p>Your username and/or password is incorrect. Please try again</p>
{% endif %}
{% if next %}
<p>You need to login first before you can do that</p>
{% else %}
<p>To see this page, please login with Username and Password</p>
{% endif %}
<form method="post" action="{% url 'VMwareInventory:login' %}">
{% csrf_token %}
<table>
<tr>
<td>{{ login_form.username.label_tag }}</td>
<td>{{ login_form.username }}</td>
</tr>
<tr>
<td>{{ login_form.password.label_tag }}</td>
<td>{{ login_form.password }}</td>
</tr>
</table>
<div style="padding-top: 5px; text-align: center">
<input type="submit" value="login"/>
<input type="hidden" name="next" value="{{ next }}"/>
</div>
</form>
</td>
</tr>
</table>
urls:
path('accounts/login/', views.LoginView.as_view(), name='login'),
path('accounts/logout/', views.LogoutView.as_view(), name='logout'),
path('accounts/password_change/', views.PasswordChangeView.as_view(), name='password_change'),
path('accounts/password_change/done/', views.PasswordChangeDoneView.as_view(), name='password_change_done')
path('Clusters/', views.StorageView.as_view(), name='storList'), # cluster url for view listed above.
OK, so after doing a bit of digging into some of Django code and seeing how the process works, I discovered that the next value wasn't getting pushed into the POST data. So I ended up having to capture the next value from request.GET.get('next') and I pushed it to a redirect variable in the html (I changed that from the next variable that I had initially).
All in all, there were only a few changes that I made in the code to get this working. I didn't have to re-create the entire view (which was helpful).
Hopefully this will help some others with this same issue get this up and running without having to completely rewrite a View, or override a bunch of methods.
Edit: I had to add a check to make sure that if there was no next value, then it wouldn't populate the redirect field.
LoginView:
class LoginView(SearchMixin, auth_views.LoginView):
template_name = 'VMwareInventory/Registration/login.html'
redirect_field_name = "redirect" # added
redirect_authenticated_user = True # added
form = AuthenticationForm
def get_context_data(self, **kwargs):
context = super(LoginView, self).get_context_data()
context['login_form'] = self.form
if self.request.GET.get('next'):
context['redirect'] = self.request.GET.get('next') # added
return context
login.html:
<div class="login" style="vertical-align: middle; height: 100%; margin-top: 13%">
<table class="login" style="border: none; margin-top: auto; margin-bottom: auto">
<tr>
<td>
{% if form.errors %}
<p>Your username and/or password is incorrect. Please try again</p>
{% endif %}
{% if next %}
<p>You need to login first before you can do that</p>
{% else %}
<p>To see this page, please login with Username and Password</p>
{% endif %}
<form method="post" action="{% url 'VMwareInventory:login' %}">
{% csrf_token %}
<table>
<tr>
<td>{{ login_form.username.label_tag }}</td>
<td>{{ login_form.username }}</td>
</tr>
<tr>
<td>{{ login_form.password.label_tag }}</td>
<td>{{ login_form.password }}</td>
</tr>
</table>
<div style="padding-top: 5px; text-align: center">
<input type="submit" value="login"/>
<input type="hidden" name="redirect" value="{{ redirect }}"/> # changed from before
</div>
</form>
</td>
</tr>
</table>

why is input from my form not writting to the sqlite3 database in django

I would like to update my list after adding some inputs through a form but i cannot see my updated list. I see the existing items in my list ,but when i add a new item it does not appear on the list. I can manually add it using the admin pannel and view it in the list(a whole different path),but not with the form i created to take input and update the list. I was able to query my database and input from the form is not getting written to the database, that's why its not displaying any changes.Below is my code
models.py
class BlogPost(models.Model):
notes = models.CharField(max_length = 1000000000000000000000000000)
date = models.DateTimeField(auto_now_add=True)
done = models.BooleanField(default=False)
def __str__(self):
return self.notes
form.py
from blog.models import BlogPost
class BlogForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = ['notes', 'done',]
views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse,HttpResponseRedirect,HttpRequest
from blog.models import BlogPost
from blog.form import BlogForm
def home(request):
context = {
'welcome_text': 'Welcome to the home page. View some more stuff soon'
}
return render(request,'home.html', context)
def blogpost(request):
if request.method == "POST":
form = BlogForm(request.POST)
if form.is_valid():
if form.save():
message.success(request, "the task was added")
return redirect('blogpost')
else:
all_blogs = BlogPost.objects.all
return render(request, 'blog.html',{'the_blogs': all_blogs } )
blog.html
{%extends 'base.html' %}
{% block title%}
<title> Blog </title>
{% endblock title%}
{%block content %}
<div class="container">
<br>
{%for message in messages%}
{{message}}
{% endfor %}
<form method = 'POST'>
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" name = 'blog' placeholder = 'new blog' >
</div>
<button type="submit" class="btn btn-primary">Add Blog</button>
</form>
<br>
<table class="table table-hover table-dark">
<thead>
<tr>
<th scope="col">Blog </th>
<th scope="col">Done</th>
<th scope="col">Date</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
{% for item in the_blogs %}
{% if item.done %}
<tr class="table-success">
<td >{{item.notes}}</td>
<td >Not-Completed</td>
<td>{{item.date}}</td>
<td>edit</td>
<td>delete</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
</div>
{%endblock content%}
if you need more information regarding this, here is a link to my GitHub repository with more code.
https://github.com/wfidelis/Django-App
You have to correct the code indentation and the get call part, pass the form to context object and call it with double curly brackets on templates, also add an action attribute to the template.
def blogpost(request):
all_blogs = BlogPost.objects.all()
if request.method == "POST":
form = BlogForm(request.POST)
if form.is_valid():
if form.save():
message.success(request, "the task was added")
return redirect('blogpost')
else:
form = BlogForm()
return render(request, 'blog.html',{'form': form, 'the_blogs': all_blogs } )
<form method='POST' action="">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Add Blog</button>
<form/>
When you add a blog, don't redirect, try rendering the page with the new list the same as how you did it here:
all_blogs = BlogPost.objects.all
return render(request, 'blog.html',{'the_blogs': all_blogs } )
or try returning new object created as JSON format to the front-end (as a response of the POST request) and front-end will add it to the HTML with jQuery or JS

how can I update multiple record list from a form in Django 1.9

I have a shipment_details form where have some information about shipment and all item in that order of the shipments. There is two model information one Shipment another is Items model. I want to update all Marco Item Shipped value using the checkbox( see the form view pics).
here is my form view
http://imgur.com/a/dcNZE
Here is my forms.py where I linked up checkbox to Items is_shipped field and this value show in the view using {{form_status.as_p}}.
forms.py
class ShipmentStatus(forms.CheckboxInput):
input_type = 'checkbox'
class ShipmentStatusForm((forms.ModelForm)):
class Meta:
model = Items
fields = ['is_shipped']
widgets = {
'is_shipped': ShipmentStatus(),
}
Here is my view model
shipment_detail.html
{% extends "_dashboardlayout.html" %}
{% block content %}
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h2 class="page-header">Shipment Details</h2>
</div>
<div class="col-md-12">
<form method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<table class="table table-striped">
<tr>
<th>Item No</th>
<th>SKU</th>
<th>Quantity</th>
<th>Price</th>
<th>Marco Item</th>
<th>Marco Item Shipped</th>
</tr>
{% for item in items_queryset %}
<tr>
<td>{{ item.item_no }}</td>
<td>{{ item.sku }}</td>
<td>{{ item.requested_quantity }}</td>
<td>{{ item.price }}</td>
<td>{{ item.is_send }}</td>
<td>{{ form_status.as_p }}</td>
</tr>
{% endfor %}
</table>
<input type="submit" value="Save">
</form>
</div>
</div>
<!-- /.row -->
</div>
{% endblock %}
Here is my control py file
def shipment_detail(request, order_id=None):
order_queryset = Order.objects.get(order_id=order_id)
customer_queryset = Customer.objects.all()
address_queryset = Address.objects.all()
items_queryset = Items.objects.filter(order_id=order_id).order_by('item_no')
shipment_queryset = Shipment.objects.filter(order_id=order_id)
# if there is no shipment data then generate shipment details for the Order
if not shipment_queryset:
form = ShipmentForm(request.POST or None)
form_status = ShipmentStatusForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.order_id = order_queryset
order_queryset.save()
instance.save()
# save item status
if form_status.is_valid():
instance = form_status.save(commit=False)
instance.save()
context = {
"form": form,
"form_status": form_status,
"order_queryset": order_queryset,
"customer_queryset": customer_queryset,
"address_queryset": address_queryset,
"items_queryset": items_queryset,
}
return render(request, "shipment_detail.html", context)
# if there is already data then updated the shipment details for the Order
else:
instance = get_object_or_404(Shipment, order_id=order_id)
form = ShipmentForm(request.POST or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.order_id = order_queryset
# updated order is_shipped field according to ship_status
if instance.status == True:
order_queryset.is_shipped = True
if instance.status == False:
order_queryset.is_shipped = False
# updated order is_completed field according to shipment is_complete field
if instance.is_complete == True:
order_queryset.is_completed = True
if instance.is_complete == False:
order_queryset.is_completed = False
order_queryset.save()
instance.save()
print "form status"
# updated item is_shipped field
instance_status = get_list_or_404(Items, order_id=order_id)
for instance in instance_status:
form_status = ShipmentStatusForm(request.POST, instance=instance)
if form_status.is_valid():
instance = form_status.save(commit=False)
instance.save()
context = {
"form": form,
"instance": instance,
"form_status": form_status,
"order_queryset": order_queryset,
"customer_queryset": customer_queryset,
"address_queryset": address_queryset,
"items_queryset": items_queryset,
}
return render(request, "shipment_detail.html", context)
Here problem is when click all the Marco Item Shipped true or false its save value properly but if I click one false another true then it doesn't save value.
One way to do this is use pk of an object as value of check box
<input type="checkbox" value='{{item.id}}'
name='for_action' id='for_action' >
, You can get list of these pk in your views using request.POST.getlist('for_action')
Here You Go!!
HTML:
<div class="col-lg-12">
<h2 class="page-header">Shipment Details</h2>
</div>
<div class="col-md-12">
<form method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<table class="table table-striped">
<tr>
<th>Item No</th>
<th>SKU</th>
<th>Quantity</th>
<th>Price</th>
<th>Marco Item</th>
<th>Marco Item Shipped</th>
</tr>
{% for item in items_queryset %}
<tr>
<td>{{ item.item_no }}</td>
<td>{{ item.sku }}</td>
<td>{{ item.requested_quantity }}</td>
<td>{{ item.price }}</td>
<td>{{ item.is_send }}</td>
<td><input type="checkbox" value='{{item.id}}'
name='for_action' id='for_action' ></td>
</tr>
{% endfor %}
</table>
<input type="submit" value="Save">
</form>
</div>
</div>
<!-- /.row -->
{% endblock %}
views.py
def shipment_detail(request, order_id=None):
#########
# save item status
list_of_id_for_action = request.POST.getlist('for_action')
list_of_obj = Items.objects.filter(pk__in=list_of_id_for_action)
list_of_obj.update(is_shipped=True)
######
context = {
"form": form,
"instance": instance,
"form_status": form_status,
"order_queryset": order_queryset,
"customer_queryset": customer_queryset,
"address_queryset": address_queryset,
"items_queryset": items_queryset,
}
Hope this helps

My django python functions not running correctly

I am currently working on an e-commerce web app and decided to use the Beginning Django Ecommerce book. I am following the content and implementing it in my own way but i am having some issues with some few functions that are not running.
here are the apps with the files where i think the problem is coming from;
1. cart app models.py:
from django.db import models
from menu_items.models import Item
from smartmin.models import SmartModel
import django.db.models.options as options
options.DEFAULT_NAMES = options.DEFAULT_NAMES + ('augment_quatity','name','price','get_absolute_url','total',)
class OrderItem(SmartModel):
order_id = models.CharField(max_length=50)
date_added = models.DateTimeField(auto_now_add=True)
quantity = models.IntegerField(default=0)
item = models.ManyToManyField(Item)
class Meta:
db_table='order_items'
def __unicode__(self):
return "%s" % (self.order_id)
def total(self):
return self.quatity *self.item.price
def name(self):
return self.item.name
def price(self):
return self.item.price
def get_absolute_url(self):
return self.item.get_absolute_url()
# incase user orders same item twice we jus add on the quantity
def augment_quatity(self, quantity):
self.quatity = self.quantity + int(quantity)
self.save
orders.py in the same app:
from cart.models import OrderItem
#from cart.models import order_id
from menu_items.models import Item
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
import decimal
import random
ORDER_ID_SESSION_KEY = 'order_id'
# get the current user's cart id, sets new one if blank
def _order_id(request):
if request.session.get(ORDER_ID_SESSION_KEY,'') == '':
request.session[ORDER_ID_SESSION_KEY] = _generate_cart_id
return request.session[ORDER_ID_SESSION_KEY]
def _generate_cart_id():
order_id =''
characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*()'
order_id_length = 100
for y in range(order_id_length):
order_id += characters[random.randint(0,len(characters)-1
)]
return order_id
# return all items from the current user's order
def get_order_items(request):
return OrderItem.objects.filter(order_id=_order_id(request))
# add an item to order
def add_to_order(request):
postdata = request.POST.copy()
#get item slug from post data, return blank if empty
# item_slug = postdata.get('item_slug','')
#get quantity added, return 1 if empty
quantity = postdata.get('quantity',1)
# fetch the item or return missing page error_message
i = get_object_or_404(Item,)
# get items in order
order_items = get_order_items(request)
item_in_orders = False
# check to see if item is already in cart
for order_item in order_items:
if order_item.item.id == i.id:
#update the quantity if found
order_item.augment_quantity(quantity)
item_in_order = True
if not item_in_order:
# creat and save a new order item
oi = OrderItem()
oi.item = i
oi.quantity = quantity
oi.order_id = _order_id(request)
oi.save()
2.live app views.py
def show_order(request):
if request.method == 'POST':
postdata = request.POST.copy()
if postdata['submit'] == 'Remove':
order.remove_from_order(request)
if postdata['submit'] == 'Update':
order.update_order(request)
order_items = order.get_order_items(request)
page_title = 'F4L order'
order_subtotal = order.order_subtotal(request)
return render_to_response('public/order.html',context_instance=RequestContext(request))
Template where the functionality is not working,
{% extends "base.html" %}
{% block content %}
{% load menu_tags %}
<div style="height:30px">
{% order_box request %}
</div>
<table summary="Your menu order" id="menu_order">
<caption>Your F4L Orders</caption>
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Price</th>
<th scope="col" class="right">Total</th>
</tr>
</thead>
<tfoot>
<tr>
<th class="right" colspan="2">
Order Subtotal:
</th>
<th class="right">
{{order_subtotal}}<span> frw</span>
</th>
</tr>
{% if order_items %}
<tr>
<th class="right" colspan="2">
Checkout Now
</th>
</tr>
{% endif %}
</tfoot>
<tbody>
{% if order_items %}
{% for item in order_items %}
<tr>
<td>
{{ item.name }}
</td>
<td>{{ item.price }}<span> frw</span></td>
<td class="right">
<form method="post" action="." class="order">
<label for="quantity">Quantity:</label>
<input type="text" name="quantity" value="{{ item.quantity }}" id="quantity" size="2" class="quantity" max_length="5" />
<input type="hidden" name="item_id" value="{{ item.id }}" />
</td>
<td>
<input type="submit" name="submit" value="update"/>
</form>
</td>
<td>
<form method="post" action="." class="order">
<input type="hidden" name="item_id" value="{{ item.id }}" />
</form>
</td>
<td>
<form method="post" action="." class="order">
<input type="hidden" name="item_id" value="{{ item.id}}" />
<input type="submit" name="submit" value="Remove" />
</form>
</td>
<td class="right">{{ item.total }}<span> frw</span></td>
</tr>
{% endfor %}
{% else %}
<tr>
<td colspan="2" style="height:30px;">
Your F4L order is empty.
</td>
</tr>
{% endif %}
</tbody>
</table>
{% endblock %}
Now th problem is, the above template code is a page a user redirects to after submitting a form with the quantity of item he/she is buying but that is not happening. After submitting form with for example 10items,i redirect to this page(above _template_), it loads correctly but does not return the information i submitted.
i do understand that this is alot but i have really need your help and will appreciate any sort of help.
In show_order view you should pass your variables to template as dictionary:
...
context_dict = {'order_items': order_items, 'order_subtotal': order_subtotal}
return render_to_response('public/order.html', context_dict, context_instance=RequestContext(request))

generate and calling boolean field forms in django template

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