Ubuntu12.04系统下写你的第一个Django1.5应用(三)--view
来源:互联网 发布:狂鼠伤害数据 编辑:程序博客网 时间:2024/06/05 02:55
Ubuntu12.04系统下写你的第一个Django1.5应用(三)--view
写你的第一个视图函数:
第一步,编写视图函数:
jiangge@ubuntu:~/mysite/polls$ vim views.py加入以下内容:
#coding:utf-8from django.http import HttpResponsedef index(request): return HttpResponse("Hello, world. You are at the poll index.")
第二步,ULRConf:
在polls目录下创建urls.py文件,填写以下内容:
from django.conf.urls import patterns, urlfrom polls import viewsurlpatterns = patterns('', url(r'^$', views.index, name='index'))
现在你的app目录是这个样子的:
jiangge@ubuntu:~/mysite$ tree polls/polls/├── admin.py├── __init__.py├── models.py├── tests.py├── urls.py└── views.py0 directories, 6 files
第三步:to point the root URLconf at the polls.urls module. Inmysite/urls.py insert aninclude()
from django.conf.urls import patterns, include, urlfrom django.contrib import adminadmin.autodiscover()urlpatterns = patterns('', url(r'^polls/', include('polls.urls')), url(r'^admin/', include(admin.site.urls)),)
第四步:浏览器地址栏输入:
http://localhost:8000/polls/可以看到 Hello, world. You are at the poll index. 显示出来了.
Note:
url()方法第一个参数,regular expression 匹配.
Note that these regular expressions do not search GET and POST parameters, or the domain name. For example, in a request tohttp://www.example.com/myapp/, the URLconf will look for myapp/. In a request tohttp://www.example.com/myapp/?page=3, the URLconf willalso look formyapp/.
url()方法第二个参数:view 视图函数
url()方法第三个参数:kwargs(可选的)
url()方法第三个参数:name(可选的)
写更多的视图函数
jiangge@ubuntu:~/mysite$ vim polls/views.py
#coding:utf-8from django.http import HttpResponsedef index(request): return HttpResponse("Hello, world. You are 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)
修改urls:
jiangge@ubuntu:~/mysite$ vim polls/urls.py
from django.conf.urls import patterns, urlfrom polls import viewsurlpatterns = patterns('', # ex: /polls/ 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'),)
浏览器分别访问:
http://localhost:8000/polls/34/
显示结果:You're looking at poll 34.
http://localhost:8000/polls/34/results/
显示结果:You're looking at the results of poll 34.
http://localhost:8000/polls/34/vote/
显示结果:You're voting on poll 34.
Write views that actually do something
#coding:utf-8from django.http import HttpResponsefrom polls.models import Polldef index(request): latest_poll_list = Poll.objects.order_by('-pub_date')[:5] output = ', '.join([p.question for p in latest_poll_list]) return HttpResponse(output)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)页面的设计是在view中写死的(硬代码),以后要修改会引起不必要的麻烦.
所以考虑将其分开写.
在polls目录下创建templates目录:
jiangge@ubuntu:~/mysite/polls$ mkdir templates
Note:(polls/templates) rather than the project’s (templates)
在polls/templates目录下创建polls目录
jiangge@ubuntu:~/mysite/polls/templates$ mkdir polls在新创建的polls目录下创建index.html
Note:your template should be at polls/templates/polls/index.html.Because of how theapp_directoriestemplate loader works as described above, you can refer to this template within Django simply aspolls/index.html. 这体现了,Django 模板命名空间的思想哦.
把以下内容下入文件:
jiangge@ubuntu:~/mysite/polls/templates/polls$ vim index.html
{% if latest_poll_list %} <ul> {% for poll in latest_poll_list %} <li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li> {% endfor %} </ul>{% else %} <p>No polls are available.</p>{% endif %}
在index视图函数中使用上述模板文件:
jiangge@ubuntu:~/mysite$ vim polls/views.py
#coding:utf-8from django.http import HttpResponsefrom django.template import Context, loaderfrom polls.models import Polldef index(request): latest_poll_list = Poll.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = Context({ 'latest_poll_list': latest_poll_list, }) return HttpResponse(template.render(context))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)
一个快捷方式: render()
jiangge@ubuntu:~/mysite$ vim polls/views.py
#coding:utf-8from django.http import HttpResponsefrom django.template import Context, loaderfrom polls.models import Pollfrom django.shortcuts import renderdef index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] context = {'latest_poll_list': latest_poll_list} return render(request, 'polls/index.html', context)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)
404error页面:
jiangge@ubuntu:~/mysite$ vim polls/views.py
#coding:utf-8from django.http import HttpResponsefrom django.template import Context, loaderfrom polls.models import Pollfrom django.shortcuts import renderfrom django.http import Http404def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] context = {'latest_poll_list': latest_poll_list} return render(request, 'polls/index.html', context)def detail(request, poll_id): try: poll = Poll.objects.get(pk=poll_id) except Poll.DoesNotExist: raise Http404 return render(request, 'polls/detail.html', {'poll': poll})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)
编写模板文件:
jiangge@ubuntu:~/mysite/polls/templates/polls$ vim detail.html
{{ poll }}
A shortcut: get_object_or_404():
#coding:utf-8from django.http import HttpResponsefrom django.template import Context, loaderfrom polls.models import Pollfrom django.shortcuts import render, get_object_or_404def index(request): latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] context = {'latest_poll_list': latest_poll_list} return render(request, 'polls/index.html', context)def detail(request, poll_id): poll = get_object_or_404(Poll, pk=poll_id) return render(request, 'polls/detail.html', {'poll': poll})sdef 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)
再次编写detail.html模板文件:
jiangge@ubuntu:~/mysite/polls/templates/polls$ vim detail.html
<h1>{{ poll.question }}</h1><ul>{% for choice in poll.choice_set.all %} <li>{{ choice.choice_text }}</li>{% endfor %}</ul>
移除模板中的URLs硬代码(Removing hardcoded URLs in templates)
参考文献:官方文档 https://docs.djangoproject.com/en/1.5/intro/tutorial03/点击打开链接
- Ubuntu12.04系统下写你的第一个Django1.5应用(三)--view
- Ubuntu12.04系统下写你的第一个Django1.5应用(二)--admin
- Ubuntu12.04系统下写你的第一个Django1.5应用(四)--form
- Ubuntu12.04系统下写你的第一个Django1.5应用(一)--环境搭建--数据库,时区,语言,配置
- Django1.5:(二)创建第一个Django应用5
- Django1.5:(二)创建第一个Django应用1
- Django1.5:(二)创建第一个Django应用2
- Django1.5:(二)创建第一个Django应用3
- Django1.5:(二)创建第一个Django应用4
- 啦啦啦啦~Django1.96---编写第一个Django应用(5)
- Ubuntu12.04下Django1.4的删除目录
- Ubuntu12.04安装Django1.5快速指南
- bootstrap写的第一个应用1
- 基于Django1.8.2文档,编写第一个Django应用(5)
- 啦啦啦啦~Django1.96---编写第一个Django应用(1)
- 啦啦啦啦~Django1.96---编写第一个Django应用(2)
- 啦啦啦啦~Django1.96---编写第一个Django应用(3)
- 啦啦啦啦~Django1.96---编写第一个Django应用(4)
- Android-sharedUserId数据权限!!!!!!!!!!
- Android 颜色(RGB)对照表
- 用指针作函数参数
- ZOJ 1205 Martian Addition
- C语言 单引号和双引号的区别
- Ubuntu12.04系统下写你的第一个Django1.5应用(三)--view
- xml文件的jdom解析
- 自己整理的MBR数据结构
- eclipse 设置编码
- 揭秘 typedef四用途与两陷阱
- 随机指标KDJ使用入门
- 远程连接服务器无法拷贝本地文件解决
- Oracle E-Business Suite on Mobile Device
- uva 11464 - Even Parity