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

Django电商站添多产品报错:get()返回多个Post,求Coinbase支付适配

解决Django中get()返回多个Post的错误并正确传递产品信息到支付页面

错误的核心原因是你在get_context_data方法里调用了Post.objects.get()——这个方法要求必须返回恰好一个对象,但当你添加多个产品后,数据库里存在多个Post实例,直接调用无参数的get()就会抛出返回多个对象的异常。

而你使用的DetailView视图类,已经自动根据URL中的主键或slug参数加载了当前对应的Post对象,你只需要通过self.get_object()获取这个实例即可,不需要重新查询整个表。

修正后的views.py代码如下:

class PostDetail(generic.DetailView):
    model = Post
    template_name = "shop-single.html"

    def get_context_data(self, **kwargs):
        # 获取当前页面对应的Post实例
        current_post = self.get_object()
        context = super().get_context_data(**kwargs)
        client = Client(api_key = settings.COINBASE_COMMERCE_API_KEY)
        domain_url = "https://www.nitroshop.store/"
        # 使用当前产品的属性构造支付请求参数
        product = {
            "name": current_post.title,
            "description": current_post.subject,
            "local_price": {
                "amount": current_post.product_price,
                "currency": "USD"
            },
            "pricing_type": "fixed_price",
            "redirect_url": domain_url + "NXnUijYpLIPy4xz4isztwkwAqSXOK89q3GEu5DreA3Ilkde2e93em8TUe99oRz64UWWBw9gEiiZrg60GMu3ow",
            "cancel_url": domain_url + "products"
        }
        charge = client.charge.create(**product)
        context['charge'] = charge
        return context

额外优化提示

你的Post模型里product_price用的是CharField,但价格本质是数值类型,建议改成DecimalField来存储,避免后续出现格式转换问题:

# 在models.py里修改product_price字段
product_price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:30:59