用户提交内容时返回实例属性

时间:2017-05-25 03:19:19

标签: python html django

现在我正在尝试建立一个电子商务网站。我的问题是,我无法计算用户在当前购买上花费的总金额,我不知道如何使用当前Product对象的价格,而是我只是得到None 。我知道这可能是一个简单的答案。

这是我的models.py:

from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
from django import forms, views
from django.db.models import Sum

class ExtendedProfile(models.Model):
    user = models.OneToOneField(User)
    amount_spent = models.DecimalField(max_digits=6, decimal_places=2, default=0)

    #@classmethod tells the class to act on itself instead of an instance of itself
    @classmethod
    def total_amount(cls):
        #returns a dictionary
        return cls.objects.all().aggregate(total=Sum('amount_spent'))

class RevenueInfo(models.Model):
    #here we access the dictionary
    user_total = ExtendedProfile().total_amount()['total']
    total_amount_spent = models.DecimalField("Total User Revenue", max_digits=6, decimal_places=2, default=user_total)

class Product(models.Model):
     category = models.CharField(max_length=100)
     name = models.CharField(max_length=100)
     description = models.TextField()
     #photo = models.ImageField()
     price_CAD = models.DecimalField(max_digits=6, decimal_places=2)
     quantity = models.DecimalField(max_digits=2, decimal_places=0, null=True, editable=True)

这是我的观点

def product_page(request):
    all_products = Product.objects.all()
    quantity_forms = QuantityForms(request.POST)
    quantity = request.POST.get('amount')
    grand_total = RevenueInfo.user_total
    if quantity > 0:
        return HttpResponse(Product().price_CAD)
    return render(request,'tracker/product_page.html', {'all_products':all_products, 'quantity_forms':quantity_forms})

这是模板:

{% load staticfiles %}
<!DOCTYPE html>
<!DOCTYPE html>
<html>
{% for object in all_products %}
<h3><a href="{{ object.get_absolute_url }}">{{ object.name }}</a></h3>
<p>{{ object.description }}</p>
<p>{{ object.price_CAD }}</p>
<form method='POST'>
{% csrf_token %}
{{ quantity_forms.amount }}<button>Buy</button>
</form>
{% endfor %}
</html>

现在我只想尝试至少返回用户按下的正确数量的产品&#34;购买&#34;上。然后从那里我将计算购买总额

1 个答案:

答案 0 :(得分:1)

有几个问题,首先是你刚刚返回新创建的产品的price_CAD

if quantity > 0:
    return HttpResponse(Product().price_CAD)

如果空白允许则为零,如果不允许空白则为零。

您应该返回与该用户关联的产品。但是你的模型并没有显示这种关联是否存在。

其他问题包括您没有使用request.user抓取登录用户,而是直接从request.POST获取数据,这是不安全的。

相关问题