[翻译]Django 1.0 中文文档—–指导 第三部分 发布视图

编写你的Django应用 第三部分

我们接着上篇开始,继续网页投票应用,本篇我们着重在建立发布视图。

理念

视图在Django中就是一个特定功能和特定模板的网页,例如在博客程序中你会有如下视图:

  • 博客首页 – 显示最新记录.
  • 进入详细内容页面 – 页面固定链接.
  • 基于年的存档页 – 显示给定年里所有月份的进入点.
  • 基于月的存档页 – 显示给定月里所有天的进入点. .
  • 基于日的存档页 – 显示给定日里所有天的进入点.
  • 评论 – 所有评论的进入链接.

 

在我们的投票应用程序中,我们有下面四个视图:

 

  • Poll “archive” 页 – 显示最新的投票.
  • Poll “detail” 页  – 显示投票页面.
  • Poll “results” 页 – 显示投票结果.
  • Vote action – 处理投票程序的页面.

 

在Django里,每个视图都是用一个简单的python函数描述的。

设计你的urls

 

编写视图第一步是设计你的URL结构,需要借助python的一个组件URLconf将python代码和URL联系起来。

当用户请求Django的页面,系统会查找ROOT_URLCONF 设置,Django加载组件并查找urlpatterns变量,一段类似如下格式的序列:

(regular expression, Python callback function [, optional dictionary])

Django会从第一个规则表达式开始,一直往下,匹配请求的URL直到匹配上,当找到匹配的时候,Django会回调函数,为第一个参数传入HttpRequest 对象,还有表达式里捕获的值。

要了解更多HttpRequest,URLconfs详情,可查看具体文档。

当我们创建工程的时候,mysite/urls.py会被自动创建。settings.py中默认配置指定位置ROOT_URLCONF = ‘mysite.urls’
编辑mysite/urls.py:

  1. from django.conf.urls.defaults import *
  2. urlpatterns = patterns(”,
  3.     (r’^polls/$’, ‘mysite.polls.views.index’),
  4.     (r’^polls/(?P<poll_id>\d+)/$’, ‘mysite.polls.views.detail’),
  5.     (r’^polls/(?P<poll_id>\d+)/results/$’, ‘mysite.polls.views.results’),
  6.     (r’^polls/(?P<poll_id>\d+)/vote/$’, ‘mysite.polls.views.vote’),
  7. )

 

当有”/polls/23/”这样的地址请求时,python 会匹配到 r’^polls/(?P<poll_id>\d+)/$’ 这里,然后调用

mysite/polls/views.py里的detail()函数,如下:

 

 

 

 

 

detail(request=<HttpRequest object>, poll_id=’23’)

 

poll_id=’23’ 来自(?P<poll_id>\d+). 通过正则匹配捕获的值,这里也可以定义多个值来捕获。

因为URL定义没有什么扩展名定义限制你也可以像这样定义

(r’^polls/latest\.php$’, ‘mysite.polls.views.index’),
用php做扩展名,看起来比较幽默。不过最好还是不要定义扩展名。

 

注意,URL表达式是不包括GET,POST参数和域名。例如http://www.example.com/myapp/,URL配置为/myapp/。

http://www.example.com/myapp/?page=3 也同样匹配/myapp/

 

表达式会在django加载的时候编译。

 

编写你的第一个视图

 

好,我们还没有创建视图,只是创建了URLconf,接下来我们确认下URLconf。

启动django服务

 

python manage.py runserver

我们访问”http://localhost:8000/polls/“,我们会看到下面的报错信息:

 

ViewDoesNotExist at /polls/

Tried index in module mysite.polls.views. Error was: ‘module’
object has no attribute ‘index’

 

这个信息提示我们没有在mysite/polls/views.py里创建 index() 函数

测试”/polls/23/”, “/polls/23/results/” 和 “/polls/23/vote/”. 都会有错误提示没有创建视图函数。

 

