• RubyonRails
  • Struts
  • jQuery
  • Spring
  • Servlet
  • JSP
  • PHP
  • JavaScript
  • Core Java

  • <

    Django Generic ListView

    In this tutorial we will learn django generic listview.Django Generic listview also known as class based view. Class based view is simple compare to function based view.

    Let's create a Project ListView project to understand deeply.

    Django ListView Example

    Create a django project testapp using Pycharm IDE.Then create an app by following command

    In Pycharm IDE press these keys to appear run option CTRL+ALT+R..

    python manage.py startapp newtest

    After that a new folder was created this is application folder newtest.

    Edit settings.py file from project folder and add app name in INSTALLED_APPS .


    Edit urls.py file inside application folder

    Place following code in urls.py file under project folder


    Here include() function to include and refer to the application's urls.py file.

    from django.contrib import admin
    from django.urls import path,include
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('test', include('newtest.urls')),


    View function is defined in views.py file .Here the view function is PersonList .Django import generic view module django.views.generic.list import ListView .

    Copy and Paste following code to your views.py file .

    from django.views.generic.list import ListView 
    from .models import Person
    class PersonList(ListView):
        # specify the model for list view 
        model = Person


    Create django admin username and password using command createsuperuser .Then provide username,email and password .

    Edit admin.py file and register models .

    from django.contrib import admin
    from .models import Person
    # Register your models here.


    Django model is collection of database with different types of fields,tables and various constraints

    from django.db import models 
    class Person(models.Model):
        name = models.CharField(max_length = 100)
        age = models.IntegerField()
        def __str__(self): 
            return self.name


    urls.py file contains the relative path to the template .

    from django.urls import path
    from .views import PersonList
    urlpatterns = [
            path('', PersonList.as_view()),

    Django ListView Template

    In django generic listview each view class define there own template name.Here class name is Person then _list, .html.

        <!-- Iterate over object_list -->
        {% for object in object_list %} 
        <!-- Display Objects -->
        <li>{{ object.name }}</li>
        <li>{{ object.age }}</li>
        <!-- If objet_list is empty  -->
        {% empty %} 
        <li>No objects yet.</li> 
        {% endfor %} 




    © copyright 2017-2021 Completedone pvt ltd.