簡體   English   中英

在Django中應用折扣后如何計算總數?

[英]How to calculate the total after applying discount in Django?

我想在應用折扣后計算總金額。 為此,我做了cart.py。 但是,當我從templates.html中的cart.py調用函數時。 它既不顯示折扣后的總金額,也不顯示折扣率。

在購物車應用中創建的cart.py

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"))

template.html的此部分未顯示。 請有人在這方面幫助我。

注意:

  coupon_apply_form = CouponApplyForm()
  context={'cart':cart,'coupon_apply_form':coupon_apply_form}

我已經在購物車應用程序的view.py中寫了這個。

您不能從模板中調用函數。 在視圖中進行計算,然后將新的總計保存到變量中,然后通過上下文將其傳遞給模板。 如果確實需要有關我所描述的代碼的幫助,請告訴我。 但是,這是一個重復的問題。

編輯:我建議以后再問一些描述您所遇到的問題的問題,而不要使用僅適合您問題的細節。 作為一個例子,我會問(從Django模板調用函數不起作用),盡管看起來像一個“簡單”或“愚蠢”的問題,但它還是非常簡潔。 希望這對以后有幫助! :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM