I can't find where is the problem, so I want to create li element for each of my categories. Here are my codes:
views.py:
def categories(request):
context = {
'category_list': Category.objects.all(),
}
return render(request, 'base.html', context)
base.html:
<nav id="header-nav">
<ul id="nav-ul" class="menu font-reg clearfix">
<li class="menu-item menu-item-has-children">
<a href="">Blog<span class="sub-drop-icon fa fa-angle-down"></span></a>
<ul class="sub-menu sub-menu-first">
{% for category in category_list %}
<li><a href="#">{{ category.name }}</a></li>
{% endfor %}
</ul>
</li>
<li class="menu-item menu-item-has-children">
<a href="about-1.html">About</a>
</li>
<li class="menu-item menu-item-has-children">
<a href="contact-1.html">Contact</a>
</li>
</ul>
</nav>
urls.py:
urlpatterns = [
path('', views.index),
path('article/<slug:article_slug>', views.article, name='article'),
]
Category class:
class Category(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length=20)
To show the article and categories on the same page, you can do as follows:
urls.py
urlpatterns = [
path('', views.index),
path('article/<slug:article_slug>', views.article, name='article'),
]
models.py
It's better to put def __str__
below all the fields.
class Category(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
views.py
You need to pass the article and the categories in one view.
def article(request, slug):
context = {
'article': Article.objects.get(slug=slug),
'category_list': Category.objects.all()
}
return render(request, 'base.html', context)
base.html
To show a list of categories:
{% for category in category_list %}
<li><a href="#">{{ category.name }}</a></li>
{% endfor %}
Note:
It will have much more sense to create a separate article.html
page with {% extends 'base.html' %}
line in the beginning to render your article. Moreover, pay attention to Class-based views for simple rendering lists and detail info for instances of your Models.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.