You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中如何在视图内将Product模型的price赋值给Main模型的amount字段

实现步骤

1. 调整前端HTML表单

首先删除表单中手动输入金额的amount输入项,新增隐藏的product_id字段用来传递当前购买商品的主键(你需要确保渲染这个表单的视图已经把当前商品对象product传入了模板上下文):

<form action="{%url 'payment_start' %}" method="POST">
   {% csrf_token %}
   <!-- 新增隐藏字段传递商品ID -->
   <input type="hidden" name="product_id" value="{{ product.id }}">
   <input style="width: 100%;" type="text" name="name" placeholder="Name" required>
   <br/> <br/>
   <input style="width: 100%;" type="text" name="phone" placeholder="Phone">
   <br/> <br/>
   <input style="width: 100%;" type="mail" name="mail" placeholder="MAil">
   <br/> <br/>
   <input style="width: 100%;" type="text" name="desc" placeholder="Description">
   <br/> <br/>
   <button style="width: 100%;"  type="submit" class="btn btn-primary">Start Payment</button>
</form>

2. 修改payment_start视图函数

调整视图逻辑,不再从POST参数中获取amount,而是根据提交的商品ID查询Product表获取对应价格,同时增加必要的异常校验:

def payment_start(request):
    if request.method == 'POST':
        # 先获取商品ID并查询对应商品
        product_id = request.POST.get('product_id')
        try:
            product = Product.objects.get(id=product_id, is_available=True)
        except Product.DoesNotExist:
            txt = "商品不存在或已下架"
            return render(request, 'error.html', {'txt': txt})
        
        order_id = uuid.uuid1()
        # 直接用商品的price作为支付金额
        amount = product.price
        name = request.POST.get('name')
        email = request.POST.get('mail')
        phone = request.POST.get('phone')

        payer = {
            'name': request.POST.get('name'),
            'phone': request.POST.get('phone'),
            'mail': request.POST.get('mail'),
            'desc': request.POST.get('desc'),
        }

        record = Main(order_id=order_id, amount=int(amount), name=name, email=email, phone=phone, user=request.user)
        record.save()

        idpay_payment = payment_init()
        result = idpay_payment.payment(str(order_id), amount, 'orders/payment/return', payer)

        if 'id' in result:
            record.status = 1
            record.payment_id = result['id']
            record.save()
            return redirect(result['link'])
        else:
            txt = result['message']
    else:
        txt = "Bad Request"
    return render(request, 'error.html', {'txt': txt})

补充说明

如果你的业务是多商品合并支付,需要先建立订单模型关联多个商品,先计算订单总金额再赋值给amount,以上逻辑是单商品购买场景的实现。

内容的提问来源于stack exchange,提问作者Fredy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 03:57:02