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

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 = '''
    <html>
      <head><title>%s</title></head>
      <body>
        <h1>%s</h1><p>%s</p>
      </body>
    </html>
  ''' % (
    'Django Bookmarks',
    'Welcome to Django Bookmarks',
    '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.

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.

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 using 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 explaining 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 $. r'', which is the Python syntax for defining raw strings. If Python encounters such a raw string, then 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 ^$ basically means a string that doesn't contain anything; that 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

Below is a table that 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 urls.py 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 and returns the generated page wrapped in an HttpResponse object.
  • If Django doesn't find a URL that matches the request, it displays a 404 "Page Not Found" error. You can test this by requesting http://127.0.0.1:8000/does_not_exist/ as illustrated in the image below. 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 and how to store and manage our data.

主站蜘蛛池模板: 吴江市| 高阳县| 巴南区| 斗六市| 新闻| 枞阳县| 隆尧县| 德清县| 景德镇市| 陵水| 漠河县| 宝清县| 策勒县| 白玉县| 泰州市| 综艺| 青川县| 德安县| 红原县| 泰兴市| 邵东县| 延吉市| 南丹县| 丰宁| 牡丹江市| 巩留县| 象山县| 安远县| 湖南省| 紫金县| 中西区| 壶关县| 怀远县| 玛曲县| 教育| 甘肃省| 榆中县| 察雅县| 汶川县| 东阿县| 大余县|