Table of contents
1.
Introduction
2.
What is function-based List View?
3.
When to use function-based List View?
4.
Sample Django App
5.
Frequently Asked Questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

Function-Based List View in Django

Author Sneha Mallik
3 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Views in Django are Python functions or classes that receive a web request and return a web response in the Django framework. A basic HTTP response, an HTML template response, or an HTTP redirect response that transfers a user to another page are all possible responses. Django views provide the logic required to return information to the user in any manner. The logic that deals with views should be kept in the ‘views.py’ file as a best practice in a Django app. 

The list view accesses the database to create a list of model elements. A Django list view is a sort of view that displays the elements/instances in a model table. This is used to display the many entries in the database and add new information.

What is function-based List View?

List View in Django is a view (logic) that allows you to list all or specific instances of the table from the database in a particular order. It shows various data on a single page or view, such as products on an e-commerce site. Django provides exceptional List View functionality.

The function-based list view has many lines of code and can be converted to a class-based list view.

 

This blog focuses on the function-based list view in Django, which includes Django Models. We will work on a project with models and multiple instances to display the function-based List View. 

When to use function-based List View?

Django includes several generic views based on functions to help with common tasks. List View is one of them.

So, we should use List View when we wish to display or view a list of objects on an HTML page.

List View should not be used when our page has forms and creates or updates objects. Form View, Create View, and Update View are better for working with forms, object creation, and object updation.

Sample Django App

Consider establishing a model from which we'll create instances through our view after we have a project and an app. 

In the Ninja/models.py file,

# To import the Django Model from the in-built library
from django.db import models

 
# To declare the new model with the name "NinjaModel"
class NinjaModel(models.Model):
   
   # The fields of the Ninjamodel
  name = models.CharField(max_length = 150)
  description = models.TextField()
   
   # To rename the instances of the Ninjamodel with their name
  def __str__(self):
      return self.name
You can also try this code with Online Python Compiler
Run Code

 

After creating this model, we'll need to run two commands to establish a database.

python3 manage.py makemigrations
python3 manage.py migrate

 

Now, using shell, let's make some instances of this model, run from bash.

python3 manage.py shell

 

We will enter the following command in the python shell.

>>> from Ninja.models import NinjaModel
>>> NinjaModel.objects.create(name="Sneha",description="Student 1").save()
>>> NinjaModel.objects.create(name="John",description="Student 2").save()
>>> NinjaModel.objects.create(name="Rajiv",description="Student 3").save()
>>> NinjaModel.objects.create(name="Sammy",description="Student 4").save()
You can also try this code with Online Python Compiler
Run Code

 

We will then create a view and a template. The view file will be in the path Ninja/views.py:

from django.shortcuts import render

 
# To import the forms
from .models import NinjaModel

 
def list_view(request) :
   
   # The dictionary for data initialization with field names as the keys
  context ={}
   
   # It has to be added to the dictionary during field initialization
  context["dataset"] = NinjaModel.objects.all()   
  return render(request, "list_view.html", context)
You can also try this code with Online Python Compiler
Run Code

 

We will then create the template in templates/list_view.html.

<div class="main">
  {% for data in dataset %}.
  
  {{ data.name }} - {{ data.description }}
  <br/>
  <hr/>
  
  {% endfor %}
</div>

 

Upon running the following command, we can see the output at ‘http://127.0.0.1:8000/’.

python3 manage.py runserver
You can also try this code with Online Python Compiler
Run Code

 

Output

 

Frequently Asked Questions

  1. What are views in Django?
    Views in Django are an essential feature of the Django MVT(Model-View-Template) Structure. According to the Django documentation, a view function is a Python function that takes a Web request and delivers a Web response. This response could be the HTML content of a Web page, a redirect, a 404 error, an XML document, an image, or anything else that a web browser can display.
     
  2. How many forms of list views does Django have?
    Function-based list views and class-based list views are the two forms of list views in Django.
     
  3. Why is list view preferred over template view?
    Template view can do everything list view can however, list view has the advantage of not requiring as much boilerplate code as template view would.
    List view would save us several lines of code while also providing better separation of concern.
     
  4. List down some pros and cons of the function-based list view.

Pros

Cons

  • Implementation is simple.
  • Easy to read the code.
  • The code flow is explicit.
  • The usage of decorators is straightforward.
  • The code cannot be reused.
  • It is hard to extend the code.
  • The handling of HTTP methods is done via conditional branching.

 

Key Takeaways

In this blog, we have learned the concepts of function-based list views in Python, which generates a list of model items from the database and is easier to read the code. Views are crucial for web development, especially when utilizing MVT(Model View Template) frameworks like Django. Filtered items can also be displayed or ordered in numerous ways based on specific criteria in List View.

Go through The Basics of Django Framework to deeply understand the concept of Django to get a hold of the function-based list view in Django

 

Credits: GIPHY

Happy Developing!

Live masterclass