打开mysite/polls/views.py文件加入下面的代码:

 

  1. from django.http import HttpResponse
  2. def index(request):
  3.     return HttpResponse(“Hello, world. You’re at the poll index.”)

 

这是个简单的视图,访问”/polls/” 你会看到相应的内容输出。

我们继续创建接下来的视图,这个有一点不通,多了一个参数

 

 

 

 

  1. def detail(request, poll_id):
  2.     return HttpResponse(“You’re looking at poll %s.” % poll_id)

 

访问”/polls/34/”. 你会看到URL传入的ID

 

写一个有实际功能的视图

 

每个视图都会负责做些事情,返回一个HttpResponse 对象,包含请求页面的内容,或抛出HTTP 404 异常。

视图可以读取数据库数据,可以使用Django带的模板,也可以使用第三方模板,还可以输出PDF,XML,ZIP等。

为了方便,我们用DJANGO自己的数据库API根据发布时间显示5挑问卷,用逗号分开

 

  1. from mysite.polls.models import Poll
  2. from django.http import HttpResponse
  3. def index(request):
  4.     latest_poll_list = Poll.objects.all().order_by(‘-pub_date’)[:5]
  5.     output = ‘, ‘.join([p.question for p in latest_poll_list])
  6.     return HttpResponse(output)

有个问题,如果页面比较复杂,这里用python编写html会很麻烦,那么我们可以使用django的模板来解决。

 

  1. from django.template import Context, loader
  2. from mysite.polls.models import Poll
  3. from django.http import HttpResponse
  4. def index(request):
  5.     latest_poll_list = Poll.objects.all().order_by(‘-pub_date’)[:5]
  6.     t = loader.get_template(‘polls/index.html’)
  7.     c = Context({
  8.         ‘latest_poll_list’: latest_poll_list,
  9.     })
  10.     return HttpResponse(t.render(c))

程序会调用”polls/index.html”模板,同时会传入一个字典到给模板,刷新页面你会看到下面输出

 

TemplateDoesNotExist at /polls/
polls/index.html

 

提示没有这个模板文件,我们编辑 TEMPLATE_DIRS 在 settings.py 文件中,设置模板目录,在”[template_directory]/polls/index.html” 位置添加模板文件,代码入校

 

  1. {% if latest_poll_list %}
  2.     <ul>
  3.     {% for poll in latest_poll_list %}
  4.         <li>{{ poll.question }}</li>
  5.     {% endfor %}
  6.     </ul>
  7. {% else %}
  8.     <p>No polls are available.</p>
  9. {% endif %}

 

一个快捷方法: render_to_response()

 

  1. from django.shortcuts import render_to_response
  2. from mysite.polls.models import Poll
  3. def index(request):
  4.     latest_poll_list = Poll.objects.all().order_by(‘-pub_date’)[:5]
  5.     return render_to_response(‘polls/index.html’, ‘latest_poll_list’: latest_poll_list})

 

抛出404

 

投票详细内容视图

 

  1. from django.http import Http404
  2. # …
  3. def detail(request, poll_id):
  4.     try:
  5.         p = Poll.objects.get(pk=poll_id)
  6.     except Poll.DoesNotExist:
  7.         raise Http404
  8.     return render_to_response(‘polls/detail.html’, {‘poll’: p})

 

如果请求的投票ID 不存在,就会升级404 异常

 

快捷函数 get_object_or_404()

 

  1. from django.shortcuts import render_to_response, get_object_or_404
  2. # …
  3. def detail(request, poll_id):
  4.     p = get_object_or_404(Poll, pk=poll_id)
  5.     return render_to_response(‘polls/detail.html’, {‘poll’: p})

 

同样还有一个 get_list_or_404() 函数

 

使用模板系统

 

回到投票detail()视图,在模板路径建立”polls/detail.html” 文件

 

 

  1. <h1>{{ poll.question }}</h1>
  2. <ul>
  3. {% for choice in poll.choice_set.all %}
  4.     <li>{{ choice.choice }}</li>
  5. {% endfor %}
  6. </ul>

 

 

