0

I want to loop through my categories in my html. I am making a filter that will show all of the categories but i cant get my {% for %} to work i need some help heres my code. Ask if theres any more info that you need to solve this.

HTML:

<div class="filter-box">

<h1>Filter</h1><hr>
{% for category in categorys%}
  <p class="checkbox-text">Hello</p>
  <h1>AAAAAAAAAAAAAAA</h1>
{% endfor %}

</div>

Views:

def category_all(request):
categorys = Category.objects.all()
return render(request, "product/dashboard_test.html", {"names": categorys})
    

Models:

class Category(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=255, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

2 Answers 2

1

Try the following code, it should work for you.

Code:

Python Code:

def category_all(request):
    categories = Category.objects.all()
    context = {
        'categories': categories
    }
    return render(request, "product/dashboard_test.html", context=context)

HTML Code:

<div class="filter-box">

<h1>Filter</h1><hr>
{% for category in categories%}
  <p class="checkbox-text">Hello</p>
  <h1>AAAAAAAAAAAAAAA</h1>
{% endfor %}

</div>

Explanations:

{"names": categorys} this implementation is not correct.

Sign up to request clarification or add additional context in comments.

4 Comments

Nope, nothing changed again...
Do you have data in Category table??
No i dont... why? Do i need it?
Without data it will not execute for loop in html
1

Looks like you are passing in a template variable "names" and then in the template you are trying to call it "categorys"
Change this line:

return render(request, "product/dashboard_test.html", {"names": categorys})

to this:

return render(request, "product/dashboard_test.html", {"categorys": categorys})

Also categorys is spelled categories, not that it effects your code

2 Comments

Nothing changed, its the same
If "categorys" is empty then the loop has nothing to loop through, hence nothing is printed. In Django you can also add a {% empty %} tag before {% endfor %} and in between these tags you can put the html that should display when there are no categories to display

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.