我无法理解我的代码中的一些不当行为,
在这里,我在模板表单而不是 django 表单中定义radio
和,check boxes
<form method="post" action=".">
{% csrf_token %}
{% for optionalitem in optionalcategory.optional_items.all %}
<input type="radio" value="{{optionalitem.id}}" name="option">{{optionalitem.name}}
{% endfor %}
{%for topping in toppingcategory.topping.all %}
<input type="checkbox" value="{{topping.id}}" name="topping">{{topping.name}}
{% endfor%}
........
</form>
表单验证,
.....
final_form = form(request.POST)
if final_form.is_valid():
order.add_to_order(request,a)
....
else:
final_form = partial_order_item_form()
....
我的模型利用了表单生成的发布数据;
class OrderItem(SmartModel):
......
option = models.ForeignKey(Optional_Item,null=True,blank=True)
topping = models.ForeignKey(Topping,null=True, blank=True)
然后我OrderItem object
从上面的表格中创建使用 postdata,
def add_to_order(request,obj):
postdata = request.POST.copy()
op = postdata.get('option',False)
optional_item = None
if op:
optional_item = get_object_or_404(Optional_Item, pk=op)
toppings_checked = postdata.get('topping',None)
toppings = None
if toppings_checked:
toppings = get_object_or_404(Topping, pk=toppings_checked)
.....
if not item_in_orders:
# creat and save a new order item
anon_user = User.objects.get(id=settings.ANONYMOUS_USER_ID)
oi=OrderItem.objects.create(item=i,
topping = toppings,
option = optional_item,
created_by=anon_user,
modified_by=anon_user)
oi.save()
我的问题来自这个函数,因为我试图计算一个小计OrderItem
def order_subtotal(request):
.....
for order_item in order_items:
if order_item.item.price:
order_total += order_item.item.price * order_item.quantity
elif order_item.option:
order_total += order_item.option.price * order_item.quantity
elif order_item.topping:
order_total += order_item.topping.price * order_item.quantity
return order_total
当我计算 a 的小计时,option
结果很好,但对于topping
. 我不明白为什么。我更喜欢详细的答案,但也很感谢简短的答案。