Django新手求助:AttributeError错误排查与代码修复
错误原因与修复方案
错误根源
你把products变量赋值成了单个Product实例对象,但后续代码里却调用了列表的append()方法——Product类并没有定义这个方法,所以触发AttributeError。
修复步骤
- 将
products初始化为包含首个Product实例的列表,而不是单个对象 - 修正类定义里的缩进问题(原代码中
__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
相关产品推荐
相关产品推荐