{{ poll.question }}是用点语法访问变量的属性或者字典的KEY,{% for %}是模板脚本的循环,poll.choice_set.all 投票选项的所有记录。

 

简化URLconfs

 

  1. urlpatterns = patterns(”,
  2.     (r’^polls/$’, ‘mysite.polls.views.index’),
  3.     (r’^polls/(?P<poll_id>\d+)/$’, ‘mysite.polls.views.detail’),
  4.     (r’^polls/(?P<poll_id>\d+)/results/$’, ‘mysite.polls.views.results’),
  5.     (r’^polls/(?P<poll_id>\d+)/vote/$’, ‘mysite.polls.views.vote’),
  6. )

视图函数部分都是完整的名称,我们可以简化下配置:

 

  1. urlpatterns = patterns(‘mysite.polls.views’,
  2.     (r’^polls/$’, ‘index’),
  3.     (r’^polls/(?P<poll_id>\d+)/$’, ‘detail’),
  4.     (r’^polls/(?P<poll_id>\d+)/results/$’, ‘results’),
  5.     (r’^polls/(?P<poll_id>\d+)/vote/$’, ‘vote’),
  6. )

mysite.polls.views 提取出来,这样URL配置更简化了些。

 

解耦URLconfs

 

URLs 可以分多个文件模块配置,通过include包含进来。

(r’^polls/’, include(‘mysite.polls.urls’)),
polls/相关的请求就会到mysite/polls/urls.py查找匹配

 

mysite/polls/urls.py如下:

 

 

 

 

  1. urlpatterns = patterns(‘mysite.polls.views’,
  2.     (r’^$’, ‘index’),
  3.     (r’^(?P<poll_id>\d+)/$’, ‘detail’),
  4.     (r’^(?P<poll_id>\d+)/results/$’, ‘results’),
  5.     (r’^(?P<poll_id>\d+)/vote/$’, ‘vote’),
  6. )

去掉了polls/部分

