我有一个命名为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()
,并有一个名为"product.html"其中显示当前产品信息,如图所示:产品页面图片
和我得到的所有这些数据的产品。html的视图如下:
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
和在product.html我得到数据的语法:
<span class="mr-1">
<del>₹ {{ object.price }}</del>
</span>
<span>₹ {{ object.discount_price }}</span>
这是一个正常工作的故事,没有问题,直到有**问题开始时,我在下面创建这个讨价还价模型**
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')
]
让我解释一下这个交易模型的目的。实际上,该模型用于讨价还价产品的价格,它从用户处获取输入价格,并使用以下值更新到讨价还价模型user, Item和"bprice"这是产品议价后的新价格*
和我已经成功创建了一个对象"交易对象(3)"在图像中显示的模态值:图像的模态值
**so what i need - if user have bargained the price product.html show the bargain price which is "bprice" in the Bargain modal instead of product price in Item modal** of the respective user**
为了实现这一点,我改变了我的itemView如下:
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
def get_bargain(self, request):
if request.user.is_authenticated():
return Bargain.objects.filter(item=self.object, user=request.user).first()
和在product.html我这样做:<h1>This is the {{ view.get_bargain.bprice }}</h1>
*但这没有给我任何*更多信息-登录用户admin
谁能告诉我我做错了什么或任何其他的方法吗?提前谢谢。如果视图仅限于登录用户,则可以从LoginRequiredMixin
扩展视图。然后,您可以指定上下文对象名称"item"如下。
class ItemDetailView(LoginRequiredMixin, DetailView):
model = Item
template_name = "product.html"
context_object_name = "item"
def get_object(self, queryset=None):
return get_object_or_404(self.model, pk=self.kwargs['pk'])
,在您的模板中,您可以获得与此项目相关的所有便宜货。就像.
{% if item.bargain %}
<h1>This is the {{ item.bargain.first.bprice }}</h1>
{% else %}
<h1> no bargain against this item </h1>
{% endif %}
细节:item
为上下文项。item.bargain.first
让你获得第一个特价商品。
在你的app/urls.py
你可以把你的url像这样:
urlpatterns = [
....
path('product/<int:pk>', ItemDetailView.as_view()),
]