List View – Class Based Views Django

List View refers to a view (logic) to display multiple instances of a table in the database. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views.

After you have a project and an app, let’s create a model of which we will be creating instances through our view.



from django.db import models

# Create your models here.

class Article(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField(blank=True, default="")
    slug = models.SlugField(max_length=200)
    published = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('-published',)

    def __str__(self):
        return self.title


After creating this model, we need to run two commands in order to create Database for the same.


Python manage.py makemigrations
Python manage.py migrate

Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create ListView for, then Class based ListView will automatically try to find a template in app_name/modelname_list.html or you can use template_name


       template_name = "folder/template2.html"


class ArticleList(ListView):
	model = Article
	template_name = 'blogpost/article.html'
	context_object_name = 'blogs'

Now create a url path to map the view.


from django.urls import path
from . import views

urlpatterns = [
       path('list', views.ArticleList.as_view(), name='articlelist'),
]

Create a template in templates/blogpost/article.html,


    
    {% for object in blogs %} 
    
    {{ object.title }} 
    {{ object.body }}  
    
    {% empty %} 
    No objects yet. 
    {% endfor %} 

Since we have given context_object_name = 'blogs', we will have to iterate over


       {% for object in blogs %} 

If context_object_name = 'blogs' was not specified, then


       {% for object in object_list %} 

Latest Blog