gpt4 book ai didi

python - 当用户提交某些内容时返回实例属性

转载 作者:太空宇宙 更新时间:2023-11-03 15:11:37 24 4
gpt4 key购买 nike

现在我正在尝试制作一个电子商务网站。我的问题是,我无法计算用户当前购买的总金额,我不知道如何使用当前 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>

现在我只是想至少返回用户按下“购买”按钮的正确数量的产品。然后我将计算购买的总金额

最佳答案

有几个问题,第一个问题是您只是返回新创建产品的 price_CAD

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

如果允许空白,则该值始终为“无”;如果不允许空白,则该值始终为零。

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

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

关于python - 当用户提交某些内容时返回实例属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44171721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com