List view

List view

List view: Django features us various built in fuctionalities, ListView is one of them. The application remains incomplete  till there is no interaction with some database. In our previous tutorial, we have discussed about Template view, for more details you can visit the link below:

Django Class Based Views

  • We’ve learned how to use CBVs to directly show a template, but what about models?
  • Often when we have models, we want to either list the records from the model, or show details of a single record.
  • Previously we did this with calls using the Object Relation Mapper directly
  • This included things like:
    • MyModel.objects.all()
  • However these sort of operations are very common!
  • Django has some generic view classes you can inherit to very quickly display information from your model.
  • This is where the power of CBV comes to help us out!

What we will do next?

In this tutorial, now we are going to create List view of our models.

  • Now we will quickly create:
    • New Models
    • New Templates
  • Then we will focus on:
    • ListView
    • DetailView

List view example process:

  1. Create model inside models.py file
  2. Register model inside admin.py file
  3. Setup views to display list of model data
  4. Add new folders template/appName  inside app folder
  5. Create HTML file inside this template folder
  6. Setup URL file to actually display HTML file
  7. Run server and check output
  8. Here is my directory tree:
list view
list view

Let’s start to perform all above mentioned steps:

Step 1: Create model inside models.py file

Let’s create an model inside app folder. It is an most important part to create an model for practicing list views and detail views. Here i am creating a new model named Collage. This model contains following fields:

  1. Name
  2. Principal Name
  3. Location
  4. Contact Number
  5. Registered At

Moreover, we will create a list view which contains list of all collage. You can return anything, here i am going to return name of the collage. Here is the code for doing so:

CBV > cbvapp > models.py

from django.db import models

class Collage(models.Model):
    name = models.CharField(max_length=250)
    principal_name = models.CharField(max_length=250)
    location = models.CharField(max_length=200)
    contact_no = models.PositiveIntegerField()
    registered_at = models.DateField(auto_now_add=True,null=True)

    def __str__(self):
        return self.name

Step 2: Register model inside admin.py file

It is short but important part to register models in admin.py. So, don’t forget it. Here is the code for the admin.py :

CBV > cbvapp > admin.py

from django.contrib import admin
from cbvapp.models import Collage

admin.site.register(Collage)
Note: Don’t forget to make migrations for changes in model. For your reminder, here are the commands for the same:
python managr.py makemigrations AppName

and then

python manage.py migrate

Step 3: Setup views to display list of model data

Now, it is our main part of code. Crete Class Based View to show model data list. Here we will directly show the HTML template rather than using render() function. Here is the code for doing the same:

CBV > cbvapp > models.py

from django.shortcuts import render
from django.views.generic import View,TemplateView,ListView
from .models import Collage

class MyCBV(TemplateView):
    template_name= 'index.html'

class collageList(ListView):
    context_object_name = 'collages_list'
    model = Collage

Explanation

  • Here are two views, first is for index page and second is for List view
  • In index page, there is same HTML template which is in our previous tutorial. (You can see in link above)
  • The second page is which contain collage list(which we are going to create) i.e. collageList view.
  • Here is also an base page, which contains navigation bar. All pages inherits from that base page.
  • Navigation bar contains following links:
    • Home
    • Collage List
    • Admin page
  • where admin is Django’s administration.

Step 4: Add new folders template/appName inside app folder

As you can see in Directory tree above, i have added a new folder named templates inside app folder.

  • Previously we’ve been putting all our templates inside the templates folder within the matching app folder.
  • However it is also common practice to do the “reverse”, have a template folder inside the app’s folder.
  • Create a new file named collage_list.html inside app_folder > template > app_name folder.
  • Here is the coding for all HTML pages:

CBV > template_folder > base.html

<!DOCTYPE html>
{% load staticfiles %}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <title>Mysite</title>
  </head>
  <body>
    <div class="container-fluid">
      <div class="row">
        <div class="col-md-12 px-0">
          <nav class='navbar navbar-expand-sm bg-dark navbar-dark'>
            <a href="{% url "cbvapp:list" %}" class='navbar-brand'>Collages</a>
            <ul class='navbar-nav mx-auto'>
              <li class='nav-item'>
                <a href="#" class='nav-link'>Home</a>
              </li>
              <li class='nav-item'>
                <a href="{% url "admin:index" %}" class='nav-link'>Admin</a>
              </li>
            </ul>
          </nav>
        </div>
      </div>
    </div>
    <div class="container-fluid">
      {% block body_block %}

      {% endblock %}
    </div>
  </body>
