hello i am new here.
I have a concern about for loop counter, it counts but conversely what I wanted here is the code:
{% for product, range, nSlides in allProds %}
{{product.0.0.category}}({{forloop.counter}})
{% endfor %}
normally it should return to me like this:
Bag(2) accessory(1)
but it returns to me like this:
Bag(1) accessory(2)
how can I solve this problem. thank you in advance
Hi!
About the counter, you might want to use the forloop.counter0
, which starts counting from 0. Docs
About the Bag number, what’s the content of product.0.0.category
?
PD: When posting code here, please encapsulate it between 3 backticks (```). That way it will be easier for everyone to read. Thanks!
thanks for reply,
I have already tried with ‘’‘forloop.counter0’’’ but the result remains indisputable. ‘’‘product.0.0.category’’’ is the relation of product and category
Let me ask, why are you accessing the category of a product like that? I assume something like:
>>> p = Product.objects.first()
>>> p.category
(Shows the category related to that product)
Anyway, you changed the loop to counter0
and the result was the same? I’m not sure what do you mean by indisputable.
Hello,
Excuse me for poorly trained English,
in my index view I do like this:
prod = Product.objects.all()
allProds = []
catprods = Product.objects.values('category', 'product_id')
cats = {item['category'] for item in catprods}
for cat in cats:
prod = []
for p in [i for i in Product.objects.filter(category=cat)]:
prod.append([p])
n = len(prod)
nSlides = 5
allProds.append([prod[::-1], range(1, nSlides), nSlides])
params = {
'sliders':Slider.objects.all(),
'allProds':allProds,
'category':category.objects.all(),
}
return render(request, 'store/index.html', params)```
this is why I am using this code:
``` {% for product, range, nSlides in allProds %}
<a href="/products/{{product.0.0.category}}">{{product.0.0.category}}({{forloop.counter}})</a>
{% endfor %}```,
and thank you again sincerely
Hi Erwan, can you show us the __str__
or __repr__
method for category
? I want to know what’s actually printing out Bag(1) accessory(2)
. Specifically what does {{product.0.0.category}}
render in the template by itself.
thank you CODENAME but my problem i already find the soultion, excuse me for the delay and thanks for all answered me