I am creating a basic shopping cart application, I can get in my cart all of the items to populate with the quantity and cost, but I am trying to find a way thats I can create a total cost, and adding sales tax on top of that. Clearly the total line is the issue, but I am not sure what I could do to populate price and quantity for all products and multiply them together.
{% for addtocart in userCart %}
<li>Quantity:{{addtocart.quantity}} <a href="/products/{{addtocart.product.id}}">{{addtocart.product.prodName}}</a> ${{addtocart.product.prodPrice}}(<a
href=/delItem/{{addtocart.id}}>Remove</a>)<br>
{% endfor %}
</ul>
{% else %}
<p> No products available </p>
{% endif %}
***<p>Total: {{addtocart.quantity}}"x"{{addtocart.product.prodPrice}}***
views.py
def addtocart(request, prod_id):
if (request.method == 'POST'):
form = CartForm(request.POST)
if form.is_valid():
newComment = form.save()
newComment.session = request.session.session_key[:20]
newComment.save()
return HttpResponseRedirect('/products/' + str(newComment.product.id))
else:
form = CartForm( {'name':'Your Name', 'session':'message', 'product':prod_id} )
return render_to_response('Products/comment.html', {'form': form, 'prod_id': prod_id})
def userHistory(request):
userCart = Cart.objects.filter(session = request.session.session_key[:20])
return render_to_response('Products/history.html', {'userCart':userCart})
models.py
from django.db import models
from django.forms import ModelForm
# Create your models here.
class prod(models.Model):
prodName = models.CharField(max_length=100)
prodDesc = models.TextField()
prodPrice = models.FloatField()
prodImage = models.ImageField(upload_to="userimages/")
def __unicode__(self):
return self.prodName
class Cart(models.Model):
session = models.CharField(max_length=100)
product = models.ForeignKey('prod')
quantity = models.IntegerField()
def __unicode__(self):
return self.name
class CartForm(ModelForm):
class Meta:
model = Cart
exclude = ('session')
There are two ways you can do this:
(1) in more detail:
In your view:
Then in your template:
<p>{{totalCost}}</p>(2) in more detail:
First make a new file my_app/templatetags/my_tags.py (also put an __init__.py file in this directory, so that Python knows it’s a package)
Then in your template add
{% load my_tags %}at the top, and you’ll be able to use{{addtocart.quantity|multiply:addtocart.product.prodPrice}}