Display Views - ListView
The view is a display view representing a list of objects, identified by self.object_list
.
For the same example as earlier, if you want to list all the articles available for a specific date, the ListView
can be used instead of DetailView
from django.views.generic.list import ListView
...
class ArticleListView(ListView):
model = Article
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['now'] = timezone.now()
return context
The URL conf definition is the same as previous.
urlpatterns = [
path('', ArticleListView.as_view(), name='article-list'),
]
The article headlines can be listed in an HTML file article_list.html
by looping through the list of article objects as shown.
<ul>
{% for article in object_list %}
<li>{{ article.pub_date|date }} - {{ article.headline }}</li>
{% empty %}
<li>No articles yet.</li>
{% endfor %}
</ul>
No comments:
Post a Comment
If you have any doubts, Please let us know.