The Wayback Machine - https://web.archive.org/web/20241001063648/https://www.geeksforgeeks.org/views-in-django-python/
Open In App

Views In Django | Python

Last Updated : 04 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Django Views are one of the vital participants of the MVT Structure of Django. As per Django Documentation, A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, a redirect, a 404 error, an XML document, an image, or anything that a web browser can display. 

Django Views

Django views are part of the user interface — they usually render the HTML/CSS/Javascript in your Template files into what you see in your browser when you render a web page. (Note that if you’ve used other frameworks based on the MVC (Model-View-Controller), do not get confused between Django views and views in the MVC paradigm. Django views roughly correspond to controllers in MVC, and Django templates to views in MVC.)

Django Views

Illustration of How to create and use a Django view using an Example. Consider a project named geeksforgeeks having an app named geeks. 

Refer to the following articles to check how to create a project and an app in Django.
 

After you have a project ready, we can create a view in geeks/views.py,

Python3
# import Http Response from django
from django.http import HttpResponse
# get datetime
import datetime

# create a function
def geeks_view(request):
    # fetch date and time
    now = datetime.datetime.now()
    # convert to string
    html = "Time is {}".format(now)
    # return response
    return HttpResponse(html)

Let’s step through this code one line at a time: 

  • First, we import the class HttpResponse from the django.http module, along with Python’s datetime library.
  • Next, we define a function called geeks_view. This is the view function. Each view function takes an HttpRequest object as its first parameter, which is typically named request.
  • The view returns an HttpResponse object that contains the generated response. Each view function is responsible for returning an HttpResponse object.

For more info on HttpRequest and HttpResponse visit – Django Request and Response cycle – HttpRequest and HttpResponse Objects
Let’s get this view to working, in geeks/urls.py,

Python3
from django.urls import path

# importing views from views..py
from .views import geeks_view

urlpatterns = [
    path('', geeks_view),
]

Now, visit http://127.0.0.1:8000/.

django-view-example

To check how to make a basic project using MVT (Model, View, Template) structure of Django, visit Creating a Project Django.

Django Class Based Views vs Function Based Views

Django views are divided into two major categories:

  • Function Based Django Views
  • Class Based Django Views

Class Based Views vs Function Based Views


 

Function Based Views in Django

Function based views are written using a function in python which receives as an argument HttpRequest object and returns an HttpResponse Object. Function based views are generally divided into 4 basic strategies, i.e., CRUD (Create, Retrieve, Update, Delete). CRUD is the base of any framework one is using for development. 

How to use Function based view in Django?

Let’s Create a function-based view list view to display instances of a model. Let’s create a model of which we will be creating instances through our view. In geeks/models.py,

Python3
# import the standard Django Model
# from built-in library
from django.db import models
 
# declare a new model with a name "GeeksModel"
class GeeksModel(models.Model):

    # fields of the model
    title = models.CharField(max_length = 200)
    description = models.TextField()

    # renames the instances of the model
    # with their title name
    def __str__(self):
        return self.title

After creating this model, we need to run two commands in order to create Database for the same.

Python manage.py makemigrations
Python manage.py migrate

Now let’s create some instances of this model using shell, run form bash,

Python manage.py shell

Enter following commands

>>> from geeks.models import GeeksModel
>>> GeeksModel.objects.create(
                       title="title1",
                       description="description1").save()
>>> GeeksModel.objects.create(
                       title="title2",
                       description="description2").save()
>>> GeeksModel.objects.create(
                       title="title2",
                       description="description2").save()

Now if you want to see your model and its data in the admin panel, then you need to register your model.
Let’s register this model. In geeks/admin.py,

Python3
from django.contrib import admin
from .models import GeeksModel
# Register your models here.
admin.site.register(GeeksModel)

Now we have everything ready for the back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/ 

django-listview-check-models-instances


Let’s create a view and template for the same. In geeks/views.py,

Python3
from django.shortcuts import render

# relative import of forms
from .models import GeeksModel


def list_view(request):
    # dictionary for initial data with 
    # field names as keys
    context ={}

    # add the dictionary during initialization
    context["dataset"] = GeeksModel.objects.all()
        
    return render(request, "list_view.html", context)

Create a template in templates/list_view.html,

html
<div class="main">

    {% for data in dataset %}.

    {{ data.title }}<br/>
    {{ data.description }}<br/>
    <hr/>

    {% endfor %}

</div>

Let’s check what is there on http://localhost:8000/

django-listview-function-based


Similarly, function based views can be implemented with logics for create, update, retrieve and delete views.

Django CRUD (Create, Retrieve, Update, Delete) Function Based Views :-

Class Based Views in Django

Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views: 

  • Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching.
  • Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components.


