我无法访问模板上多对多字段的对象,而我可以访问其他字段的对象
models.py
class Cart(models.Model):
total = models.IntegerField(max_length=None, default=0)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
active = models.BooleanField(default=True)
products = models.ManyToManyField(product)
views.py
def carthome(request):
cartproduct = Cart.objects.all()
print(cartproduct)
context = { 'cartproduct' : cartproduct, }
return render(request, 'home/carthome.html', context)
在模板中
{% for abc in cartproduct%}
{{ abc.product.name }}
{% endfor %}
错误
AttributeError: 'Cart' object has no attribute 'product'
您必须对模型对象和进行排序,然后对manytomy字段进行排序-下面提到的选项将起作用。你知道吗
Cart.objects.all()
将为您提供所有的Cart
。或者在模板中循环所有的Cart
(尽管我怀疑这是您想要做的),或者选择一个。你知道吗cart = Cart.objects.first()
或cart = Cart.objects.get(id=1)
或任何只给你一辆车的东西(所以没有filter()
)。你知道吗那么
cartproducts = cart.products.all()
应该修复它。模板正常,没有输入错误(cartproduct->;cartproducts)。你知道吗此外,这是广泛的离题:您将如何管理您的购物车数量?产品没有数量,购物车只装产品。您将只能使用单个数量的产品,除非您使用
ForeignKeys
cart
、product
和IntegerField
数量创建单独的模型。你知道吗在您的模型中,产品=模型.ManyToManyField(产品)。 确保在产品型号中有atribute这个名字。那就试试这个代码
似乎在您的代码中,您正试图直接访问产品模型。但是你应该通过Cart(cartproduct)然后products(cartpatribute)然后name来获取它。你知道吗
相关问题 更多 >
编程相关推荐