In Django, views are responsible for processing incoming HTTP requests. Why is it important that views handle this request logic?
Think about what happens when a user visits a web page and how Django decides what to show.
Views in Django act as the middleman between the user's request and the data or template that should be shown. They contain the logic to process the request and return the right response.
Consider a Django view function that receives a GET request. What is the typical behavior of this view?
from django.http import HttpResponse, HttpResponseNotAllowed def example_view(request): if request.method == 'GET': return HttpResponse('Hello, world!') else: return HttpResponseNotAllowed(['GET'])
Look at how the view checks the request method and what it returns.
The view checks if the request method is GET, then returns a simple HTTP response. If the method is not GET, it returns a 'method not allowed' response.
Given the following Django view, what will be the HTTP response content if the request method is POST?
from django.http import HttpResponse, HttpResponseNotAllowed def my_view(request): if request.method == 'GET': return HttpResponse('GET request received') elif request.method == 'POST': return HttpResponse('POST request received') else: return HttpResponseNotAllowed(['GET', 'POST'])
Check the condition that matches the POST method.
The view returns 'POST request received' when the request method is POST, as per the elif branch.
Which option contains a syntax error in the Django view function below?
from django.http import HttpResponse def sample_view(request): if request.method == 'GET': return HttpResponse('Hello') else: return HttpResponse('Other method')
Look carefully at the if statement syntax.
The if statement is missing a colon at the end of the condition line, which causes a syntax error.
Examine the Django view below. When a request is made, it raises an error. What is the cause?
from django.http import HttpResponse def error_view(request): if request.method == 'POST': data = request.POST['username'] return HttpResponse(f'User: {data}')
Consider what happens if the request method is not POST.
If the request method is not POST, the variable 'data' is never assigned, but the return statement tries to use it, causing an UnboundLocalError.