django (七) 第一个django app 创建表单

首先,在polls/detail.html里添加<form>:

<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>

下面一次解释一下这段代码的含义:

它的主要功能就是在POLL下选择一个choice,然后点击button提交表单。

  • We set the form’s action to {% url ’polls:vote’ poll.id %}, and we set method="post".Using method="post" (as opposed to method="get") is very important, because the act of submitting thisform will alter data server-side. Whenever you create a form that alters data server-side, use method="post". This tip isn’t specific to Django; it’s just good Web development practice.
  • forloop.counter indicates how many times the for tag has gone through its loop
  • Since we’re creating a POST form (which can have the effect of modifying data), we need to worry about CrossSite Request Forgeries. Thankfully, you don’t have to worry too hard, because Django comes with a very easyto-use system for protecting against it. In short, all POST forms that are targeted at internal URLs should use the {% csrf_token %} template tag.

这一步完成了后,先别刷新页面。和之前一样,修改polls/view.py如下:

# -*- coding: utf-8 -*-
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from polls.models import Poll,Choice

def index(request):
    latest_poll_list = Poll.objects.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})

def results(request,poll_id):
    return HttpResponse("You’re looking at the results of poll %s." %poll_id)

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, ‘polls/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,)))

  • request.POST is a dictionary-like object that lets you access submitted data by key name. In this case,request.POST[’choice’] returns the ID of the selected choice, as a string. request.POST values arealways strings.Note that Django also provides request.GET for accessing GET data in the same way – but we’re explicitlyusing request.POST in our code, to ensure that data is only altered via a POST call.
  • request.POST[’choice’] will raise KeyError if choice wasn’t provided in POST data. The abovecode checks for KeyError and redisplays the poll form with an error message if choice isn’t given.
  •  After incrementing the choice count, the code returns an HttpResponseRedirect rather than a normal HttpResponse. HttpResponseRedirect takes a single argument: the URL to which the user will be redirected (see the following point for how we construct the URL in this case). As the Python comment above points out, you should always return an HttpResponseRedirect aftersuccessfully dealing with POST data. This tip isn’t specific to Django; it’s just goodWeb development practice.
  • We are using the reverse() function in the HttpResponseRedirect constructor in this example. This
    function helps avoid having to hardcode a URL in the view function. It is given the name of the view that we
    want to pass control to and the variable portion of the URL pattern that points to that view. In this case, using
    the URLconf we set up in Tutorial 3, this reverse() call will return a string like


    ’/polls/3/results/’
    ... where the 3 is the value of p.id. This redirected URL will then call the ’results’ view to display the
    final page.

接下来,修改results:

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

然后新建result.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>

整个项目已基本完成,但是稍显繁琐,下面使用generic view系统来改造他一下:

The detail() (from Tutorial 3) and results() views are stupidly simple – and, as mentioned above, redundant.
The index() view (also from Tutorial 3), which displays a list of polls, is similar.
These views represent a common case of basic Web development: getting data from the database according to a
parameter passed in the URL, loading a template and returning the rendered template. Because this is so common,
Django provides a shortcut, called the “generic views” system.
Generic views abstract common patterns to the point where you don’t even need to write Python code to write an app.
Let’s convert our poll app to use the generic views system, so we can delete a bunch of our own code. We’ll just have
to take a few steps to make the conversion. We will:
1. Convert the URLconf.
2. Delete some of the old, unneeded views.
3. Introduce new views based on Django’s generic views.
Read on for details.

首先,打开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 the last 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):
    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, ‘polls/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,)))

时间: 2024-10-10 21:43:32

django (七) 第一个django app 创建表单的相关文章

Python+Django+SAE系列教程11-----request/pose/get/表单

表单request,post,get 首先我们来看看Request对象,在这个对象中包含了一些有用的信息,学过B/S开发的人来说这并不陌生,我们来看看在Django中是如何实现的: 属性/方法 说明 举例 request.path 除域名以外的请求路径,以正斜杠开头 "/hello/" request.get_host() 主机名(比如,通常所说的域名) "127.0.0.1:8000" or"www.example.com" request.g

activiti自定义流程之整合(二):使用angular js整合ueditor创建表单

