Reputation: 69
I want to calculate the total amount after applying the discount. For that i have made cart.py. But when i call the functions from cart.py in templates.html. It neither display the total amount after discount nor the discounted percentage.
cart.py created in cart app
from decimal import Decimal
from django.conf import settings
from shop.models import Product
from coupons.models import Coupons
class Cart(object):
def __len__(self):
return sum(item['quantity'] for item in self.cart.values())
def get_total_price(self):
return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
def clear(self):
del self.session[settings.CART_SESSION_ID]
self.session.modified = True
@property
def coupon(self):
if self.coupon_id:
return Coupons.objects.get(id=self.coupon_id)
def get_discount(self):
if self.coupon:
return (self.coupon.discount / Decimal('100')) * self.get_total_price()
def get_total_price_after_discount(self):
return self.get_total_price() - self.get_discount()
template.html
<tr class="gray2">
<td colspan="2"> coupon ({{discount}}) % off</td>
<td colspan="3"></td>
<td class="num neg"> {{cart.get_discount|floatformat:"2"}}</td>
</tr>
<tr class="total">
<td>Total</td>
<td colspan="4"></td>
<td class="num">{{cart.get_total_price_after_discount|floatformat:"2"}}</td>
</tr>
</table>
<div class="divo">
<p>
coupon code to apply discount
</p>
<form action="{% url 'coupons:apply' %}" method="post">
{{coupon_apply_form}}
{% csrf_token %}
<input type="submit" value="apply" class="btn">
</form>
</div>
views.py
@require_POST
def coupon_apply(request):
now = timezone.now()
form = CouponApplyForm(request.POST)
if form.is_valid():
code = form.cleaned_data['code']
try:
coupon = Coupons.objects.get(code__iexact=code,
valid_form__lte=now,
valid_to__gte=now,
active=True)
request.session['coupon_id'] = coupon.id
except Coupons.DoesNotExist:
request.session['coupon_id'] = None
return HttpResponseRedirect(reverse("cart"))
This portion of template.html is not displaying. Please if anybody can help me in this regard.
Note:
coupon_apply_form = CouponApplyForm()
context={'cart':cart,'coupon_apply_form':coupon_apply_form}
I have wrote this in view.py in carts app.
Upvotes: 0
Views: 1952
Reputation: 384
You cannot call functions from within your template. Do the calculation in your views, and save the new total to a variable and pass that to your template through the context. If you do need help with the actual coding of what I described let me know. This is however a duplicate question.
Edit: I would recommend asking questions in the future that describe the problem you are having instead of using specifics that are only exact to your question. As an example I would ask (Calling function from Django template does not work) which is very concise even though it looks like a "simple" or maybe "dumb" question. Hopefully this helps you in the future! :)
Upvotes: 1