</html>

CBV > template_folder > index.html

{% extends "base.html" %}
{% block body_block %}
<div class="row" style='height:400px;background:url("http://www.compassproperties.com/wp-content/uploads/2018/02/city-square2.jpg");background-size:100% 100%;'>
  <div class="col-md-12 px-0">
    <section>
      <div class="text-center text-white pt-5">
        <h1 class='display-1'><strong>It is awesome</strong> </h1>
        <p class=''>It is a paragraph</p>
      </div>
    </section>
  </div>
</div>
<div class="row">
  <div class="col-md-12 my-5 text-center text-warning">
    <h1>Who we are</h1>
  </div>
  <div class="col-md-12">
    <div class="row">
      <div class="col-md-4">
        <p>This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.</p>
      </div>
      <div class="col-md-4">
        <p>This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.</p>

      </div>
      <div class="col-md-4">
        <p>This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.This is a paragraph.</p>

      </div>
    </div>
  </div>
</div>
{% endblock %}

Step 5: Create HTML file inside this template folder

Now i am going to actually create HTML page to show data inside models. It is also extends from the base page i.e. Navigation bar. Here is the code:

CBV > cbvapp > template > cbvapp > collage_list.html

{% extends "base.html" %}
{% block body_block %}
<div class="row">
    <div class="col-md-12">
      <h1 class='text-warning'>Here is the list of collages</h1>
      <ul class='list-group'><ol>
        {% for collage in collages_list %}
        <li>  <li class='list-group-item'>{{ collage.name }}</li></li>
        {% endfor %}
      </ol>
      </ul>
    </div>
</div>
{% endblock %}

Step 6: Setup URL files to actually display HTML page

  1. First of all setup main project’s URL file.
  2. Main URL file contains an include() function which includes app’s URL.
  3. Then set URL which is inside app folder.
  4. Here is the code for both files:

CBV > CBV > urls.py

from django.contrib import admin
from django.urls import path,include
from cbvapp import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.MyCBV.as_view()),
    path('cbvapp/',include('cbvapp.urls')),
]

CBV > cbvapp > urls.py

from django.conf.urls import url
from cbvapp import views

app_name='cbvapp'

urlpatterns = [
    url('collageList/',views.collageList.as_view(),name='list')
]

Step 7: Run server and check output

So now everything is setup now, you may get an basic idea of MTV (settings Model Template Views). Check output using the command below:

Note: Don’t forget to create superuser and add data to models

# Command to create superuser
python manage.py createsuperuser

# Runserver
python manage.py runserver

OUTPUT

INDEX PAGE
list view
list view
COLLAGE LIST PAGE
list view
list view

Download source code

Download project on Github
Download project on Github 

So, it is all about List view. Furthermore, if you want to learn about detail view then you can visit the link below. Thanks!!!

Detail View

16 thoughts on “List view

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. This is very interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your excellent post. Also, I’ve shared your web site in my social networks!

  2. Thanks , I’ve just been looking for info about this topic for a long time and yours is the greatest I’ve discovered till now. But, what concerning the conclusion? Are you certain concerning the source?

  3. Wonderful goods from you, man. I’ve understand your stuff previous to and you are just too magnificent. I actually like what you have acquired here, certainly like what you are saying and the way in which you say it. You make it entertaining and you still care for to keep it wise. I can not wait to read much more from you. This is really a great site.

  4. hey there and thank you for your information – I’ve definitely picked up anything new from right here. I did however expertise some technical points using this site, as I experienced to reload the website many times previous to I could get it to load properly. I had been wondering if your web hosting is OK? Not that I’m complaining, but slow loading instances times will often affect your placement in google and can damage your high quality score if advertising and marketing with Adwords. Well I’m adding this RSS to my e-mail and can look out for much more of your respective interesting content. Make sure you update this again very soon..

  5. I simply want to say I am newbie to weblog and truly liked your web-site. Very likely I’m want to bookmark your blog post . You certainly have impressive posts. Cheers for revealing your web-site.

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.