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

Django新手求助:AttributeError错误排查与代码修复

错误原因与修复方案

错误根源

你把products变量赋值成了单个Product实例对象,但后续代码里却调用了列表的append()方法——Product类并没有定义这个方法,所以触发AttributeError。

修复步骤

  1. 将products初始化为包含首个Product实例的列表,而不是单个对象
  2. 修正类定义里的缩进问题(原代码中__init__方法的缩进不符合Python规范)

修复后的完整代码:

from django.shortcuts import render
from django.http import HttpResponse,HttpRequest 
import random

class Product:
    __MAX_ID = 0
    def __init__(self, name:str, color: str, availability: str, cost: str, weight: str):
        self.id = Product.__MAX_ID
        self.name = name
        self.color = color
        self.availability = availability
        self.cost = cost
        self.weight = weight
        Product.__MAX_ID += 1

    def __str__(self):
        return (
            f'{self.name}\n'
            + f'color: {self.color}\n'
            + f'availability: {self.availability}\n'
            + f'cost: {self.cost}\n'
            + f'weight: {self.weight}\n'
        )

# 修改:将products初始化为列表,包含第一个Product实例
products = [Product('nuke','red','100 pcs','9999 rub','4500 gramm')]

def test(request:HttpRequest):
    body = request.body.decode('UTF-8')
    # 现在products是列表,可以正常调用append()
    products.append(Product(body,'red','100 pcs','9999 rub','4500 gramm'))
    return HttpResponse('\n'.join(str(product) for product in products))

额外提示

这种全局列表仅适合本地测试场景,正式上线的Django项目建议使用数据库(如Django ORM)存储产品数据,避免重启服务后数据丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:12:10