在Django,网页和其他内容通过views来进行交互。每个视图都通过一个简单的Python函数(或方法)来展示。Django将通过检查请求的URL来选择一个视图(更精确地说是域名后面的URL)。从URL到View的过程是通过URLconfs来控制的。
接下来让我们写一个view。首先打开polls/views.py,添加如下代码:
# -*- coding: utf-8 -*- from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You’re at the poll index.")
接下来打开在polls文件夹下新建一个urls.py文件,建立view和url的联系,代码如下:
# -*- coding: utf-8 -*- from django.conf.urls import patterns, url from polls import views urlpatterns = patterns(‘‘, url(r‘^$‘, views.index, name=‘index‘) )
然后打开mysite/urls.py,添加代码如下:
urlpatterns = patterns(‘‘, url(r‘^polls/‘, include(‘polls.urls‘)), url(r‘^admin/‘, include(admin.site.urls)), )
注意一下,所有的html文件都要保存为utf-8格式。
现在你就有一个Poll的主页了,进入http://127.0.0.1:8000/polls/.
下面我们来分析一下这行代码:
url(r‘^$‘, views.index, name=‘index‘)
url有两个固定参数,正则表达式和view,另外还有两个可选的这里暂不做介绍。接下来让我们在polls/view.py里添加更多的方法。不过和之前的有所不同,他们多了一个变量。代码如下:
# -*- coding: utf-8 -*- from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You’re at the poll index.") def detail(request, poll_id): return HttpResponse("You’re looking at poll %s." % poll_id) def results(request, poll_id): return HttpResponse("You’re looking at the results of poll %s." % poll_id) def vote(request, poll_id): return HttpResponse("You’re voting on poll %s." % poll_id)
然后在polls/url.py里添加下面的代码:
import sys from django.conf.urls import patterns, url from polls import views reload(sys) sys.setdefaultencoding(‘utf-8‘) urlpatterns = patterns(‘‘, url(r‘^$‘, views.index, name=‘index‘), # ex: /polls/5/ url(r‘(?P<poll_id>\d+)/$‘,views.detail,name=‘detail‘), # ex: /polls/5/results/ url(r‘^(?P<poll_id>\d+)/results/$‘, views.results, name=‘results‘), # ex: /polls/5/vote/ url(r‘^(?P<poll_id>\d+)/vote/$‘, views.vote, name=‘vote‘), )
时间: 2024-10-29 19:11:42