2.C] Discuss the concept of views in Django.
Answer:
In Django, a view is a Python function that receives a web request and returns a web response.
This response can be anything from HTML content, redirect, error message, or XML data, depending on the logic implemented in the view.
Functionality:
- Request Handling: A view function takes an
HttpRequest
object as its input. This object contains information about the request, such as user data, request method (GET, POST), and more. - Response Creation: The view function processes this request, performs necessary operations (like fetching data or computing values), and constructs an
HttpResponse
object. This object contains the content to be sent back to the user’s browser.
Example:
- Consider a view function that displays the current date and time:
from django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html)
- Imports:
HttpResponse
anddatetime
are imported to handle HTTP responses and date/time operations. - Function Definition:
current_datetime
is defined to handle the request and return a response. It computes the current date and time, formats it into an HTML string, and returns it wrapped in anHttpResponse
object.