40 Comments

  1. Law Firm

    I not to mention my guys appeared to be digesting the excellent guides found on your website then all of a sudden I had a terrible suspicion I had not expressed respect to the blog owner for those strategies. The young boys appeared to be as a consequence happy to read them and have now clearly been loving these things. I appreciate you for getting quite accommodating and for deciding on this kind of notable tips most people are really desperate to learn about. My honest apologies for not expressing gratitude to earlier.

    Reply
  2. Vitamin

    hello there and thank you for your information – I have definitely picked up anything new from right here. I did however expertise some technical points using this website, as I experienced to reload the web site many times previous to I could get it to load properly. I had been wondering if your web host is OK? Not that I am complaining, but sluggish loading instances times will sometimes affect your placement in google and could damage your high quality score if advertising and marketing with Adwords. Anyway I’m adding this RSS to my email and can look out for a lot more of your respective exciting content. Make sure you update this again very soon..

    Reply
  3. viagra no prior prescription

    Diversified Presentation Extensively this outcome

    Reply
  4. Business Service

    Good article and right to the point. I am not sure if this is really the best place to ask but do you guys have any ideea where to hire some professional writers? Thanks in advance 🙂

    Reply
  5. Oil investments

    Pretty nice post. I just stumbled upon your weblog and wanted to say that I’ve really enjoyed surfing around your blog posts. After all I’ll be subscribing in your feed and I am hoping you write again very soon!

    Reply
  6. hydraulically

    This site was… how do I say it? Relevant!! Finally I’ve found something that helped me. Thank you!|

    Reply
  7. Education and Training

    I have been exploring for a little for any high-quality articles or weblog posts on this kind of area . Exploring in Yahoo I finally stumbled upon this web site. Reading this info So i¡¦m satisfied to convey that I have an incredibly excellent uncanny feeling I found out exactly what I needed. I most certainly will make certain to do not put out of your mind this site and give it a glance regularly.

    Reply
  8. software development outsourcing

    Great blog! Do you have any recommendations for aspiring writers? I’m planning to start my own blog soon but I’m a little lost on everything. Would you advise starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m totally confused .. Any ideas? Thanks a lot!

    Reply
  9. AlbertAgoxy

    Hello there! mexica pharmacy online very good internet site.

    Reply
  10. Classic Car

    Hi there, You’ve done an excellent job. I’ll definitely digg it and personally suggest to my friends. I am sure they’ll be benefited from this website.

    Reply
  11. Auto Care and Service

    Thank you, I’ve just been looking for information approximately this topic for a while and yours is the best I have discovered till now. But, what about the conclusion? Are you sure concerning the source?

    Reply
  12. buy instagram likes

    to write some content for your blog in exchange for a link back to

    Reply
  13. Education and Training

    Enjoyed studying this, very good stuff, appreciate it. “Nothing happens to any thing which that thing is not made by nature to bear.” by Marcus Aurelius Antoninus.

    Reply
  14. buy instagram followers

    Thanks for another magnificent article. Where else could anyone get that kind of info in such an ideal way of writing? I have a presentation next week, and I am on the look for such information.

    Reply
  15. AlbertAgoxy

    Hi there! mexica pharmacy online beneficial internet site.

    Reply
  16. where to buy good hair extensions

    This is a topic that is close to my heart… Cheers! Exactly where
    are your contact details though?

    Reply
  17. islam videos

    This can be a good blog and i wish to take a look at this each and every day in the week.

    Reply
  18. Education and Training

    Terrific paintings! That is the kind of information that are supposed to be shared around the net. Disgrace on the search engines for now not positioning this put up higher! Come on over and discuss with my website . Thank you =)

    Reply
  19. AlbertAgoxy

    Hi! online pharmacy great internet site.

    Reply
  20. Business & Finance

    I’ve been absent for a while, but now I remember why I used to love this blog. Thanks , I will try and check back more often. How frequently you update your web site?

    Reply
  21. Viagra

    I think I will become a great follower.Just want to say your post is striking. The clarity in your post is simply striking and i can take for granted you are an expert on this subject.

    Reply
  22. Car & Automotive

    Wow! This can be one particular of the most beneficial blogs We have ever arrive across on this subject. Basically Magnificent. I am also a specialist in this topic therefore I can understand your hard work.

    Reply
  23. Womans Health

    Wow! Thank you! I continually wanted to write on my website something like that. Can I take a portion of your post to my blog?

    Reply
  24. Law

    What i do not understood is if truth be told how you’re now not really a lot more well-liked than you might be right now. You’re very intelligent. You know therefore considerably in terms of this topic, produced me individually imagine it from a lot of varied angles. Its like women and men are not interested except it¡¦s something to accomplish with Lady gaga! Your personal stuffs excellent. At all times take care of it up!

    Reply
  25. Education

    I like this post, enjoyed this one regards for posting .

    Reply
  26. Education

    I have been absent for some time, but now I remember why I used to love this web site. Thanks, I’ll try and check back more often. How frequently you update your site?

    Reply
  27. Education

    Thank you for the sensible critique. Me and my neighbor were just preparing to do some research about this. We got a grab a book from our area library but I think I learned more from this post. I’m very glad to see such fantastic information being shared freely out there.

    Reply
  28. Education

    I think this is one of the most important info for me. And i’m glad reading your article. But wanna remark on some general things, The web site style is perfect, the articles is really great : D. Good job, cheers

    Reply
  29. Car & Automotive

    Super-Duper website! I am loving it!! Will be back later to read some more. I am taking your feeds also

    Reply
  30. discount chainsaw

    This is a topic that is near to my heart Many thanks! Exactly where are your contact details though?

    Reply
  31. Pingback: URL

  32. Pingback: mold removal

  33. Pingback: pendaftaran cpns

  34. Pingback: cpns kemenkumham

  35. Pingback: Top beach hotels DR

  36. Pingback: Agenwin

  37. Pingback: מיזוג אוויר

  38. Pingback: gambar pemandangan

  39. Pingback: more

Leave a Comment

电子邮件地址不会被公开。 必填项已用*标注