Create a first static view in Django

Source: Internet
Author: User
As our first goal, create a Web page that is used to output this well-known sample information:

  Hello World.

If you've ever published the Hello World page, but don't use the web frame, simply type Hello world into the hello.html text file and upload it to any Web server. Note that in this process, you have explained two key information about this page: it includes (the string "Hello World") and its URL (http://www.example.com/hello.html, if you put the file in a subdirectory, it may also be http://www.example.com/files/hello.html).

With Django, you'll use different methods to illustrate that the content of the page is generated by the view function (views functions), and the URL is defined in URLconf. First, let's write a Hello world view function first.

In the previous chapter, in the MySite folder made with django-admin.py Startproject, create an empty file called views.py. This Python module will contain a view of this chapter. Note that Django has no special requirements for view.py file naming, and it doesn't care what the file is called. But according to the Convention, it's a good idea to name it view.py so that other developers can read your code, just as easily as you read this article.

Our Hello world view is very simple. These are the complete functions and import declarations that you need to enter into the views.py file:

From django.http import httpresponsedef Hello (Request):  return HttpResponse ("Hello World")

Let's parse this code one step at a time, by line:

    • First, we import the (import) HttpResponse class from the Django.http module. See Appendix H for more details on HttpRequest and HttpResponse. We need to import these classes, because we'll use them later.
    • Next, we define a view function called Hello.
    • Each view function must have at least one parameter, which is often called a request. This is an object that triggers this view, contains the current Web request information, and is an instance of the class Django.http.HttpRequest. In this example, although we don't have to do anything with the request, it still has to be the first parameter of the view.
    • Note that the name of the view function is not important, and it does not necessarily have to be named in a particular way for Django to recognize it. Here we name it: Hello, because the name clearly shows the purpose of the view. In the same way, you can name it with an ugly short phrase such as: Hello_wonderful_beautiful_world. In the next section (Your first URLconf), you will be told how Django found this function.
    • This function has a simple line of code: it simply returns a HttpResponse object that contains the text "Hello World".

The main point here is that a view is a function of Python. The type of the first parameter of this function is HttpRequest; it returns a HttpResponse instance. In order for a Python function to be a Django-aware view, it must satisfy both of these conditions. (There are exceptions, but we will not be in touch until later.)
Your first urlconf.

Now, if you run again: Python manage.py runserver, you'll also see the Django Welcome page without seeing the Hello World display page we just wrote. That's because our MySite project also knows nothing about the Hello view. We need to explicitly tell it and activate this view through a URL that is described in detail. (Continue with our example of publishing a static HTML file just now.) Now that we have created the HTML file, we have not uploaded it to the server directory. In order to bind the view functions and URLs, we use urlconf.

URLconf is like a directory of Django-supported websites. Its essence is the URL pattern and the mapping table between the view functions to invoke for that URL pattern. That's how you tell Django to call that code for that URL and call that code for that URL. For example, when a user accesses/foo/, the View function Foo_view () is called, and this view function exists in the Python module file view.py.

When you execute django-admin.py startproject in the previous chapter, the script automatically builds a copy of the URLconf (that is, the urls.py file) for you. The default urls.py will look like this:

From django.conf.urls.defaults import *# uncomment the next and lines to enable the admin:# from Django.contrib Import adm in# admin.autodiscover () Urlpatterns = Patterns (",  # Example:  # (R ' ^mysite/', include (' Mysite.foo.urls ')),  # Uncomment the Admin/doc line below and add ' Django.contrib.admindocs '  # to Installed_apps to enable admin docum Entation:  # (R ' ^admin/doc/', include (' Django.contrib.admindocs.urls ')),  # Uncomment the next line to enable the admin:  # (R ' ^admin/', include (Admin.site.urls)),)

The default urlconf contains some of the features that are commonly used in Django, which can be turned on simply by removing the annotations. The following is the actual contents of the urlconf after ignoring the commented lines

From django.conf.urls.defaults Import *urlpatterns = Patterns (",)

Let's explain the code on a line-by-row basis:

    • The first line imports all the modules under Django.conf.urls.defaults, which are the basic constructs of the Django urlconf. This includes a patterns function.
    • The second line calls the patterns () function and saves the returned result to the Urlpatterns variable. The patterns function currently has only one parameter-an empty string. (This string can be used to represent a generic prefix for a view function.) Specifically, we will introduce in the eighth chapter. )

It is now important to note that the Urlpatterns variable, Django expects to be able to find it from the root_urlconf module. The variable defines the mapping between the URL and the code used to process the URLs. By default, URLconf all the content is commented out--django application or white version piece. (Note: That's why Django knows how to display the Welcome page in the previous section.) If URLconf is empty, Django will assume that you are creating a new project, so that information is displayed as well.

If you want to add URLs and view to urlconf, simply add the python tuple that maps the URL pattern and view functionality. Here's how to add the Hello feature in view.

From django.conf.urls.defaults import *from mysite.views Import hellourlpatterns = Patterns (",  (' ^hello/$ ', hello) ,)

Please note: For brevity, we removed the comment code. If you like, you can keep those lines. )

We have made two changes.

    1. First, we introduced the Hello View from the module (in the import syntax of Python, mysite/views.py translation to Mysite.views). (This assumes that mysite/views.py is on your Python search path.) For an explanation of the search path, refer to the following. )
    2. Next, we add a line for Urlpatterns: (' ^hello/$ ', hello), which is called the Urlpattern, which is a python tuple. The first element in a tuple is a pattern-matching string (a regular expression), and the second element is the view function that the pattern will use.

Simply put, we just tell Django that all requests to url/hello/should be handled by the Hello view function.

Python Search Path

The Python search path is the list of system catalogs that Python looks for when using the import statement.

For example, suppose you set the Python path to [', '/usr/lib/python2.4/site-packages ', '/home/username/djcode/']. If you execute code from foo Import bar, Python will first find the foo.py module in the current directory (the empty string for the first item in the Python path represents the current directory). If the file does not exist, Python will look for the/usr/lib/python2.4/site-packages/foo.py file.

If you want to see the value of the Python search path, run the Python interaction interpreter and enter:

>>> Import sys>>> Print Sys.path

Typically, you don't have to care about the Python search path settings. Python and Django will automatically help you with the background.

It is worthwhile to discuss the syntax of Urlpattern because it is not obvious. Although we want to match the address/hello/, the pattern looks a little different. This is why:

    • Django Removes a slash (/) at the beginning of each request URL before checking the URL pattern. This means that we write the URL pattern for/hello/without having to include a slash (/). (This may not seem intuitive at first, but this requirement simplifies a lot of work, such as URL pattern embedding, which we'll talk about in chapter eighth.) The
    • pattern contains a caret (^) and a dollar sign ($). These are regular expression symbols and have a specific meaning: The up arrow requires the expression to match the head of the string, and the dollar sign requires the expression to match the tail of the string.
    • It is best to use examples to illustrate this concept. If we use the trailing not $ mode ' ^hello/', then any URLs beginning with/hello/will match, for example:/hello/foo and/hello/bar, not just/hello/. Similarly, if we omit the caret (^), which is ' hello/$ ', then any URLs ending in hello/will match, for example:/foo/bar/hello/. If we simply use hello/, that is, there is no ^ start and end, then any URLs that contain hello/will match, such as:/foo/hello/bar. Therefore, we use these two symbols to ensure that only/hello/matches, not many and many.
    • Most of your URL patterns start with a ^ and end with $, but the flexibility to have complex matches is better.
    • You may ask: what happens if someone requests access to/hello (no trailing slash/). Because our URL pattern requires a trailing slash (/), the request URL will not match. However, by default, any mismatch or trailing request URL without a slash (/) will be redirected to the URL of the same word with the trailing slash. (This is controlled by the Append_slash item in the configuration file setting, see annex D.)
    • If you are a person who likes all URLs ending with a '/' (Django Developer's preference), then you only need to add a slash after each URL and set "Append_slash" to "True". If you do not like URLs ending in slashes or depending on each URL, then you need to set "Append_slash" to "False" and add the trailing slash/after URL mode to your own liking.

It is also important to note that we pass the Hello view function as an object instead of calling it. This is an important feature of Python (and other dynamic languages): functions are primary objects (first-class objects), meaning that you can pass them like other variables. Pretty cool, huh?

Start the Django Development server to test the modified URLconf, and run the command line Python manage.py runserver. (If you keep it running, the development server will automatically monitor code churn and reload automatically, so you don't need to restart manually) the address of the development server is http://127.0.0.1:8000/, open your browser to access http://127.0.0.1:8000/hello/. You can see the output. The development server will automatically detect changes to Python code to do the necessary reloading, so you do not need to restart the server after the code changes. The server runs the address ' http://127.0.0.1:8000/', so open the browser directly into ' http://127.0.0.1:8000/hello/' and you will see the Hello World output by your Django view.

Hail! You have created the first Django Web page.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.