Introduction: A correct understanding of Django View, model, template three concepts to quickly use Django to make Web pages
This article focuses on the understanding of view views after learning Django
Body: A Django view needs to have a view function, and if you want the view function to work you need to map the URL l to the view.
The view function is placed in a file called views.py , which is located in the Django project directory
Here's an example of how the view works:
Here is a view that returns the current date and time as an HTML document:
from django.http import httpresponseimport datetimedef current_datetime (request): now = datetime datetime. Now () html = ".</body>% now return httpresponse (html)
Let's read the above code on line:
-
first, we imported the HttpResponse class from the Django.http module, as well as the Python datetime Library.
-
then we defined current_datetime Function. It is the view function. each view function should receive httprequest The object is generally referred to as the first parameter as request .
Note that the name of the view function is not important; we name it current_ DateTime because the name accurately reflects its functionality.
-
This view returns a HttpResponse object that contains the generated response. Each view function returns a httpresponse object. (with the exception, we'll talk about it next.) )
The time zone in Django
Django contains a time_zone setting, which defaults to America/chicago. It may not be where you live, so you may be able to modify it in the settings file.
map your URL to a view¶
So, again, this view function returns an HTML page containing the current date and time. you need to create URLconf to present this view on a specific URL, as described in the URL Scheduler .
The Django view can complete a series of responses to a page when a user requests access to a page. The process is as follows:
when a page is requested, Django creates a HttpRequest object that contains the request metadata . When Django loads the corresponding view, theHttpRequest object acts as the first parameter of the view function. Each view returns a HttpResponse object.
Server-side response (English: Response) and client requests (English: request)
[Diango] Understanding how Django views Work