Home > OS >  For loop on Django Template
For loop on Django Template

Time:07-06

I'm having a huge issue on making for loop on django templates,for some reasone it dont show on the page the categories that i create on database

urls.py

app_name = 'statenews'
urlpatterns = [
path('', views.home, name="home"),
path('', views.category, name = 'category'),]

models.py

class Category(models.Model):
    name = models.CharField(max_length=65)
   ...

class News(models.Model):
   ...
category = models.ForeignKey(
        Category, on_delete=models.SET_NULL, null=True, blank=True,
        default=None,
    )

views.py

def category(request):
categories = Category.objects.all()
return render(request,'partials/footer.html',{
    'categories': categories
})

html template

<div >
        <h4 >Tags</h4>
        {% for category in categories %}
        <div >

            <a href="" >({category.name})</a>

        </div>
        {% endfor %}
    </div>

CodePudding user response:

You have two url paths with same url. Change it to:

urlpatterns = [
    path('', views.home, name="home"),
    path('categories', views.category, name = 'category')
]

Then enter via yourdomain.com/categories. Otherwise it will always show home view.

EDIT:

In you homepage you can simply see home view as it is set in url with ''. If you want to see categories as footer part, then you have to change your home template, render it with {% include 'partials/footer.html' %}. Then you have to pass categories in home view context.

  • Related