Table of contents
1.
Introduction
2.
Creating and using Views in Django
3.
Class-based Views (Generic)
3.1.
Sample Django App
3.2.
The List View
3.3.
The Detail View
3.4.
The Create View
3.5.
The Update View
3.6.
The Delete View
4.
Function-based Views
4.1.
Simple HTTP Response
4.2.
HTTP Response Redirect
4.3.
Template Response
5.
Frequently Asked Questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

Views in Django

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

Introduction

The view component of the MVT(Model View Template) architecture is responsible for presenting data to users for viewing and consumption. 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 that is required to return information to the user in any manner. The logic that deals with the views in Django application should be kept in the ‘views.py’ file as a best practice.

This blog will help you use views in Django to display and view the data. It will also look at two main types of views: class-based views and function-based views.

Creating and using Views in Django

Using an example, let us demonstrate how to construct and use a Django view. Let us consider a project called codingNinjas, which has a ‘student’ app.

We can construct a view in student/views.py after we have the project codingNinjas ready.

views.py:

from django.shortcuts import render
from django.http import HttpResponse
def student_show(request):
  x = []
  for i in range(15):
      x.append(i+1)
  return HttpResponse("<h1>Welcome to Coding Ninjas</h1>The Digits are: {0}".format(x))
You can also try this code with Online Python Compiler
Run Code

 

The resulting response is returned as a HttpResponse object by the view. An HttpResponse object is always returned by each view function.

In student/urls.py, let us get this view to work.

urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
  path('admin/', admin.site.urls),
  path('student/', include('student.urls')),
]
You can also try this code with Online Python Compiler
Run Code

Output

Class-based Views (Generic)

Class-based views enable us to create views by generating them from inherited classes. In general, any common web application has five standard class-based views(generic) that perform the CRUD(create, retrieve, update, and delete) operations. These views require using a model instance to interact with the data. A model instance is available at all times.

Views can be implemented as Python objects instead of functions using class-based views. They do not replace function-based views, but they do have several advantages and differences when compared to the function-based views:

  • Rather than conditional branching, different methods can organize code relevant to various HTTP methods (GET, POST, etc.).
  • Mixins(multiple inheritances) and other object-oriented approaches can factor the code into reusable components.
  • Class-based views are much easier to manage and more efficient than function-based views. The function-based view with many lines of code can be transformed into the class-based view with only changing a few lines of code. OOP(Object-Oriented Programming) comes into play here.

Sample Django App

Consider a Django app for musical Instruments to understand views better. The model contains information on the musical instruments that are being saved. A snippet for the model is given as the following.

from django.db import models

class Musical(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
You can also try this code with Online Python Compiler
Run Code

 

The five sorts of standard class-based views in Django are:-

The List View

As the name implies, the list view generates a list of model items from the database. For the music app, here is a sample list view class.

from django.views.generic import ListView
from . models import Musical
class MusicItemListView(ListView):
    model = Musical
    # html file that will display list of all the items in a musical model
    template_name = 'music/items.html' 
    context_object_name = 'items' # how the list will be referred to in the HTML template
You can also try this code with Online Python Compiler
Run Code

The Detail View

The ‘detail view’ command shows a specific database record data. Here's the code for displaying a single record from your app's Inventory database in a ‘detail view’.

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

class MusicItemDetailView(DetailView):
    model = Musical
    template_name = 'instrument/detail.html'
    context_object_name = 'item'
You can also try this code with Online Python Compiler
Run Code

The Create View

‘Create view’ uses the model instance to generate/create a new record in the database.

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

class ItemCreateView(CreateView):
    model = Musical
    template_name = 'music/create_item.html'
    fields = ('item', 'item_code', 'item_condition', )
    success_url = reverse_lazy('music-list')
You can also try this code with Online Python Compiler
Run Code

The Update View

The ‘update view’ command changes an existing database record.

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

class ItemUpdateView(UpdateView):

    model = Musical
    template_name = 'music/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})
You can also try this code with Online Python Compiler
Run Code

The Delete View

The ‘delete view’ method is used to delete a single record from a database using the provided model.

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

class ItemDeleteView(DeleteView):
    model = Musical
    template_name = 'music/delete.html'
    success_url = reverse_lazy('item-list')
You can also try this code with Online Python Compiler
Run Code

Function-based Views

Function-based views produce an HTTP response after executing a view's required business logic.

Function-based views are created with a Python function that takes an HttpRequest object as an input and returns a HttpResponse object. There are four primary approaches for function-based views: CRUD (Create, Retrieve, Update, Delete) is the foundation of any framework for development.

Simple HTTP Response

This method is utilized when the message is relatively simple—perhaps only has a few lines of text—and the presentation is not vital. The code snippet below demonstrates the function-based view returning a simple HTTP response.

from django.http import HttpResponse

def simple_http_response(request):
    # perform the business logic
    return HttpResponse("Welcome to Coding Ninjas!")
You can also try this code with Online Python Compiler
Run Code

HTTP Response Redirect

This HTTP Response Redirect is used when the logic demands the user to be redirected to another view after execution. The page redirects to the home page after deleting a record in a detail view.

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

def delete_item(request, id):
    # performs the delete operation successfully
    return HttpResponseRedirect(reverse('url_name_of_homepage'))
You can also try this code with Online Python Compiler
Run Code

Template Response

When the response is complicated and requires further HTML processing, such as looping to display several records, a template response is utilized. This use case also requires correct presentation, allowing the HTML file rendering.

from django.shortcuts import render
def simple_template(request):
    # performs the business logic
    return render(request, "music/simple_template.html", {})
You can also try this code with Online Python Compiler
Run Code

Frequently Asked Questions

  1. What do you mean by HTTP decorators of views in Django?
    HTTP decorators of views in Django are used to limit access to a view based on the method of request. 
    These HTTP decorators are listed in ‘django.views.decorators.http’. If the conditions aren't met, ‘django.http.HttpResponseNotAllowed’ is returned.
    Syntax for HTTP decorators: require_http_methods(request_method_list)
     
  2. Explain what happens when a typical Django website receives a request.
    When users type a URL into their browser, the Django Server receives the exact URL request.
    The server then checks its URL-config for a match to the requested URL, and if it does, it returns the appropriate view function.
    If any data is required, it will request it from the Model of that application and give it to the corresponding template, which is subsequently rendered in the browser; otherwise, a 404 error will be issued.
     
  3. What comprises Django's architecture?
    The MVT architecture is used by Django. The components that make up the Django architecture are as follows:
    Models: Models are used to describe backend elements such as database schema. (relationships)
    View: The user interface is what we see when we render a website in our browser. HTML/CSS/Javascript and Jinja files are used to represent it.
    Template: The template comprises both static sections of the desired HTML output and specific syntax that describes how dynamic content will be included.

Key Takeaways

In this blog, we have learned the concepts of views in Django in Python. Views are crucial for web development, especially when utilizing MVT frameworks like Django. This essential ability is beneficial for Python developers who work as Django developers, backend engineers, or full-stack engineers.

Go through The Basics of Django Framework to deeply understand the concept of Django. 

Credits: GIPHY

Happy Developing!

Live masterclass