Interview question
What are Django Views? Explain Function-Based Views (FBV) vs Class-Based Views (CBV). Django Views क्या हैं? Function-Based Views (FBV) vs Class-Based Views (CBV) explain करें।
Answer
Views are Python functions/classes that receive requests and return responses. FBV are simple functions for straightforward logic, while CBV use classes with methods for complex reusable logic. CBV provides inheritance, mixins, and built-in HTTP method handling.
// FUNCTION-BASED VIEWS (FBV)
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from .models import Product
from .forms import ProductForm
# Simple view
@require_http_methods(['GET', 'POST'])
def product_list(request):
if request.method == 'POST':
form = ProductForm(request.POST)
if form.is_valid():
form.save()
return redirect('product_list')
else:
form = ProductForm()
products = Product.objects.all()
return render(request, 'products/list.html', {
'products': products,
'form': form
})
# Detail view with URL parameter
def product_detail(request, product_id):
try:
product = Product.objects.get(id=product_id)
return render(request, 'products/detail.html', {'product': product})
except Product.DoesNotExist:
return render(request, '404.html', status=404)
// CLASS-BASED VIEWS (CBV)
from django.views import View
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
# Generic view for listing
class ProductListView(ListView):
model = Product
template_name = 'products/list.html'
context_object_name = 'products'
paginate_by = 10
def get_queryset(self):
return Product.objects.filter(is_active=True)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['total_products'] = self.get_queryset().count()
return context
# Generic view for detail
class ProductDetailView(DetailView):
model = Product
template_name = 'products/detail.html'
context_object_name = 'product'
pk_url_kwarg = 'product_id'
# Generic view for creation
class ProductCreateView(LoginRequiredMixin, CreateView):
model = Product
form_class = ProductForm
template_name = 'products/form.html'
success_url = reverse_lazy('product_list')
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
# Generic view for update
class ProductUpdateView(UpdateView):
model = Product
form_class = ProductForm
template_name = 'products/form.html'
pk_url_kwarg = 'product_id'
def get_success_url(self):
return reverse('product_detail', args=[self.object.id])
// Custom Class-Based View
class ProductAPIView(View):
def get(self, request, product_id=None):
if product_id:
product = Product.objects.get(id=product_id)
return JsonResponse({
'id': product.id,
'name': product.name,
'price': str(product.price)
})
else:
products = list(Product.objects.values('id', 'name', 'price'))
return JsonResponse({'products': products})
def post(self, request):
# Handle POST
data = request.POST
product = Product.objects.create(**data)
return JsonResponse({'id': product.id})
// urls.py
from django.urls import path
from . import views
urlpatterns = [
# FBV routes
path('products/', views.product_list, name='product_list'),
path('products/<int:product_id>/', views.product_detail, name='product_detail'),
# CBV routes
path('api/products/', views.ProductListView.as_view(), name='product_list_cbv'),
path('api/products/<int:pk>/', views.ProductDetailView.as_view(), name='product_detail_cbv'),
path('api/products/create/', views.ProductCreateView.as_view(), name='product_create'),
]
// FBV vs CBV Comparison
// FBV Advantages:
// - Simple and straightforward
// - Direct control over logic
// - Easy for small views
// - Good for beginners
// CBV Advantages:
// - Reusable code
// - Inheritance and mixins
// - DRY principle
// - Built-in generic views
// - HTTP method separation
// - Better for complex applicationsDjango Views:
FBV (Function-Based Views):
@app.route('/products/')
def product_list(request):
# Get data
# Process
# Return response
Simple, easy to understand
Direct control
CBV (Class-Based Views):
class ProductListView(ListView):
model = Product
template_name = 'list.html'
Reusable, inheritance
Mixins support
Generic CBV:
- ListView - all objects
- DetailView - single object
- CreateView - create object
- UpdateView - edit object
- DeleteView - delete object
Mixins:
LoginRequiredMixin - auth check
UserPassesTestMixin - custom logic
When to use:
FBV - Simple views
CBV - Complex, reusable logicWas this answer clear?