Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Introduction to Django Views

This guide will explore how to use views in Django as a data display and viewing tool. It will also explore the two major types of views: class-based and function-based views.

Oct 28, 2020 • 7 Minute Read

Introduction

In the model view controller (MVC) architecture, the view component deals with how data is presented to users for consumption and viewing. In the Django framework, views are Python functions or classes that receive a web request and return a web response. The response can be a simple HTTP response, an HTML template response, or an HTTP redirect response that redirects a user to another page. Views hold the logic that is required to return information as a response in whatever form to the user. As a matter of best practice, the logic that deals with views is held in the views.py file in a Django app.

This guide will explore how to use views in Django as a data display and viewing tool. It will also explore the two major types of views: class-based and function-based views. It assumes that you have at least beginner level knowledge of Django and a general understanding of the Django MVC. An introductory guide to Django can be found here.

Sample App

To better understand views, consider a Django app for a sports inventory. The model has details about the sports items being stored. Below is a snippet for the model.

      from django.db import models

class Inventory(models.Model):
    item = models.CharField(max_length=20)
    item_code = models.IntegerField()
    item_condition = models.CharField(max_length=50)
    def __str__(self):
        return self.item
    

Class-based Views (Generic)

Class-based views allow you to create views from inherited classes, thus making coding the views much easier. Generally, there are five types of common class-based views (generic) that perform the CRUD (create, retrieve, update, delete) operations for any common web app. All of these views involve operating on data via a model instance. At all times, a model instance is provided.

List View

As the name suggests, the list view generates a list of items in the model from the database. Here is a sample list view class for the sports inventory app.

      from django.views.generic import ListView
from . models import Inventory
class SportsItemListView(ListView):
    model = Inventory
    # a html file that will display a list of all the items in inventory model
    template_name = 'sports/items.html' 
    context_object_name = 'items' # how the list will be referred to in the html template
    

DetailView

The detailview command is used to display the data for a single record from the database. Here is sample code for a detail view to display a single record from the Inventory table in your app.

      from django.views.generic import DetailView
from . models import Inventory

class SportsItemDetailView(DetailView):
    model = Inventory
    template_name = 'book/detail.html'
    context_object_name = 'item'
    

CreateView

createview creates a new record in the database using the model instance.

      from django.views.generic import CreateView
from . models import Inventory
from django.urls import reverse_lazy

class ItemCreateView(CreateView):
    model = Inventory
    template_name = 'sports/create_item.html'
    fields = ('item', 'item_code', 'item_condition', )
    success_url = reverse_lazy('sports-list')
    

UpdateView

The updateview command performs an update operation to an existing record in the database.

      from django.views.generic import UpdateView
from . models import Inventory
from django.urls import reverse_lazy

class ItemUpdateView(UpdateView):

    model = Inventory
    template_name = 'sports/update.html'
    context_object_name = 'item'
    fields = ('item', 'item_code', 'item_condition', )

    def get_success_url(self):
        return reverse_lazy('item-detail', kwargs={'pk': self.object.id})
    

Delete View

deleteview is used to perform a delete operation on a single record in the database via the specified model.

      from django.views.generic import DeleteView
from . models import Inventory
from django.urls import reverse_lazy

class ItemDeleteView(DeleteView):
    model = Inventory
    template_name = 'sports/delete.html'
    success_url = reverse_lazy('item-list')
    

Function-based Views

Function-based views are functions that return an HTTP response after executing the required business logic of a certain view.

Simple HTTP Response

This is used in cases where the message is very simple—maybe just short text—important, and the presentation does not matter. The code snippet below demonstrates a function-based view returning a simple HTTP response.

      from django.http import HttpResponse

def simple_http_response(request):
    # perform business logic
    return HttpResponse("Hello world from Django !")
    

HTTP Response Redirect

This redirect is used when the logic requires that after execution, the user is redirected to another view. An example would be after deleting a record in a detail view, the page redirects to the home page.

      from django.http import HttpResponseRedirect
from django.urls import reverse

def delete_item(request, id):
    #perform delete operation successfully
    return HttpResponseRedirect(reverse('url_name_of_homepage'))
    

Template Response

A template response is used when the response is complex and may require further processing on the HTML side, such as displaying multiple records via looping. This use case also requires proper presentation, so it allows rendering of a HTML file.

      from django.shortcuts import render
def simple_template(request):
    # perform business logic
    return render(request, "sports/simple_template.html", {})
    

Conclusion

Mastering views is an important aspect of web development, especially using MVC frameworks like Django. This vital skill is beneficial for Python developers holding the role of Django developer, backend engineer, or full-stack engineer in their places of work.

To further build on this guide, research more about the views used in APIs. This will likely involve research on the Django Rest Framework (DRF)—more specifically, the APIView class.

As a challenge, finish up the above app for a sports inventory business. Add appropriate URLs to all the views created and design simple HTML pages for displaying the data. This guide will give you a good idea of how to navigate this task.