【问题标题】:I am trying to print a cart with prices in Django我正在尝试在 Django 中打印带有价格的购物车
【发布时间】:2016-11-01 14:43:54
【问题描述】:

当我传递上下文时,另一端似乎无法使用它,为了使其更简单并举个例子,我将尝试传递我所有的产品并简单地列出所有产品 id 的列表,它不起作用,当我访问该页面时,我得到的只是一个空白页面。

views.py

def cart(request):
items = [1,2,3,4]
template = loader.get_template("Cafe/cart.html")
ip = get_client_ip(request)
order = current_order.objects.order_by('id')
products = product.objects.order_by('id')
context = {
    'order': order,
    'products': products,
    'items': items
}
return HttpResponse(template.render(request))

cart.html

    <head>
{% load static %}
{% load app_filters %}
<link rel="stylesheet" type="text/css" href="{% static 'Cafe/stylesheet.css' %}" />
</head>
<body>
  {% for product in products %}
    <a>{{product.id}}</a>
  {% endfor %}
</body>

models.py

class product(models.Model):
    categories = (
        ('HD', 'Hot Drink'),
        ('CD', 'Cold Drink'),
        ('Br', 'Breakfast'),
        ('Sa', 'Sandwich'),
        ('Ex', 'Extras'),
        ('Sp', 'Specials'),
    )
    product_name = models.CharField(max_length=100)
    category = models.CharField(max_length=2, choices=categories, default=categories[0][0])
    price = models.FloatField()

我没有看到为什么这不应该起作用的原因,因为相同的概念适用于我制作的所有其他页面。

【问题讨论】:

    标签: python django


    【解决方案1】:

    不要像这样渲染你的模板:

    return HttpResponse(template.render(request))
    

    你可以这样做:

    ...
    context = {'order': order, 'products': products, 'items':items}
    return render(request, "cafe/cart.html", context)
    

    现在你的context 变量在渲染任何东西时都没有被使用,所以你不能在模板中访问它。像这样使用render 并提供上下文字典将使您能够访问字典中的所有项目,就像您期望的那样。

    【讨论】:

    • 完美,只是完全错过了作为参数的上下文!我知道它会那么小!
    猜你喜欢
    • 2016-10-29
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 2013-02-18
    相关资源
    最近更新 更多