如何在Django模板中打印模型数据?



我有一个名为Item的模型,如下所示:

class Item(models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
bargainprice = models.FloatField(default=0)
discount_price = models.FloatField(blank=True, null=True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField()
description = models.TextField()
image = models.ImageField()

我有一个名为Bargain的模型,如下所示:

class Bargain(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
item = models.ForeignKey(
Item,
on_delete=models.CASCADE
)
bprice = models.FloatField()
class Meta:
constraints = [
models.UniqueConstraint(
fields=['item', 'user'], name='unique_user_item')
]

,我将这个模型数据传递到模板"product.html"如下:

class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
def get_bargain(self, request):
if request.user.is_authenticated():
print("this is the user ", self.user.pk)
return Bargain.objects.filter(item=self.object, user=request.user).first()

,我想访问"bprice"在模板"product.html"所以我在模板上这样做:

这是Bprice:{{view.get_bargain。bprice}}

但是它什么也没显示,我也有一个对象在讨价还价模型名为"讨价还价对象(3)与所有必要的值示例:user: admin item:mattalicdot bprice:1799和我登录用户admin。

谁能告诉我是什么问题?

使用详细视图,当视图呈现时,它将对象传递给页面的上下文。在您的模板中,您应该只能够说{{ object.attribute_field }},其中attribute_field是您想要显示的对象字段的名称,在您的情况下,它将是object.bprice,以便能够显示值。

最新更新