Hello, anyone has idea on compare two variables in template system? Someone used ifequal
, but it has deprecated since version 3.1.
Thanks!
Hello, anyone has idea on compare two variables in template system? Someone used ifequal
, but it has deprecated since version 3.1.
Thanks!
Doesn’t the ==
operator work? The docs say that ifequal is the obsolete way of saying ==
.
oh, I see. I should wrote my question with more detail. So I was trying to generate a products list in a page, the list was under a brand, so I tried to pass a brand name as a
keyword argument to the url
and want to compare the keyword argument with the brand field
of products to get the queryset of the products of specific brand.
From this description, this isn’t something you would do in the template - this is work more appropriately done in a view.
You don’t want to mix your processing logic with your templates.
Yes, you are right! I tried on view, and didn’t figure out how to compare variables in query set like in filter
, so I turned to template by using {% if product.brand == brandtag %}, but that’s not working, so I tried put those variable in {{product.brand}} and {{brandtag}} in template, they both showed up properly.
To be more clear, this is my code sample below, could you take a look what’s issue of my code is?
*Model.py*
class Brand(models.Model):
name = models.CharField(max_length=20)
class Products(models.Model)
...
brand = models.ForeignKey(Brand,on_delete=models.PROTECT)
...
*urls.py*
urlpatterns = [
...
path('brand/<brandtag>', products_page.as_view(), name='products_page'),
...
]
*views.py*
class products_page(ListView):
model = Products
template_name = "core/products_page.html"
*products_page.html*
{% for product in products_list %}
{% if product.brand == brandtag %}
<p class="card-text">{{product.title}}</p>
<p class="card-text">{{product.price}}</p>
{% endif %}
{% endfor %}
Since you’re using ListView, you’ll want to create a get_queryset method for that class that filters Products by brandtag.
Thanks, I’ll learn more about filter
first.