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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.32.213