Django App(四) Submit a form

andayhou 2018-01-24 原文

Django App(四) Submit a form

      经过前面的努力,到这里我们已经基本完成了,从服务器到浏览器的数据下发,还没有解决从浏览器到服务器的数据上传,这一节将创建一个Form获取从浏览器提交的数据

    1.新建Form

       接着前面建的项目,网上调查,每一个Question有多个Choice,当用户针对特定问题,可以提交选择,数据库记录每个Choice的vote数,所以新建:

       polls/templates/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>

       {% url ‘polls:vote’ question.id %}的写法,是为了防止页面硬编码[查看上一篇内容],引入的url的另一种写法, polls:vote 的写法是给polls/urls.py 加了url命名空间:

 1 from django.urls import path
 2 from . import views
 3 app_name="polls"
 4 urlpatterns=[
 5     path('',views.index,name='index'),
 6     path('<int:question_id>/detail',views.detail,name="detail"), #定义detail view
 7     path('<int:question_id>/results',views.results,name='results'),#定义格式:/参数[参数类型为int]/results
 8     #这里将原来的vote/<int:question_id>改成<Vote/<int:question_id>
 9     path('vote/<int:question_id>',views.vote,name='vote')  #定义格式:vote/参数[参数类型为int]
10 ]

        上面建的表单要提交一个question_id 和 Choice_Id 到 /vote view,为了表单提交数据的安全性,这里指定使用POST传输,这点view没有特别要求,改造view/vote 对指定的question_id的choice_id的votes+1

      2.接收Form数据并处理业务

         修改polls/views.py/vote如下,(为了方便对比这里贴出来整个Views.py): 

 1 from django.shortcuts import get_object_or_404, render
 2 from django.http import HttpResponseRedirect, HttpResponse
 3 from django.urls import reverse
 4 
 5 from .models import Choice, Question
 6 # ...
 7 def vote(request, question_id):
 8     question = get_object_or_404(Question, pk=question_id)
 9     try:
10         selected_choice = question.choice_set.get(pk=request.POST['choice'])
11     except (KeyError, Choice.DoesNotExist):
12         # Redisplay the question voting form.
13         return render(request, 'polls/detail.html', {
14             'question': question,
15             'error_message': "You didn't select a choice.",
16         })
17     else:
18         selected_choice.votes += 1
19         selected_choice.save()
20         # Always return an HttpResponseRedirect after successfully dealing
21         # with POST data. This prevents data from being posted twice if a
22         # user hits the Back button.
23         return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
24 
25 def index(request):
26     latest_question_list = Question.objects.order_by('-pub_date')[:5]
27 
28     context = {
29         'latest_question_list': latest_question_list,
30     }
31     return  render(request,'polls/index.html',context)
32 # ...
33 def detail(request, question_id):
34     question = get_object_or_404(Question, pk=question_id)
35     return render(request, 'polls/detail.html', {'question': question})
36 
37 def results(request, question_id):
38     response = "You're looking at the results of question %s."
39     return HttpResponse(response % question_id)

 

           编辑polls/templates/polls/index.html如下:

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

          启动站点,浏览http://localhost:8000/polls/

         

            投票完成之后,查询数据:

            

 

发表于 2018-01-24 12:03 RemiHoston 阅读() 评论() 编辑 收藏

 

版权声明:本文为andayhou原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/andayhou/p/8340994.html

Django App(四) Submit a form的更多相关文章

  1. 第九章 常用模块

    第九章 常用模块 第九章 常用模块 1.模块介绍                                […]...

  2. Python3学习笔记(3)集合、文件操作、字符转编码

      —————个人学习笔记—̵ […]...

  3. Python 变量 (上)

    标识符 标识符是由字母,数字和下划线构成。 标识符不能以数字开头。 标识符是区分大小写的。 下划线开头的标识符 […]...

  4. python学习笔记

    python学习笔记 第一章 计算机基础 1.1 硬件 计算机基础的硬件: CPU/内存/主板硬盘/网卡/显卡 […]...

  5. python学习笔记(二)、字符串操作

     该一系列python学习笔记都是根据《Python基础教程(第3版)》内容所记录整理的   1.字符串基本操 […]...

  6. Python学习笔记整理Module1

    编程语言介绍 Python介绍 Python安装 第一个Python程序 变量 程序交互 格式化输出 数据运算 […]...

  7. python函数定义及作用域

    函数 按照过程编写代码,一般功能都是一次性的,非常不好维护,把功能封装集成,方便二次开发和维护 语法定义:在P […]...

  8. PYCHRARM界面配置学习笔记

      Pycharm的主题现在比较流行的是黑色和灰色,我之前用LINUX的时候,比较喜欢LINUX的代码风格,所 […]...

随机推荐

  1. N皇后问题 回溯非递归算法 C++实现2

    N皇后问题 回溯非递归算法 C++实现2 运行结果   代码如下 1 #include <bits/st […]...

  2. Win10下 VS2017 安装失败 未能安装包“Microsoft.VisualStudio.AspNet45.Feature,version=15.0.26208.0”

    Win10下 VS2017 安装失败 未能安装包“Microsoft.VisualStudio.AspNet4 […]...

  3. 流程管理

    1.流程管理的用法是什么样的? 2.怎么发起想要的流程? 3.审批的人要是怎么审批通过? 4.流程审核是不是要 […]...

  4. 微信小程序开发视频教程学习(第3天)2:PHP测验错误题分析

    1.PHP 语法与下列哪种最相似? 您的回答:JavaScript 正确答案:Perl 和 C 2.请判断以下 […]...

  5. java 进销存 商户管理系统 库存管理 销售报表 SSM项目 客户管理 – yuwaimingser

    java 进销存 商户管理系统 库存管理 销售报表 SSM项目 客户管理 系统介绍: 1.系统采用主流的 SS […]...

  6. 防止系统锁屏-python、C++实现

    一、背景 作为一个开发,我的电脑经常是一个礼拜不关机,甚至时间更久,不知道在其他人看来这是不是一个常规操作。在 […]...

  7. 2018世界杯球迷群体分析实录 !(附完整版研究报告)

    文章转载自酷鹅俱乐部 本文多图,建议阅读8分钟。 本文联合腾讯指数,为您带来更有看点、更具价值的世界杯球迷群体 […]...

  8. 如何进行用户行为分析并提高用户粘性

      当下,在互联网高速发展的今天,各类产品层出不穷。从一开始做好一些特定功能满足用户的特定需求,到现在分析用户 […]...

展开目录

目录导航