from django.views import View
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
class ProductListView(View):
def get(self, request):
products = [{'id': 1, 'name': 'Laptop'}]
return JsonResponse({'products': products})
@require_http_methods(["GET", "POST"])
def create_order(request):
if request.method == 'POST':
return JsonResponse({'status': 'Order created'})
return JsonResponse({'status': 'Ready to receive order'})Identifying View Type and Response Method
ProductListView is a class-based view handling GET requests, while create_order is a function-based view restricted to GET and POST methods using a decorator.
Both ProductListView and create_order are function-based views and must be decorated with @require_http_methods.
The require_http_methods decorator is unnecessary because Django automatically restricts HTTP methods for all views.
Class-based views cannot return JsonResponse; they can only return TemplateResponse.
Show answer & explanationAnswer
Correct answer
ProductListView is a class-based view handling GET requests, while create_order is a function-based view restricted to GET and POST methods using a decorator.
Explanation
Class-based views inherit from View and use HTTP method handlers (get, post, etc.), while function-based views handle all methods in one function. Decorators restrict HTTP methods for function-based views.
All 30 Django Views and URL Routing questions
- 1.What is the primary purpose of URL routing in Django?
- 2.Which file in a Django project is responsible for defining URL patterns?
- 3.What is a Django view?
- 4.What is the difference between a function-based view and a class-based view in Django?
- 5.What does the `path()` function do in Django's urls.py?
- 6.What is the purpose of URL parameters in Django routing?
- 7.What does `HttpResponse` represent in Django views?
- 8.What is the role of `include()` in Django URL routing?
- 9.What is the purpose of the `name` parameter in Django's `path()` function?
- 10.What does `render()` function do in Django views?
- 11.Understanding Django URL Routing with Path Converters
- 12.Scenario:
- 13.Identifying the Correct URL Pattern Syntax
- 14.Understanding Django View Function Parameters
- 15.Scenario:
- 16.Identifying View Type and Response Method
- 17.Understanding Reverse URL Lookup
- 18.Scenario:
- 19.Understanding Regular Expression Patterns in URLs
- 20.Scenario:
- 21.Understanding Django URL Routing with Include and Namespace
- 22.Identifying the Bug in Django URL Pattern Matching
- 23.Scenario:
- 24.Analyzing Django View and URL Mapping
- 25.Scenario:
- 26.Understanding Class-Based Views with URL Routing
- 27.Finding the Output:
- 28.Scenario:
- 29.Identifying URL Pattern Issues with Regex Converters
- 30.Scenario:
