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)
Related
I ve an error when loading 'group_list.html' :
Reverse for 'group-edit' not found. 'group-edit' is not a valid view function or pattern name.
If I supress this href reference, it works but I need this to be able to edit a group instance
this is my views.py for group_edit:
def group_edit(request, group_id):
group_form = GroupFormEdit(instance=Group.objects.get(id=group_id))
if request.method == "POST":
group_form = GroupForm(request.POST, instance=Group.objects.get(id=group_id))
if group_form.is_valid():
group_form.save()
messages.success(request, 'Group saved') # message for inform user of success - See messages in html file
return redirect('home')
else:
group_form = GroupForm()
return render(request, 'imports/group_edit.html', {
"group_form": group_form,
})
my group_list.html:
{% block page %}
<div class="panel-body">
<table class="table table-bordered table-hover table-striped col-md-3">
<thead class="thead-dark">
<tr class="text-center">
<th>Group Name</th>
<th>Parent Name</th>
</tr>
</thead>
<tbody>
{% for group in groups %}
<tr>
<td scope="row" class="col-md-3">{{ group.group_name }}</td>
<td class="col-md-3">{{ group.groupParent_id }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
my urls.py:
urlpatterns = [
path('', views.imports_last, name='home'),
path('company_create/', views.company_create, name='company_creation'),
path('group_create/', views.group_create, name='group_creation'),
path('group_edit/', views.group_edit, name='group_edit'),
path('group_list/', views.group_list, name='group_list'),
]
and models.py:
class Group(models.Model):
group_id = models.AutoField(primary_key=True)
groupParent_id = models.ForeignKey('self', blank=True, null=True, related_name='Parent', on_delete=models.CASCADE)
group_name = models.CharField(max_length=100, null=False, blank=False, unique=True)
def __str__(self):
return '{}'.format(self.group_name)
I find my pain point;
it is in the url
I should mention that I want to add a variable :
path('group_edit/<int:group_id>/', views.group_edit, name='group-edit'),
I am a newbie in Django. I want to show the food_status in drop-down list options, therefore the chef can select one of them, change it, and update it into database. It can be updated into database, but i am not sure how to display the drop-down list on template based on the food_status that I have in models.py.
Anyone know how to do it?
models.py
class OrderItem(models.Model):
Table_No = models.IntegerField(blank=False)
FoodId = models.TextField()
Item = models.TextField()
Qty = models.DecimalField(max_digits=5, decimal_places=0)
Price = models.DecimalField(max_digits=10, decimal_places=2)
TotalPrice = models.TextField()
Note = models.TextField(max_length=100, null=True)
OrderId = models.TextField(max_length=5, null=True)
FoodStatus = (
('1', 'Has been ordered'),
('2', 'cooked'),
('3', 'ready to be served'),
('4', 'done'),
)
food_status = models.CharField(max_length=50, choices=FoodStatus)
views.py
def see_order(request):
if request.method == "POST":
OrderId = request.POST.get("OrderId")
customerOrder = OrderItem(OrderId=OrderId)
so = OrderItem.objects.filter(OrderId=OrderId)
return render(request, 'restaurants/see_order.html', {'so': so})
else:
return render(request, 'restaurants/customer_page.html')
see_order.html
<form action="#" method="post">
<style>
table, th, td {
border: 1px solid black;
table-layout: fixed ;
height: "2000" ;
width: "2000" ;
}
</style>
{% csrf_token %}
{% for order in so %}
<table>
<tr>
<th>Table Number</th>
<th>Item</th>
<th>Quantity</th>
<th>Status</th>
<th>Order Id</th>
</tr>
<tr>
<td>{{ order.Table_No }}</td>
<td>{{ order.Item }}</td>
<td>{{ order.Qty }}</td>
<td>{{ order.food_status }}</td>
<td>{{ order.OrderId }}</td>
</tr>
{% endfor %}
</table>
<br><input action="action" onclick="window.history.go(-1); return false;" type="button" value="Back"></br>
</form>
The kitchen_page template should show the drop-down list, then the chef can choose the food_status from that drop-down list, click save button, and update the database.
You can render choices using {% for %} loop and FoodStatus list of choices like this:
<td>
{{ order.get_food_status_display }}
<select name="food_status">
{% for id, choice in order.FoodStatus %}
<option value="{{ id }}"{% if order.food_status == id %} selected="selected"{% endif %}>{{ choice }}</option>
{% endfor %}
</select>
</td>
You can display actual status text (instead of id), using get_FOO_display method.
Added {% if %} tag to preselect correct option.
Consider switching to Forms so it can handle rendering fields automatically.(!!!)
Consider switching food_status to IntegerField instead. Provide default attribute, so it will always be one of the choices, even if not specified.
Try using choices attribute of Django fields https://docs.djangoproject.com/en/2.0/ref/models/fields/#choices
I have a table in my models which the stocks are saving in it and its name is Stocks
this table is desplayed in a template and i want to put a checkbox beside each row to save the checked row in another table of the model
here ismy model.py :
class Stocks(models.Model):
user=models.ForeignKey(User, null=True)
name=models.CharField(max_length=128,verbose_name=_('stockname'))
number=models.CharField(blank=True,null=True,max_length=64,verbose_name=_('number'))
brand=models.CharField(max_length=64, validators=[
RegexValidator(regex='^[A-Z]*$',message=_(u'brand must be in Capital letter'),)]
,verbose_name=_('brand'))
comment=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('comment'))
price=models.PositiveIntegerField(blank=True,null=True,verbose_name=_('price'))
date=models.DateTimeField(auto_now_add = True,verbose_name=_('date'))
confirm=models.CharField(choices=checking,max_length=12,verbose_name=_('confirmation'), default=_('pending'))
def __str__(self):
return str(self.id)
class Meta:
verbose_name=_('Stock')
verbose_name_plural=_('Stocks')
def get_absolute_url(self):
return reverse('BallbearingSite:mystocks' )
class SellerDesktop(models.Model):
seller=models.OneToOneField(User, related_name='seller', blank=True, null=True)
buyer=models.OneToOneField(User, related_name='buyer', blank=True, null=True)
stock=models.ForeignKey(Stocks, related_name='stocktoseller', blank=True, null=True)
def __str__(self):
return str(self.seller) + '-' + str(self.buyer)
class Meta:
verbose_name=_('SellerDesktop')
verbose_name_plural=_('SellerDesktop')
and the Template :
<form method="post">
{% csrf_token %}
<table id="example" class="table table-list-search table-responsive table-hover table-striped" width="100%">
{% for item in myst %}
<td><input type="checkbox" name="sendtoseller" value="{{ item.id }}"></td>
<td>{{ item.user.profile.companyname}}</td>
<td>{{ item.name }}</td>
<td>{{ item.brand }}</td>
<td>{{ item.number }}</td>
<td>{{ item.pasvand }}</td>
<td>{{ item.comment }}</td>
<td>{{ item.price }}</td>
<td>{{ item.date|timesince }}</td>
</tr>
{% endfor %}
</table>
<div style="text-align: center; margin-top:0.5cm; margin-bottom:1cm;">
<input type="submit" name="toseller" value="Submit to seller " style="color:red; width:100%;"/>
</div>
</form>
and the view :
def allstocks_view(request):
if request.method=='POST':
tosave = request.POST.getlist('sendtoseller')
stockid=Stocks.objects.filter(id=tosave)
SellerDesktop.objects.create(buyer=request.user,stock=stockid)
stocks_list=Stocks.objects.all().filter(confirm=_('approved') ).order_by('-date')
#paginating for table
page = request.GET.get('page', 1)
paginator = Paginator(stocks_list, 15)
try:
myst = paginator.page(page)
except PageNotAnInteger:
myst = paginator.page(1)
except EmptyPage:
myst = paginator.page(paginator.num_pages)
context={
'allstocks':stocks_list,
'myst':myst,
}
return render(request,'BallbearingSite/sellerstocks.html',context)
this error was showed up
TypeError at /sellerstocks/
int() argument must be a string, a bytes-like object or a number, not 'list'
when i changed the code to :
stockid=Stocks.objects.filter(id=tosave[0])
this error was showed up:
ValueError at /sellerstocks/
Cannot assign "[]": "SellerDesktop.stock" must be a "Stocks" instance.
How can i insert the selected rows into new table?
the error :
Cannot assign must be a "" instance.
was gone when i changed :
Stocks.objects.filter(id=tosave[i])
to :
Stocks.objects.get(id=tosave[i])
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
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))