官术网_书友最值得收藏!

A view from the top

In Django, a view is defined as a callable that accepts a request and returns a response. It is usually a function or a class with a special class method such as as_view().

In both cases, we create a normal Python function that takes an HTTPRequest as the first argument and returns an HTTPResponse. A URLConf can also pass additional arguments to this function. These arguments can be captured from parts of the URL or set to default values.

Here is what a simple view looks like:

# In views.py 
from django.http import HttpResponse 
 
def hello_fn(request, name="World"): 
    return HttpResponse("Hello {}!".format(name)) 

Our two-line view function is quite simple to understand. We are currently not doing anything with the request argument. We can examine a request to better understand the context in which the view was called, for example, by looking at the GET/POST parameters, URI path, or HTTP headers such as REMOTE_ADDR.

Its corresponding mappings in URLConf using the traditional regular expression syntax would be as follows:

# In urls.py 
    url(r'^hello-fn/(?P<name>\w+)/$', views.hello_fn), 
    url(r'^hello-fn/$', views.hello_fn),

We are reusing the same view function to support two URL patterns. The first pattern takes a name argument. The second pattern doesn't take any argument from the URL and the view function will use the default name of world in this case.

The parameter passing works identically when you use the simplified routing syntax introduced in Django 2.0. So you will find the following equivalent mappings in viewschapter/urls.py:

# In urls.py 
    path('hello-fn/<str:name>/', views.hello_fn),
path('hello-fn/', views.hello_fn),

We shall use the simplified syntax for the rest of this book, as it is easier to read.

主站蜘蛛池模板: 松阳县| 江川县| 永年县| 普格县| 江西省| 崇左市| 淅川县| 东安县| 罗甸县| 贵定县| 海口市| 康马县| 屏东县| 阿勒泰市| 明溪县| 宜春市| 高青县| 乌审旗| 涿州市| 岑巩县| 洛南县| 驻马店市| 孟津县| 三门县| 新乐市| 揭东县| 鄄城县| 宜兰县| 会同县| 同仁县| 星子县| 镇康县| 卢氏县| 桃江县| 太和县| 都昌县| 云南省| 岗巴县| 姚安县| 高邑县| 禄劝|