Class-based views are simpler and efficient to manage than function-based views. A function-based view with tons of lines of code can be converted into class-based views with few lines only. This is where Object-Oriented Programming comes into impact.  

How to use Class based view in Django?

In geeks/views.py,

Python3
from django.views.generic.list import ListView
from .models import GeeksModel

class GeeksList(ListView):

    # specify the model for list view
    model = GeeksModel

Now create a URL path to map the view. In geeks/urls.py,

Python3
from django.urls import path

# importing views from views..py
from .views import GeeksList
urlpatterns = [
    path('', GeeksList.as_view()),
]

Create a template in templates/geeks/geeksmodel_list.html,

html
<ul>
    <!-- Iterate over object_list -->
    {% for object in object_list %}
    <!-- Display Objects -->
    <li>{{ object.title }}</li>
    <li>{{ object.description }}</li>

    <hr/>
    <!-- If objet_list is empty  -->
    {% empty %}
    <li>No objects yet.</li>
    {% endfor %}
</ul>

Let’s check what is there on http://localhost:8000/
 

django-listview-class-based-views


Django CRUD (Create, Retrieve, Update, Delete) Class Based Generic Views :-



Similar Reads

Built-in Error Views in Django
Whenever one tries to visit a link that doesn't exist on a website, it gives a 404 Error, that this page is not found. Similarly, there are more error codes such as 500, 403, etc. Django has some default functions to for handle HTTP errors. Let's explore them one-by-one. Built-in Error Views in Django - 404 view (page not found) - Normally this vie
3 min read
Render a HTML Template as Response - Django Views
A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This article revolves around how to render an HTML page from Django using views. Django has always been known for its app structure and ability to manage applications easily. Let's dive in to see how to render a template file through
3 min read
Create View - Function based Views Django
Create View refers to a view (logic) to create an instance of a table in the database. It is just like taking an input from a user and storing it in a specified table. Django provides extra-ordinary support for Create Views but let's check how it is done manually through a function-based view. This article revolves around Create View which involves
3 min read
Update View - Function based Views Django
Update View refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database for example, updating an article at geeksforgeeks. So Update view must display the old data in the form and let user update the data from there only. Django provides extra-ordinary s
4 min read
Detail View - Function based Views Django
Detail View refers to a view (logic) to display a particular instance of a table from the database with all the necessary details. It is used to display multiple types of data on a single page or view, for example, profile of a user. Django provides extra-ordinary support for Detail Views but let's check how it is done manually through a function-b
3 min read
Delete View - Function based Views Django
Delete View refers to a view (logic) to delete a particular instance of a table from the database. It is used to delete entries in the database for example, deleting an article at geeksforgeeks. So Delete view must show a confirmation message to the user and should delete the instance automatically. Django provides extra-ordinary support for Delete
3 min read
List View - Function based Views Django
List View refers to a view (logic) to list all or particular instances of a table from the database in a particular order. It is used to display multiple types of data on a single page or view, for example, products on an eCommerce page. Django provides extra-ordinary support for List Views but let's check how it is done manually through a function
3 min read
Createview - Class Based Views Django
Create View refers to a view (logic) to create an instance of a table in the database. We have already discussed basics of Create View in Create View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differ
3 min read
ListView - Class Based Views Django
List View refers to a view (logic) to display multiple instances of a table in the database. We have already discussed the basics of List View in List View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain
4 min read
UpdateView - Class Based Views Django
UpdateView refers to a view (logic) to update a particular instance of a table from the database with some extra details. It is used to update entries in the database, for example, updating an article at geeksforgeeks. We have already discussed basics of Update View in Update View – Function based Views Django. Class-based views provide an alternat
3 min read
DetailView - Class Based Views Django
Detail View refers to a view (logic) to display one instances of a table in the database. We have already discussed basics of Detail View in Detail View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain dif
3 min read
DeleteView - Class Based Views Django
Delete View refers to a view (logic) to delete a particular instance of a table from the database. It is used to delete entries in the database for example, deleting an article at geeksforgeeks. We have already discussed basics of Delete View in Delete View – Function based Views Django. Class-based views provide an alternative way to implement vie
3 min read
FormView - Class Based Views Django
FormView refers to a view (logic) to display and verify a Django Form. For example, a form to register users at Geeksforgeeks. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based v
3 min read
Class based views - Django Rest Framework
Class-based views help in composing reusable bits of behavior. Django REST Framework provides several pre-built views that allow us to reuse common functionality and keep our code DRY. In this section, we will dig deep into the different class-based views in Django REST Framework. This article assumes you are already familiar with Django and Django
12 min read
Function based Views - Django Rest Framework
Django REST Framework allows us to work with regular Django views. It facilitates processing the HTTP requests and providing appropriate HTTP responses. In this section, you will understand how to implement Django views for the Restful Web service. We also make use of the @api_view decorator. Before working on Django REST Framework serializers, you
13 min read
Raw SQL queries in Django views
Let's create a simple Django project that demonstrates the use of raw SQL queries in a view. In this example, we'll create a project to manage a list of books stored in a database. We'll create a view that retrieves books from the database using a raw SQL query and displays them on a webpage. Setting up the projectWe assume that Django is already i
4 min read
Django Function Based Views
Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks. Django is based on MVT (Model View Template) architecture and revolves around CRUD (Create, Retrieve, Update, Delete) operations. CRUD can be best explain
7 min read
Django Class Based Views
Django is a Python-based web framework that allows you to quickly create web applications. It has a built-in admin interface which makes it easy to work with it. It is often called a Class-Based included framework because it provides built-in facilities for every functionality. Class Based Generic Views are an advanced set of Built-in views that ar
10 min read
Class Based vs Function Based Views - Which One is Better to Use in Django?
Django...We all know the popularity of this python framework all over the world. This framework has made life easier for developers. It has become easier for developers to build a full-fledged web application in Django. If you're an experienced Django developer then surely you might have been aware of the flow of the project. How things run in the
7 min read
Python - Obtain title, views and likes of YouTube video using BeautifulSoup
In this article, we will learn how can we obtain data (like title, views, likes, dislikes etc) from any YouTube video using a Python script. For this task, we are going to use very famous library for web scraping BeautifulSoup and Requests. Modules required and Installation : Requests : Requests allows you to send HTTP/1.1 requests extremely easily
2 min read
GUI to get views, likes, and title of a YouTube video using YouTube API in Python
Prerequisite: YouTube API, Tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this art
2 min read
Adding Tags Using Django-Taggit in Django Project
Django-Taggit is a Django application which is used to add tags to blogs, articles etc. It makes very easy for us to make adding the tags functionality to our django project.Setting up Django Project Installing django-taggit pip install django-taggitADD it to Main Project's settings.py file C/C++ Code INSTALLED_APPS = [ 'django.contrib.admin', 'dja
2 min read
How to customize Django forms using Django Widget Tweaks ?
Django forms are a great feature to create usable forms with just few lines of code. But Django doesn't easily let us edit the form for good designs. Here, we will see one of the ways to customize Django forms, So they will look according to our wish on our HTML page. Basically we will check the methods to include our own custom css, classes, or id
3 min read
Styling Django Forms with django-crispy-forms
Django by default doesn't provide any Django form styling method due to which it takes a lot of effort and precious time to beautifully style a form. django-crispy-forms solves this problem for us. It will let you control the rendering behavior of your Django forms in a very elegant and DRY way. Modules required:django : django installdjango-crispy
1 min read
Integrating Django with Reactjs using Django REST Framework
In this article, we will learn the process of communicating between the Django Backend and React js frontend using the Django REST Framework. For the sake of a better understanding of the concept, we will be building a Simple Task Manager and go through the primary concepts for this type of integration between React js and Django. Reactjs in a nuts
15+ min read
How to Fix Django "ImportError: Cannot Import Name 'six' from 'django.utils'"?
After Django 3.0, django.utils.six was removed. The "ImportError: Cannot Import Name 'six' from 'django.utils'" error occurs because of the dependency issue. This happens because when the project tries to use something that’s no longer available. Don’t worry—it’s easy to fix. We’ll explain why this error happens and give you simple steps to solve i
3 min read
Creating views on Pandas DataFrame
Many times while doing data analysis we are dealing with a large data set, having a lot of attributes. All the attributes are not necessarily equally important. As a result, we want to work with only a set of columns in the dataframe. For that purpose, let's see how we can create views on the Dataframe and select only those columns that we need and
2 min read
Creating views on Pandas DataFrame | Set - 2
Prerequisite: Creating views on Pandas DataFrame | Set - 1 Many times while doing data analysis we are dealing with a large data set has a lot of attributes. All the attributes are not necessarily equally important. As a result, we want to work with only a set of columns in the dataframe. For that purpose, let's see how we can create views on the D
2 min read
Pafy - Getting Views Count of the Video
In this article we will see how we can get the view counts of the given youtube video in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. View counts is basically the number of views the video has, view count represents how large the
2 min read
Python | User groups with Custom permissions in Django
Let's consider a trip booking service, how they work with different plans and packages. There is a list of product which subscriber gets on subscribing to different packages, provided by the company. Generally, the idea they follow is the level-wise distribution of different products. Let's see the different packages available on tour booking servi
4 min read
Article Tags :
Practice Tags :