zoukankan      html  css  js  c++  java
  • Django教程:第一个Django应用程序(4)

    Django教程:第一个Django应用程序(4)

     

    2013-10-09 磁针石

     

    #承接软件自动化实施与培训等gtalk:ouyangchongwu#gmail.comqq 37391319

    #博客:http://blog.csdn.net/oychw

    #版权所有,转载刊登请来函联系

    # 深圳测试自动化python项目接单群113938272深圳广州软件测试开发 6089740

    #深圳湖南人业务户外群 66250781武冈洞口城步新宁乡情群49494279

    #参考资料:https://docs.djangoproject.com/en/1.5/intro/tutorial01/

    # http://django-chinese-docs.readthedocs.org/en/latest/intro/tutorial01.html

    #本文的图片没有上传,完整的文档参见:python模块笔记:http://t.cn/z8ggk71

     

    本节关注简单的窗体处理和简化代码。

    简单表单

    更新polls/detail.html:

    <h1>{{ poll.question }}</h1>

    {% if error_message %}<p><strong>{{ error_message}}</strong></p>{% endif %}

    <form action="{% url 'polls:vote' poll.id %}"method="post">

    {% csrf_token %}

    {% for choice in poll.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>

    • 模板为每个投票选项显示了单选按钮。单选按钮的值是投票选项对应的 ID 。每个单选按钮的 name 都是“choice”。
    • 我们将 form 的 action 设置为 {% url 'polls:vote' poll.id %},方法为="post" 。
    • forloop.counter 表示 for 标签在循环中已经循环过的次数
    • {% csrf_token %} 用于防止交叉站点伪造请求。

    修改投票视图:

    from django.shortcuts import get_object_or_404, render

    from django.http import HttpResponseRedirect, HttpResponse

    from django.core.urlresolvers import reverse

    from polls.models import Choice, Poll

    # ...

    def vote(request, poll_id):

        p = get_object_or_404(Poll,pk=poll_id)

        try:

            selected_choice =p.choice_set.get(pk=request.POST['choice'])

        except (KeyError,Choice.DoesNotExist):

            # Redisplay the poll votingform.

            return render(request,'polls/detail.html', {

                'poll': p,

                'error_message':"You didn't select a choice.",

            })

        else:

            selected_choice.votes += 1

            selected_choice.save()

            # Always return anHttpResponseRedirect after successfully dealing

            # with POST data. Thisprevents data from being posted twice if a

            # user hits the Back button.

            returnHttpResponseRedirect(reverse('polls:results', args=(p.id,)))

    • request.POST 是一个类字典的对象, request.POST['choice'] 返回了选择投票项的 ID。 request.POST 的值是字符串。类似的有request.GET
    • 如果 choice 未在 POST 数据中提供 request.POST['choice'] 将抛出 异常。
    • 在增加了投票选项的统计数后,代码返回HttpResponseRedirect 对象而不是HttpResponse 对象。 HttpResponseRedirect 对象需参数:重定向的 URL。
    • 我们在 HttpResponseRedirect 的构造方法中使用了 reverse() 函数。它避免在视图函数中硬编码 URL 。它指定了我们想要的跳转的视图函数名以及视图函数中 URL 模式相应的可变参数。reverse() 将会返回如下:

    '/polls/3/results/'

    results视图

    def results(request, poll_id):

       poll = get_object_or_404(Poll, pk=poll_id)

       return render(request, 'polls/results.html', {'poll': poll})

    polls/results.html 模板:

    <h1>{{ poll.question }}</h1>

    <ul>

    {% for choice in poll.choice_set.all %}

        <li>{{ choice.choice_text}} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>

    {% endfor %}

    </ul>

    <a href="{% url 'polls:detail' poll.id %}">Voteagain?</a>

    现在,在浏览器中访问 /polls/1/ 并投票。将看到结果页数据有更新。如果你没有选择投票选项就提交了,将会看到错误的信息。

    使用通用视图优化代码

    通用视图可以完成一些通用性的操作:

    1. 转换URLconf 。
    2. 删除一些不需要的视图。
    3. 基于通用视图修改视图

    修改polls/urls.py:

    from django.conf.urls import patterns, url

    from polls import views

    urlpatterns = patterns('',

        url(r'^$', views.IndexView.as_view(),name='index'),

        url(r'^(?P<pk>d+)/$', views.DetailView.as_view(),name='detail'),

        url(r'^(?P<pk>d+)/results/$',views.ResultsView.as_view(), name='results'),

        url(r'^(?P<poll_id>d+)/vote/$',views.vote, name='vote'),

    )

    修改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 polls.models import Choice, Poll

     

    class IndexView(generic.ListView):

        template_name = 'polls/index.html'

        context_object_name = 'latest_poll_list'

     

        def get_queryset(self):

            """Return thelast five published polls."""

            return Poll.objects.order_by('-pub_date')[:5]

     

     

    class DetailView(generic.DetailView):

        model = Poll

        template_name = 'polls/detail.html'

     

     

    class ResultsView(generic.DetailView):

        model = Poll

        template_name = 'polls/results.html'

     

    def vote(request, poll_id):

        ....

     

    通用视图: ListViewDetailView 。这两个视图分别用于抽象“显示一系列对象” 和 “显示一个特定类型的对象的详细信息页”。

    • 每个通用视图通过model属性指定操作对象。
    • DetailView 通用视图可以通过pk指定主键。

    DetailView默认使用模板<app name>/<model name>_detail.html。在我们的例子中,将使用名为 "polls/poll_detail.html" 的模板。属性template_nam可指定的模板名。同样ListView默认使用模板 <app name>/<model name>_list.html;

    在 DetailView 自动提供poll 变量, ListView自动生成变量 poll_list。属性context_object_name可以另外指定变量。

    更多资料参见:generic views documentation.

  • 相关阅读:
    POJ1486 Sorting Slides 二分图or贪心
    POJ2060 Taxi Cab Scheme 最小路径覆盖
    POJ3083 Children of the Candy Corn 解题报告
    以前的文章
    POJ2449 Remmarguts' Date K短路经典题
    这一年的acm路
    POJ3014 Asteroids 最小点覆盖
    POJ2594 Treasure Exploration 最小路径覆盖
    POJ3009 Curling 2.0 解题报告
    POJ2226 Muddy Fields 最小点集覆盖
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3359711.html
Copyright © 2011-2022 走看看