Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Django ListView – How to Create Function and Class-Based ListViews?

Django Project And App Structure

In this article, we will learn about Django ListViews.

What is a Django ListView?

Django ListView refers to that type of view which shows the instances/ elements present in a Model Table. It is used to display the multiple entries present in the Database and also allows us to add up new data.

Therefore, you can infer that ListView is based on the API interface having the GET and POST option.

This is similar to the ItemsView that we created in our series Django REST API.

Pre-requisites for coding ListViews

Consider a Django Project having an App Itemsapp. Here we will have Model saving information about items like chair, book, table, etc.

The code for the Model:

class ItemModel(models.Model):
    id = models.IntegerField(primary_key = True)
    name = models.CharField(max_length = 80, blank = False)
    price = models.IntegerField
 
    class Meta:
        ordering = ['name']
 
    def __str__(self):
        return f"{self.name}:{self.price}"

We will then create the table in the pre-set database SQLite using the terminal:

python manage.py migrate
python manage.py makemigrations
python manage.py migrate

After that we will have the serializers.py file, having an ItemSerializer Class to convert DB instances into JSON.

The code for ItemSerializer:

from rest_framework import serializers
from .models import ItemModel

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = ItemModel
        fields = ['id',name','price']

After that, just add a few items into the table via The Python shell or The admin Site itself.

Admin
Admin

Also, the Endpoint will be simply /items since List Views focus on displaying the entire instances of the Model Table

The code for the URL mapping:

  • For Function-Based List View
path ('items/', ItemsView)
  • For Class-Based List View
path('items/',ItemView.as_view())

That’s it, now we will learn to create a ListView in different ways.

The Logic Behind Django ListView

In a ListView API, the logic is very simple.

1. Data display from Server to User

The steps involved will be:

  1. Get data from DB 
  2. Convert the Data into JSON using Serializers
  3. Return the JSON data to the user either as it is or via a template(using JS)

2. Take data from User to Server

The steps involved here will be:

  1. Separate JSON data from the rest of the request(Using JSON Parser)
  2. Convert into Django-readable format(python methods)
  3. perform the dedicated Task(add, edit, delete) on that piece of Data.

In this case, the dedicated task can just be to display or to add the data from the user into the DB.

Creating a Django ListView

Let’s create a Django Listview now.

1. Function-Based ListView

Sample code for a function based ListView here will be:

@csrf_exempt
def ItemsView(request):
 
    if request.method == 'GET':
        items = ItemsModel.objects.all()
        serializer = ItemSerializer(items, many =True)
        return JsonResponse(serializer.data, safe =False)
 
    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer =ItemSerializer(data = data)
 
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data,status =201)
        return JsonResponse(serializer.errors,status = 400)

Remember the steps given in the above section that we perform with a ListView API and try to understand the code. 

  1. def get: Data from DB → Convert to JSON(serializer) →show the JSON data
  2. def post: Parse the request to separate JSON data → Convert to Python format → Perform the appropriate Task on the data

This is what we did, in the code for ItemsView.

2. Class-Based ListView

Class-based views are better than function views since using classes the code becomes more systematic, structured, and readable.

Sample code for a Class-Based ListView here will be:

class ItemsView(APIView):
    def get(self,request,format =None):
        items = ItemsModel.objects.all()
        serializer = ItemSerializer(items, many =True)
        return JsonResponse(serializer.data, safe =False)

    def post(self,request,format =None):
        data = JSONParser().parse(request)
        serializer =ItemSerializer(data = data)

        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data,status = status.HTTP_201_CREATED)
        return JsonResponse(serializer.errors,status = status.HTTP_400_BAD_REQUEST)

Again here as well, just the way we write the code changes. We use Class methods and in-class functions to write the code. But the crux of the logic remains the same.

Implementation of the ListView API

The code is done, we will now run it.

You can try running both the Function Based views and Class-Based Views for your better understanding of the function and class-based ListViews

Now for running, we will use POSTMAN, which is an efficient way to run Django REST APIs. Here is the official website of POSTMAN, where you can look upon its benefits

GET ListView
GET ListView

The above Pic shows the GET option of the ListView, where it is displaying all the instances of the ItemModel.

POST ListView
POST ListView

This pic shows the POST option of the ListView, which allows user to add new item instance into the ItemModel.

Conclusion

That’s it, Fellas !! This is what a ListView in Django does. Take the instances of the models and display them and as well take up new instances from the user.

In the next article, we will learn about Django Detail View.

Stay tuned for more such interesting topics !! Stay safe !!