我的布尔if语句出错(Django)

时间:2018-06-22 23:00:27

标签: python django if-statement boolean

我正在建立一个如下表:

<table>
    <tr>
        <th>List of car parts available:</th>
    </tr>
    <tr>
        <th>Name</th>
        <th>Price</th>
    </tr>
    {% for product in products_list %}
    <tr>
      <td>{{ product.name }}</td>
      <td>${{ product.price }}</td>
      <td>{% if product.in_cart == False: %}
              <a href="products/cart/">Add to cart</a>
          {% else %}
              {{ print('')}}
      </td>
    </tr>
    {% endfor %}
  </table>

我想说的是,如果in_cart的产品值是False(表示它不在购物车中),请在购物车网址中添加一个链接。

但是我收到此错误:无法从'False:'解析剩余的':'

然后,如何将其值更改为true?

这是我的观点

def index(request):
    products_list = Product.objects.all()
    template = loader.get_template('products/index.html')
    context = {'products_list': products_list}
    return HttpResponse(template.render(context, request))

def cart(request):
    cart_list = Product.objects.filter(in_cart = True)
    template_cart = loader.get_template('cart/cart.html')
    context = {'cart_list': cart_list}
    return HttpResponse(template_cart.render(context, request))

谢谢!

2 个答案:

答案 0 :(得分:1)

不应将冒号:添加到if语句中。 Here's example how to use Django if in templates

{% if not product.in_cart %}也会看起来更好;)

答案 1 :(得分:0)

Django模板不允许这种语法if product.in_cart == False:以冒号:结尾,就像Python一样,()括号都不起作用

请尝试以下操作:

{% if not product.in_cart %} 
    <a href="products/cart/">Add to cart</a>
{% else %}
    {{ print('')}}{{ print }}
{% endif %}

别忘了以if结尾endif语句

Django Documentation会有所帮助,看看!!!