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

URLs and views: creating the main page

The first thing that comes to mind after seeing the welcome page of the development server is: How can we change it? To create our own welcome page, we need to define an entry point to our application in the form of a URL and tell Django to call a particular Python function when a visitor accesses this URL. We will write this Python function ourselves, and make it display our own welcome message.

Creating the main page view

A view in Django terminology is a regular Python function that responds to a page request by generating the corresponding page. To write our first Django view for the main page, we first need to create a Django application inside our project. You can think of an application as a container for views and data models. To create it, issue the following command within our django_bookmarks folder:

$ python manage.py startapp bookmarks

The syntax of application creation is very similar to that of project creation. We used startapp as the first parameter to python manage.py, and provided bookmarks as the name of our application.

After running this command, Django will create a folder named bookmarks inside the project folder with these three files:

  • __init__.py: This file tells Python that bookmarks is a Python package
  • views.py: This file will contain our views
  • models.py: This file will contain our data models

Now, let's create the main page view. Open the file bookmarks/views.py in your code editor and enter the following:

from django.http import HttpResponse

def main_page(request):
  output = u'''
    <html>
      <head><title>%s</title></head>
      <body>
        <h1>%s</h1><p>%s</p>
      </body>
    </html>
  ''' % (
    u'Django Bookmarks',
    u'Welcome to Django Bookmarks',
    u'Where you can store and share bookmarks!'
  )
  return HttpResponse(output)

The code is short and pretty straightforward. Let's go through it line by line:

  • We import the class HttpResponse from django.http. We need this class in order to generate our response page.
  • We define a Python function that takes one parameter named request. This parameter contains user input and other information. For example, request.GET, request.POST, and request.COOKIES are dictionaries that contain get, post, and cookie data respectively.
  • We build the HTML code of the response page, wrap it within an HttpResponse object, and return it. Django uses Unicode to store and present data. Because of this, we added the letter u before strings to make them Unicode strings. This is how a Unicode string is created in Python. Throughout this book, we will use Unicode for all strings that are presented in the web pages or stored in the database. This means that whenever a string will be a part of a webpage or will be saved in the database, the letter u would need to be added before it.

A Django view is just a regular Python function. It takes user input as a parameter, and returns page output. But before we can see the output of this view, we need to connect it to a URL.

Embedding HTML snippets within views is usually not recommended for a variety of reasons. We did it here for the sake of simplicity. Later in this chapter, we will learn how to put the HTML code of our site in a separate set of files.

Creating the main page URL

As you may recall from the previous chapter, a file named urls.py was created when we started our project. This file contains valid URLs for our application, and maps each URL to a view that is a Python function. Let's examine the contents of this file and see how to edit it:

from django.conf.urls.defaults import *
urlpatterns = patterns('',
  # Example:
  # (r'^django_bookmarks/',
      include('django_bookmarks.foo.urls')),
  # Uncomment this for admin:
  # (r'^admin/', include('django.contrib.admin.urls')),
)

As you can probably tell, the file contains a table of URLs and their corresponding Python functions (or views). The table is called urlpatterns, and it initially contains example entries that are commented out. Each entry is a Python tuple that consists of a URL and its view.

The URL syntax may look familiar to you because it uses regular expressions. Django gives you a lot of flexibility by letting you specify URL patterns with the use of this powerful string-matching technique. We will gradually learn about this syntax and how to utilize it. Let's start by removing the comments and adding an entry for the main page:

from django.conf.urls.defaults import *
from bookmarks.views import *

urlpatterns = patterns('',
  (r'^$', main_page),
)

Again, let's see the breakdown of this code:

  • The file imports everything from the module django.conf.urls.defaults. This module provides the necessary functions to define URLs.
  • We import everything from bookmarks.views. This is necessary to access our views and connect them to URLs.
  • The patterns function is used to define the URL table. It contains only one mapping for now—from r'^$' to our view main_page.

One last thing needs to be explained before we see the view in action. The regular expression that we used will look a bit strange if you haven't used regular expressions before. It is a raw string that contains two characters, ^ and $. The Python syntax for defining raw strings is r''. If Python encounters such a raw string, backslashes and other escape sequences are retained in the string rather than interpreted in any way. In this syntax, backslashes are left in the string without change, and escape sequences are not interpreted. This is useful when working with regular expressions because they often contain backslashes.

In regular expressions, ^ means the beginning of the string, and $ means the end of the string. So ^$ is basically a string that doesn't contain anything, meaning it is an empty string. Given that we are writing the view of the main page, the URL of the page is the root URL, and indeed it should be empty.

Python documentation of the re module covers regular expressions in detail. I recommend reading it if you want a thorough treatment of regular expressions. You can find the documentation online at:

http://docs.python.org/lib/module-re.html

The following table summarizes regular expression syntax for those who want a quick refresher:

Now that everything is clear, we can test our first view. Launch the development server and go to http://127.0.0.1:8000/ to see the page generated by the view.

Creating the main page URL

Congratulations! Your first Django view is up and running.

Before we move to the next section, it is a good idea to understand what's going on behind the scenes:

  • When a user requests the root URL at http://127.0.0.1:8000/, Django searches the URL table in the urls.py file for a URL that matches the request. Matching is done using regular expressions.
  • If Django finds a matching URL, it calls its corresponding view. The view, which is a regular Python function, receives data generated by the user's browser as a parameter called the request object. It returns the generated page wrapped in an HttpResponse object.
  • If Django doesn't find a URL that matches the request, it displays a Page not found (404) error. You can test this by requesting http://127.0.0.1:8000/does_not_exist/ as illustrated in the following image. Notice that Django displays helpful debugging information to assist you in figuring out what's wrong. Of course, these debugging messages can be turned off when the site goes live.
Creating the main page URL

This way of mapping URLs to views gives the developer a lot of flexibility. URLs are not restricted to filenames as in PHP, and are not automatically mapped to function names as in mod_python. You are given total control over the mapping between URLs and functions. This is especially good for large projects, where URLs and function names often change during phases of the development.

Our main page looks a little basic without CSS. Therefore, we will learn to use templates, which will make it easy to style our pages using stylesheets. Before doing this, we will learn about database models as well as how to store and manage our data.

主站蜘蛛池模板: 横山县| 仙桃市| 奇台县| 长丰县| 宜丰县| 武川县| 淅川县| 招远市| 股票| 萍乡市| 博客| 锦屏县| 明水县| 巴中市| 阿鲁科尔沁旗| 县级市| 溆浦县| 固安县| 二连浩特市| 隆林| 黑水县| 黎川县| 廊坊市| 永泰县| 汕尾市| 广宁县| 凤凰县| 科技| 昌邑市| 长阳| 斗六市| 桂东县| 得荣县| 双流县| 五华县| 得荣县| 新安县| 兰溪市| 威信县| 普格县| 婺源县|