zoukankan      html  css  js  c++  java
  • 4、表单和视图

    该系列的博客都是按照这个教程上面的内容整理总结出来的,主要是为了方便自己复习和巩固的。http://www.kancloud.cn/wizardforcel/django-chinese-docs-18/98847。

    1、让我们把在上一篇教程中编写的 poll 的 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>
    

      简单的总结下:

    • 上面的模板中为每个投票选项设置了一个单选按钮。每个单选按钮的 value 是投票选项对应的 ID 。每个单选按钮的 name 都是 “choice”。这意味着,当有人选择了一个单选按钮并提交了表单,将会发送 的 POST 数据是 choice=3。这是 HTML 表单中的基本概念。
    • 我们将 form 的 action 设置为 {% url 'polls:vote' poll.id %},以及设置了method="post"` 。使用 method="post" ( 而不是 method="get") 是非常重要的,因为这种提交表单的方式会改变服务器端的数据。 当你创建一个表单为了修改服务器端的数据时,请使用 method="post" 。这不是 Django 特定的技巧;这是优秀的 Web 开发实践。
    • forloop.counter 表示 for 标签在循环中已经循环过的次数
    • 由于我们要创建一个POST form ( 具有修改数据的功能 ),我们需要担心跨站点请求伪造 ( Cross Site Request Forgeries )。 值得庆幸的是,你不必太担心这一点,因为 Django 自带了一个非常容易使用的系统来防御它。 总之,所有的 POST form 针对内部的 URLs 时都应该使用 {% csrf_token %} 模板标签。

    现在,让我们来创建一个 Django 视图来处理提交的数据。 记得吗?在s中,我们为上一篇博客中polls 应用创建了一个 URLconf 配置中包含有这一行代码:

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

      我们还创建了一个虚拟实现的 vote() 函数。让我们创建一个真实版本吧。在 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 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 voting form.
            return render(request, 'detail.html', {
                'poll': p,
                'error_message': "You didn't select a choice.",
            })
        else:
            selected_choice.votes += 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() 视图会重定向到投票结果页。让我们来编写这个视图

    def results(request, poll_id):
        poll = get_object_or_404(Poll, pk=poll_id)
        return render(request, 'results.html', {'poll': poll})
    

      

    这几乎和 教程 第3部分 中的 detail() 视图完全一样。 唯一的区别就是模板名称。 稍后我们会解决这个冗余问题。

    现在,创建一个 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 %}">Vote again?</a>
    

    现在我们看到的页面结果如下:

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

     选择一个进行投票,投票结果跳转的页面如下:

  • 相关阅读:
    GridView
    母版页
    Ajax完整结构和删除
    Ajax1
    JQuery动画
    JQuery基础
    LinQ高级查询
    C#简单的学籍管理系统(数据库变更由原来的SQLserver改为SqLite)
    C#两个数只能进行+1,-1,*2操作。求使得两个数相等的最小步骤
    C#求最小公倍数与最大公约数
  • 原文地址:https://www.cnblogs.com/wyl9527/p/6671891.html
Copyright © 2011-2022 走看看