Ubuntu12.04系统下写你的第一个Django1.5应用(三)--view
写你的第一个视图函数:
第一步,编写视图函数:
jiangge@ubuntu:~/mysite/polls$ vim views.py
加入以下内容:
#coding:utf-8
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You are at the poll index.")
第二步,ULRConf:
在polls目录下创建urls.py文件,填写以下内容:
from django.conf.urls import patterns, url
from polls import views
urlpatterns = 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.py
0 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, url
from django.contrib import admin
admin.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-8
from django.http import HttpResponse
def 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, url
from polls import views
urlpatterns = 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-8
from django.http import HttpResponse
from polls.models import Poll
def 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-8
from django.http import HttpResponse
from django.template import Context, loader
from polls.models import Poll
def 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-8
from django.http import HttpResponse
from django.template import Context, loader
from polls.models import Poll
from django.shortcuts import render
def 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-8
from django.http import HttpResponse
from django.template import Context, loader
from polls.models import Poll
from django.shortcuts import render
from django.http import Http404
def 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-8
from django.http import HttpResponse
from django.template import Context, loader
from polls.models import Poll
from django.shortcuts import render, get_object_or_404
def 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})s
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)
再次编写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/点击打开链接