← Back to Django Course | Chapter 9: Class-Based Views | Lesson 1 of 10

Class-Based Views का परिचय

एक class-based view एक recipe card जैसा है जिसे already पता है कि कई dishes कैसे cook करनी हैं, इसलिए आप सिर्फ ingredients बदलते हैं पूरा recipe फिर से लिखने के बजाय।
Syntax
markup
from django.views import View

class ViewName(View):
    def get(self, request):
        return HttpResponse('content')

# urls.py
path('route/', ViewName.as_view(), name='url_name')

Function-Based vs Class-Based Views

एक function-based view एक plain Python function है जो एक request लेता है और एक response return करता है। एक class-based view एक Python class है जो वही काम करती है पर logic को get() और post() जैसे methods में organize करती है, जिन्हें Django उपयोग किए गए HTTP method के आधार पर अपने आप call करता है।

Note: दोनों approaches valid Django हैं; CBVs shine करती हैं जब एक view को similar pages के across logic reuse करनी हो।

उदाहरण: Function-Based vs Class-Based Views

The function and the class both handle a GET request the same way, but the class organizes behavior by HTTP method name.

markup
from django.http import HttpResponse
from django.views import View


def home_fbv(request):
    return HttpResponse('Hello from a function-based view')


class HomeCBV(View):
    def get(self, request):
        return HttpResponse('Hello from a class-based view')
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

`as_view()` से एक CBV Wire करना

Class-based views को urls.py में directly reference नहीं किया जा सकता क्योंकि Django के URL resolver को एक callable function चाहिए, एक class नहीं। ClassName.as_view() call करना एक function return करता है जिसे Django हर request के लिए call कर सकता है, जो internally class का एक instance बनाता है और right method पर dispatch करता है।

Warning: .as_view() में parentheses भूल जाना एक बहुत आम mistake है — as_view एक method है, attribute नहीं।

उदाहरण: Wiring a CBV with as_view()

HomeCBV.as_view() converts the class into something Django's URL dispatcher can call directly.

markup
from django.urls import path
from .views import HomeCBV

urlpatterns = [
    path('home/', HomeCBV.as_view(), name='home'),
]
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

कई HTTP Methods Handle करना

एक class-based view हर HTTP verb के लिए अलग methods define कर सकती है जो यह support करती है। Django का dispatch() method, View से inherited, incoming request को request.method के आधार पर अपने आप get(), post(), put(), delete(), और इसी तरह पर route करता है।

Note: यह GET और POST logic को visually separate रखता है एक बड़े if/else block में tangled होने के बजाय।

उदाहरण: Handling Multiple HTTP Methods

Django calls get() for GET requests and post() for POST requests on the same URL automatically.

markup
from django.http import HttpResponse
from django.views import View


class ContactCBV(View):
    def get(self, request):
        return HttpResponse('Show the contact form')

    def post(self, request):
        return HttpResponse('Contact form submitted')
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}

Django Generic CBVs क्यों देता है

Objects list करने, एक object दिखाने, या एक create/update/delete form handle करने के लिए एक view लिखना almost हर app में same pattern follow करता है। Django built-in generic class-based views (ListView, DetailView, CreateView, UpdateView, DeleteView) ships करता है जो इस pattern को implement करते हैं इसलिए आपको सिर्फ model और template supply करना है।

Note: इस chapter के बाद के tutorials हर generic view को individually cover करते हैं।

उदाहरण: Why Django Provides Generic CBVs

This tiny class replaces a function view that would otherwise manually query Book.objects.all() and render a template.

markup
from django.views.generic import ListView
from .models import Book


class BookListView(ListView):
    model = Book
    template_name = 'books/book_list.html'
{# Django-only code -- models.py/views.py/urls.py/settings.py snippets, or template markup using Django template tags/variables -- can't run standalone via Judge0 or the browser preview, since it needs a real Django project. Only this course's pure-Python examples (example_lang == 'python', no Django imports) are actually runnable, so those still get the button below. #}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. urls.py में एक class-based view wire करते समय .as_view() call करना भूल जाना, जो एक TypeError का कारण बनता है।
  2. get() या post() को override करना पर जब अब भी ज़रूरत हो तो parent implementation call करना भूल जाना।
  3. यह assume करना कि एक class-based view बिल्कुल एक function-based view जैसी behave करती है बिना यह पढ़े कि यह असल में कौन से methods call करती है।
चैप्टर सारांश
  • Class-based views (CBVs) view logic को एक function के बजाय एक Python class के रूप में package करती हैं।
  • Django common tasks के लिए built-in generic CBVs देता है जैसे listing, showing, creating, updating, और deleting objects।
  • हर CBV urls.py में ClassName.as_view() उपयोग करके connected है।
  • CBVs copy-pasted function code की बजाय inheritance और mixins के through reuse को favor करती हैं।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.