Django入门笔记【四】
2015-06-24 15:54
513 查看
入门笔记翻译整理自:https://docs.djangoproject.com/en/1.8/
*该笔记将使用一个关于投票网络应用(poll application)的例子来阐述Django的用法。
表单和通用视图(Forms&Generic Views)
以上代码:首先,为选项生成了radio按钮;其次,当你创建数据服务端(data server-side)的表单时,要始终使用method="post";然后,forloop.counter对循环进行计数;最后,由于使用了POST方法,我们需要关心跨站请求伪造(Cross Site Request Forgeries),不过Django提供了对此的保护机制。
我们在入门基础【三】中创建了如下代码:
向polls/views.py中添加如下代码:
当有人在问题下投票后,vote()视图会重新定向至结果页面,该页面视图如下:
现在,创建polls/results.html模板:
这些视图代表了一种常见情形:根据URL中的被传递参数,从数据库中获取数据,载入模板,返回渲染后的模板。对于此类情形,可以使用Django提供的通用视图系统。
为了使用通用视图进行代码简化,我们需要进行以下改变:
1.转换URLconf;2.删除陈旧不必要的视图;3.引入基于通用视图的新视图
注意第二和第三个模式从question_id变成了pk。
-- The End --
*该笔记将使用一个关于投票网络应用(poll application)的例子来阐述Django的用法。
表单和通用视图(Forms&Generic Views)
1. 简单的表单
修改detail.html中的代码,使之含有<form>元素:# polls/templates/polls/detail.html <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{%url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> </form>
以上代码:首先,为选项生成了radio按钮;其次,当你创建数据服务端(data server-side)的表单时,要始终使用method="post";然后,forloop.counter对循环进行计数;最后,由于使用了POST方法,我们需要关心跨站请求伪造(Cross Site Request Forgeries),不过Django提供了对此的保护机制。
我们在入门基础【三】中创建了如下代码:
# polls/urls.py url(r'^(?P<question_id>[0-9]+/vote/$', views.vote, name='vote'),
向polls/views.py中添加如下代码:
# polls/views.py from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from .models import Choice, Question # ... def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html',{ 'question': p, ''error_message': "You didn't select a choice.", }) else: selected_choice.vote += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
当有人在问题下投票后,vote()视图会重新定向至结果页面,该页面视图如下:
# polls/views.py from django.shortcuts import get_object_or_404, render def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question})
现在,创建polls/results.html模板:
# polls/templates/polls/results.html <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote {{ choice.votes | pluralize }}</li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">Vote again?</a>
2. 使用通用视图
注意到,detail()和results()视图很简单,并且冗余。index()视图也很相似。这些视图代表了一种常见情形:根据URL中的被传递参数,从数据库中获取数据,载入模板,返回渲染后的模板。对于此类情形,可以使用Django提供的通用视图系统。
为了使用通用视图进行代码简化,我们需要进行以下改变:
1.转换URLconf;2.删除陈旧不必要的视图;3.引入基于通用视图的新视图
3. 修改URLconf
# polls/urls.py from django.conf.urls import url from . import views ulrpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'), url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ]
注意第二和第三个模式从question_id变成了pk。
4. 修改Views
# polls/views.py from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.views import generic from .models import Choice, Question class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): ... # same as above
-- The End --
相关文章推荐
- Google IP地址范围
- Go语言Slice操作.
- poj -- 1042 Gone Fishing(枚举+贪心)
- Category
- Suppress warning “Category is implementing a method which will also be implemented b
- 织梦dedecms转joomla!,如何自动添加文章分类-category
- django 简单会议室预约(3)
- Algorithms—74.Search a 2D Matrix
- [转载] goroutine背后的系统知识
- Netty 权威指南之Google protobuf 编解码
- Go图片上传
- Go获取当前执行路径及图片的加解码
- edx---Mongo,could not connect to localhost:27017:
- Google Chrome浏览器调试功能介绍
- HDU 1533 Going Home(最小费用流)
- Django permission
- google play SDK 游戏排行榜的接入分享
- [Leetcode] Basic Calculator
- UVa 11292 The Dragon of Loowater 勇者斗恶龙
- goagent安装和使用