Home > database >  How to loop trough objects in html
How to loop trough objects in html

Time:12-24

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 >

<h1>Filter</h1><hr>
{% for category in categorys%}
  <p >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)

CodePudding user response:

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

CodePudding user response:

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 >

<h1>Filter</h1><hr>
{% for category in categories%}
  <p >Hello</p>
  <h1>AAAAAAAAAAAAAAA</h1>
{% endfor %}

</div>

Explanations:

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

  • Related