Django

⌘K
  1. Home
  2. Django
  3. Django তে কিভাবে কাজ করতে...
  4. Views
  5. 03. class-based views

03. class-based views

class-based views (CBVs) কি?

class-based views (CBVs) ফাংশনের পরিবর্তে একজন Django Developer একেকটি View এর জন্য একেকটি Python Class ব্যবহার করবে, 

from django.shortcuts import render
from django.views import View
from django.http import HttpResponse

class HelloView(View):
    def get(self, request):
        return HttpResponse("Hello, World!")

class HelloNameView(View):
    def get(self, request, name):
        return HttpResponse(f"Hello, {name}!")

urls.py

# myapp/urls.py
from django.urls import path
from .views import HelloView, HelloNameView

urlpatterns = [
    path('hello/', HelloView.as_view(), name='hello'),
    path('hello/<str:name>/', HelloNameView.as_view(), name='hello_name'),
]

আমরা চাইলে একটা ভিউ এর মধ্যে দুইটা ইউআরএল প্যারামিটার ছাড়া ও প্যারামিটার সহ ব্যবহার করতে পারি।

# myapp/views.py
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse

class HelloView(View):
    def get(self, request, name=None):
        if name:
            return HttpResponse(f"Hello, {name}!")
        else:
            return HttpResponse("Hello, World!")

urls.py

# myapp/urls.py
from django.urls import path
from .views import HelloView

urlpatterns = [
    path('hello/', HelloView.as_view(), name='hello'),
    path('hello/<str:name>/', HelloView.as_view(), name='hello_name'),
]

You can test it with the same URLs as before:

http://localhost:8000/myapp/hello/YourName/ for the “Hello, YourName!” view.

http://localhost:8000/myapp/hello/ for the “Hello, World!” view.

How can we help?