Types of Views in Django

  • By Sagar Gade
  • February 20, 2025
  • Django
Types of Views in Django

Types of Views in Django

In Django, views are a central concept that handles the logic of processing a request and returning a response. Views are functions or classes that receive a web request, process data (often by interacting with models), and return a web response, typically HTML, JSON, or other types of data. Here’s a detailed breakdown of Types of Views in Django:

 

1. Types of Views

  • Function-based Views (FBVs): These are views that are defined using regular Python functions. They are straightforward to write and read, especially for small and simple logic.
  • Class-based Views (CBVs): These views use classes and methods to encapsulate the request-handling logic. They offer greater reusability, and organization, and can be more modular for complex views.

 

2. Function-Based Views (FBVs)

Example:
from django.http import HttpResponse

from django.shortcuts import render

 

def my_view(request):

    # Logic goes here

    return HttpResponse(‘Hello, world!’)

  • Details:
    • The request object contains all the HTTP request information.
    • The HttpResponse object is used to return a response.
    • FBVs are great for simple logic, such as rendering a template, handling a form, or doing simple data retrieval.

Rendering Templates with FBV:
def home_view(request):

    context = {‘message’: ‘Welcome to Django’}

    return render(request, ‘home.html’, context)

  • The render() function combines a template with a context dictionary to produce an HttpResponse object.

 

3. Class-Based Views (CBVs)

  • CBVs are organized using classes and methods, making them more modular and allowing for the reuse of common behaviors.
  • Django provides generic views like ListView, DetailView, CreateView, etc., which handle common patterns for database interaction.

Example of a CBV:
from django.views import View

from django.http import HttpResponse

 

class MyView(View):

    def get(self, request):

        return HttpResponse(‘Hello from a class-based view!’)

  • Details:
    • The View class is imported from django.views, and it provides methods like get(), post(), put(), delete(), etc., corresponding to HTTP methods.
    • A CBV is typically more structured, allowing you to separate logic for each type of HTTP request (e.g., GET vs POST).
  • Using Generic CBVs: Django offers several built-in generic views that reduce the need to write common view logic from scratch.

Example: ListView
from django.views.generic import ListView

from .models import Book

 

class BookListView(ListView):

    model = Book

    template_name = ‘book_list.html’

    context_object_name = ‘books’

    • ListView is used to display a list of objects from a model.
    • template_name specifies the template file to render.
    • context_object_name defines the variable name in the template for the list of objects.
  • Other Common Generic Views:
    • DetailView: For displaying a single object.
    • CreateView: For creating a new object.
    • UpdateView: For updating an existing object.
    • DeleteView: For deleting an object.

 

4. Mixins

  • CBVs can be extended using mixins, which are classes that add additional behavior.
  • Mixins help to keep code DRY (Don’t Repeat Yourself) by allowing shared functionality across different views.

Example:
from django.contrib.auth.mixins import LoginRequiredMixin

from django.views.generic import ListView

from .models import Book

 

class BookListView(LoginRequiredMixin, ListView):

    model = Book

    template_name = ‘book_list.html’

  • Here, LoginRequiredMixin ensures that a user must be logged in to access the view.

 

For Free, Demo classes Call: 020-71177359

Registration Link: Click Here!

 

5. URL Routing to Views

  • Views need to be connected to URLs in the urls.py file to be accessible from a web browser.

Example:
from django.urls import path

from .views import my_view, BookListView

 

urlpatterns = [

    path(‘my-view/’, my_view, name=‘my_view’),

    path(‘books/’, BookListView.as_view(), name=‘book_list’),

]

  • The path function maps a URL pattern to a view function or a class-based view using the as_view() method.

 

6. Handling HTTP Methods

FBVs use conditional statements to handle different HTTP methods:
def my_view(request):

    if request.method == ‘GET’:

        return HttpResponse(‘GET request’)

    elif request.method == ‘POST’:

        return HttpResponse(‘POST request’)

  • CBVs have specific methods like get(), post() for different HTTP methods, making the code more structured.

 

7. Returning JSON Responses

  • Views can also return JSON responses, which is common when building APIs.

Example:
from django.http import JsonResponse

 

def json_view(request):

    data = {‘name’: ‘Django’, ‘type’: ‘Framework’}

    return JsonResponse(data)

  • JsonResponse is useful for returning JSON data directly from a view.

 

8. Rendering Templates

  • In both FBVs and CBVs, the render() function is commonly used for rendering templates.

Example:
from django.shortcuts import render

 

def index_view(request):

    return render(request, ‘index.html’, {‘title’: ‘Home Page’})

 

Summary of Django Views:

  • FBVs are simpler to read and ideal for smaller applications or straightforward logic.
  • CBVs are more organized and modular, which is beneficial for larger applications with more complex views.
  • Django’s generic CBVs and mixins help to streamline common tasks, such as creating, updating, or deleting objects.
  • Proper routing through urls.py connects views to specific URL patterns.

Do visit our channel to learn More: Click Here

 

Author:-

Sagar Gade

Call the Trainer and Book your free demo Class for Django Call now!!!

| SevenMentor Pvt Ltd.

© Copyright 2021 | SevenMentor Pvt Ltd