I am trying to code for handling product's grand total with the auto-update option total. I used javascript for the function of auto-update the option total price from user's checking option prices with the given checkbox. And it's working nicely. Now, I want to recalculate the grand total including product price and this option total in django. I guess there are few more steps for it, but I feel I need some advice at this time. My Questions are: First, How can I auto-update the grand total after returing the option total on the single.html page? And then maybe submitting the form having the option price, Second, Is it correct I have to create model that store option total? (ex. Order Model) Lastely, where should I add the final_order_amout fuction? Thanks in advance.
Models : * products/models.py
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(null=True, blank=True)
price = models.DecimalField(decimal_places=0, max_digits=100, default=10000)
class Choice(models.Model):
product = models.ForeignKey(Product)
name = models.CharField(max_length=255)
price = models.DecimalField(decimal_places=0, max_digits=100, default=0)
Models : * orders/models.py
class Order(models.Model):
order_id = models.CharField(max_length=120, default='aaa', unique=True)
sub_total = models.IntegerField(default=0)
option_total = models.IntegerField(default=0)
final_total = models.IntegerField(default=0)
def get_option_total(self):
instance = Product.object.get(id=self.id)
sub_total = sum(instance.choice.price)
instance.save()
return instance.option_total
def get_final_amount(self):
instance = Order.objects.get(id=self.id)
sub_total_dec = int(self.sub_total)
option_total_dec = int(self.get_option_total())
instance.option_total = option_total_dec
instance.final_total = sub_total_dec + option_total_dec
instance.save()
return instance.final_total
c * single.html
{% for item in product.choice_set.all %}
<form method='POST' action=''>{% csrf_token %}
<input type='checkbox' value='{{ item.price }}' name='choice'> {{ item.name }} : {{ item.price }}
{% endfor %}
<p>Total Option Price: <input type="text" name="TotalCost" id="TotalCost" size="10"/>$</p>
<input type='submit' value='submit'>
<p>Grand Total: {{ product.price }}</p>
Javascript :
<script>
$(document).ready(function() {
$("input").click(function(event) {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).val());
});
if (total == 0) {
$('#TotalCost').val('');
}
else {
$('#TotalCost').val(total);
}
});
});
Aucun commentaire:
Enregistrer un commentaire