注:整体环境搭建:activiti自定义流程之整合(一):整体环境配置 基础环境搭建完毕,接下来就该正式着手代码编写了,在说代码之前,我觉得有必要先说明一下activit自定义流程的操作. 抛开自定义的表单不谈,通过之前的了解,我们知道一个新的流程开始,是在启动流程实例(processIntence)的时候,而流程实例依赖于流程定义(processDefinition),流程定义又依赖于流程模型(model). 我们用到的自定义表单需要在创建模型,画模型图的时候就指定表单的名称formKey,需

activiti自己定义流程之整合(二):使用angular js整合ueditor创建表单

基础环境搭建完成,接下来就该正式着手代码编写了,在说代码之前.我认为有必要先说明一下activit自己定义流程的操作. 抛开自己定义的表单不谈.通过之前的了解,我们知道一个新的流程開始.是在启动流程实例(processIntence)的时候,而流程实例依赖于流程定义(processDefinition).流程定义又依赖于流程模型(model). 我们用到的自己定义表单须要在创建模型,画模型图的时候就指定表单的名称formKey.须要保证这个formKey和我们创建的表单名称一致. 表单并不在创建

Flask:03-你离最美的web只差一个:bootstrap与表单

bootstrap与表单 Bootstrap是美国Twitter公司的设计师Mark Otto和Jacob Thornton合作基于HTML.CSS.JavaScript 开发的简洁.直观.强悍的前端开发框架,使得 Web 开发更加快捷. Bootstrap提供了优雅的HTML和CSS规范,它即是由动态CSS语言Less写成.Bootstrap一经推出后颇受欢迎,一直是GitHub上的热门开源项目,包括NASA的MSNBC(微软全国广播公司)的BreakingNews都使用了该项目.国内一些移动

创建表单以及表单元素的使用

创建表单 其基本语法 <form action="url" method=get|post> <input type=submit> <input type=reset> </form> 其中应用的属性 action=url:定义提交表单的格式,可以是url或者电子邮件地 method=get|post:指明提交表单HTTP的方法  在网页中提供一个空格 text:定义单行文本输入框 Password:定义密码 rows:属性定义多行文本

Bootstrap创建表单(一)

Bootstrap表单类型分为三种格式:垂直或基本表单.内联表单.水平表单. 垂直或基本表单(display:block;) 基本的表单结构是 Bootstrap 自带的,个别的表单控件自动接收一些全局样式.下面列出了创建基本表单的步骤: 向父 <form> 元素添加 role="form". 把标签和控件放在一个带有 class .form-group 的 <div> 中.这是获取最佳间距所必需的. 向所有的文本元素 <input>.<tex

activiti自己定义流程之自己定义表单(二):创建表单

注:环境配置:activiti自己定义流程之自己定义表单(一):环境配置 在上一节自己定义表单环境搭建好以后,我就正式開始尝试自己创建表单,在后台的处理就比較常规,主要是针对ueditor插件的功能在前端进行改动. 因为自己的前端相关技术太渣.因此好多东西都不会用,导致改动实现的过程也是破费了一番功夫.头皮发麻了好几天. 既然是用别人的插件进行改动,那么我想假设仅仅是单独的贴出我改动后的代码,可能没有前后进行对照好理解,因此这里就把原代码和改动后的同一时候对照着贴出,以便于朋友们能从对照中更快的

activiti自定义流程之自定义表单(二):创建表单

注:环境配置:activiti自定义流程之自定义表单(一):环境配置 在上一节自定义表单环境搭建好以后,我就正式开始尝试自己创建表单,在后台的处理就比较常规,主要是针对ueditor插件的功能在前端进行修改. 由于自己的前端相关技术太渣,因此好多东西都不会用,导致修改实现的过程也是破费了一番功夫,头皮发麻了好几天. 既然是用别人的插件进行修改,那么我想如果只是单独的贴出我修改后的代码,可能没有前后进行对比好理解,因此这里就把原代码和修改后的同时对比着贴出,以便于朋友们能从对比中更快的得到启发.

webform快速创建表单内容文件--oracle 数据库

使用方法 前台页面这样写就足够了 <form class="stdform" runat="server"> <div id="field_tab_content" runat="server"></div> </form> 新增编辑加载页面(改页面需要继承CreateModel类) Type type; public decimal id = 0; protected void