现在我正在创建一个电子商务商店,但是当用户点击它时,我无法绕过显示特定对象信息(在本例中为Product实例)。所以这是我的views.py:
def product_page(request):
all_products = Product.objects.all()
quantity_forms = QuantityForms(request.POST)
quantity = request.POST.get('amount')
grand_total = RevenueInfo.user_total
current_user = request.user
#buyer = User.
if quantity > 0:
#ExtendedProfile().amount_spent += (quantity * Product.price_CAD)
#RevenueInfo().user_total += int(quantity)
return HttpResponse(current_user.product_set.all()[0].description)
return render(request,'tracker/product_page.html', {'all_products':all_products, 'quantity_forms':quantity_forms})
def product_details(request, object_id):
product = object_id
return render(request, 'tracker/product_details.html', {'product':product})
models.py:
class Product(models.Model):
purchase = models.ManyToManyField(settings.AUTH_USER_MODEL, through="Purchases")
category = models.CharField(max_length=100)
name = models.CharField(max_length=100)
description = models.TextField()
#photo = models.ImageField()
price_CAD = models.DecimalField(max_digits=6, decimal_places=2)
quantity = models.DecimalField(max_digits=2, decimal_places=0, null=True, editable=True)
def get_absolute_url(self):
return reverse("product_details")
我的product_page.html
:
{% load staticfiles %}
<!DOCTYPE html>
<!DOCTYPE html>
<html>
{% for object in all_products %}
<h3><a href="{{ object.get_absolute_url }}">{{ object.name }}</a></h3>
<p>{{ object.description }}</p>
<p>{{ object.price_CAD }}</p>
{% endfor %}
</html>
基本上我没有得到合理的信息流,当我点击其中一个引用我的get_absolute_url
视图的产品链接时Product
正在我的product_details
模型中运行,但是从那里我如何引用单击的单个产品实例,然后在另一个模板中显示它的唯一属性?
答案 0 :(得分:1)
当用户点击链接
时,您需要传递一些唯一的产品ID<h3><a href="{% url 'your url' object.id %}">{{ object.name }}</a></h3>
然后在urls.py中发送相同的url
url(r'^(?P<object_id>[0-9]+)/$', views.detail, name='detail'),
现在,您可以将object_id用作
def detail(request, object_id):
答案 1 :(得分:1)
from django.urls import reverse
def get_absolute_url(self):
return reverse('product_details', args=[self.id])
您可以在定义get_absolute_url
的模型中执行此操作,并在模板上保持原样,现在单击它将重定向到特定对象