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

Django DetailView – How to Create Detail Views in Django?

Django Detail View

In this article we will learn about Django DetailView.

What is a Django DetailView?

Django DetailView refers to that type of view that shows a single instance from the Model Table. It is used to display the information about a single entry from the database and also to carry out different tasks on that instance.

Prerequisites for Django DetailView

The prerequisites for this topic are the exact same as the ones listed in our ListView article. The codes for the pre-requisites are added below, you can go through them.

If you feel for the need for an explanation, do go through the pre-requisites listed in the ListView article and then you can continue with creating the Django Detail view here.

ItemModel in Models.py

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}"

ItemSerializer in Serializers.py

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

URL endpoint for Detail View

Also, the Endpoint will be simply /item/<id> since Detail Views focuses on displaying just the instance from DB having a particular id.

The code for the Url mapping:

path('item/<id>', ItemView.as_view())

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

Code Logic for Detail View

In the previous article, you saw logic for ListView. Detail Views also has its logic to get the <id> from the endpoint request and then perform the necessary tasks further.

This is similar to ListView but has some changes in its basic format since we are dealing with the endpoint data here.

First, we will do to get the endpoint data, which is basically the item id that the user will send along with the request.

Code Logic for Server to User interaction

The logic is simple and can be understood after going through the steps outlined below:

  1. Using the id, we got before, retrieve the item information from the DB.
  2. Convert the information into JSON format using serializers.
  3. Show it to the user via a template or directly as a JSON.

The basic flowchart is given below:

Code Logic for User to Server interaction

This logic is kind of a backward process to what we did in the above section.

  1. Segregate(Parse) the JSON data from the rest of the request.
  2. JSON data taken from the user has to be converted into a Django readable format(python-dictionary) using serializers
  3. Make the necessary changes(add, edit, delete) to the item, whose id was sent in the endpoint request.

The basic flowchart is given below:

Creating a Django DetailView

1. Function-Based Detail View

Sample code for a function based DetailView here will be:

@csrf_exempt
def ItemView(request,nm):
    try: 
        item = ItemsModel.objects.get(id = nm)
    except ItemsModel.DoesNotExist:
        raise Http404('Not found')
 
    if request.method == 'GET':
        serializer = ItemSerializer(item)
        return JsonResponse(serializer.data)
 
    if request.method == 'PUT':
        data = JSONParser().parse(request)
        serializer = ItemSerializer(item,data =data)
 
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status =400)
 
    if request.method == "DELETE":
        item.delete()
        return HttpResponse(status =204)

Just remember the steps given in the above section that we perform with a DetailView API and try to understand the code. 

  1. Get the id from endpoint request
  2. try-except block: if the item exists then get object information from DB and save it in a variable item.
  3. def GET: Convert item variable into JSON(serializer) →show the JSON data
  4. def PUT: Parse the request to separate JSON data → Convert to Python format → update the data regarding the item in the DB
  5. def DELETE: delete the item from the Database.

2. Class-Based Detail View

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 DetailView here will be:

class ItemView(APIView):
     
    def get_objects(self,nm):
        try: 
            return ItemsModel.objects.get(id = nm)
        except ItemsModel.DoesNotExist:
            raise Http404('Not found')
 
    def get(self,request,nm,format =None):
        item = self.get_objects(nm)
        serializer = ItemSerializer(item)
        return JsonResponse(serializer.data)
 
    def put(self,request,nm,format =None):
        item = self.get_objects(nm)
        data = JSONParser().parse(request)
        serializer = ItemSerializer(item,data = data)
 
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status = status.HTTP_400_BAD_REQUEST)
 
    def delete(self,request,nm,format=None):
        item = self.get_objects(nm)
        item.delete()
        return HttpResponse(status =status.HTTP_204_NO_CONTENT)

Again here as well, the way to write the code just changes. We use Class methods and in-class functions( The try-except block is inside a separate class function in this case) to write the code. But the crux of the logic remains the same.

Implementation of the DetailView API

That’s it. We’re pretty much done with the code and it’s time to run a few tests for this demonstration.

Let’s try running both the function-based and class-based views.

We will use POSTMAN to run REST APIs. The official website of POSTMAN talks about the benefits of the tool. Let’s move ahead with our demonstration here.

GET Item
GET Item

In the above screenshot, you can see GET in action. We display the “id 1” data pulled from the database

PUT Item
PUT Item

The above screenshot demonstrates PUT.

DELETE Item
DELETE Item

Have a look at how the command output looks when we run the DELETE command on top of it.

Conclusion

That’s it, fellas!! This is what a DetailView in Django does. Take a single instance from the model based on the request data(<id>) and then display it, add, edit or delete the item instance from the DB.

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