
现在我们来编写的第一个视图。打开文件polls/views.py,把下面的Python代码放入里面:
polls/views.py
from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.")

这是 Django 最简单的视图。
要调用这个视图还需要把它映射到一个URL - 对于这一点,我们需要 URL 配置。
要在polls 目录创建URL配置,创建一个名为 urls.py 文件,现在您的应用程序目录应该是这样的:
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
urls.py
views.py
polls/urls.py文件包含以下代码:
polls/urls.py
from django.conf.urls import url from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]

下一步骤是让 polls.urls 模块指向该ROOT_URLCONF。在 mysite/urls.py 中, 增加导入 django.conf.urls.include 并插入 include() 在URL模式列表中,所以这里有:
mysite/urls.py
from django.conf.urls import include, url from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
现在已经连接索引视图到URL配置。让我们来验证它结果,运行以下命令:
C:\Python27\mysite> python manage.py runserver

在浏览器中打开http://localhost:8000/polls/,应该看到如下文字显示: “Hello, world. You’re at the polls index.”, 在 index 视图中所定义。

url()函数传递四个参数,两个必需的:regex 和 view,以及两个可选:kwargs 和 name。 |