Django 表单

HTML表单

  表单在网页中主要负责数据采集功能。一个表单有三个基本组成部分:

1. 表单标签:包含处理表单数据所用CGI程序的URL和数据提交到服务器的方法。

<form action="URL" method="GET|POST">
</form>

2. 表单域:包含文本框、密码框、隐藏域、多行文本框、复选框、单选框、下拉选择框和文件上传框等。

<input type="text|password|hidden|checkbox|radio|file" name="" value="">    # 文本框、密码框、隐藏域、复选框、单选框和文件上传框
<textarea name="" cols="" rows="" wrap="virtual"></textarea>    # 多行文本框
<select name="" size="" multiple><option value="" selected></option></select>    # 下拉选择框

3. 表单按钮:包括提交按钮、复位按钮和一般按钮。用于将数据传送到服务器上的CGI脚本或者取消输入,还可以用表单按钮来控制其他定义了处理脚本的处理工作。

<input type="submit|reset" name="" value="">    # 提交、复位按钮
<input type="button" name="" value="" onClick="">    # 一般按钮

编写一个表单

编写模板文件 polls/templates/polls/detail.html,让它包含一个 HTML <form> 元素:

<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>
  • <label> 标签为 input 元素定义标记,for 属性与 input 元素的 id 属性相同。当用户选择该标签时,浏览器会自动转到和标签相关的表单控件上。

添加视图函数 vote() 到 polls/views.py :

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from .models import Choice, Question

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        choices = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't make a choice.",
        })
    else:
        choices.votes += 1
        choices.save()
        return HttpResponseRedirect(reverse('polls:result', args=(question.id,)))
  • request.POST 是一个类字典对象,可以通过关键字的名字获取提交的数据。request.POST['choice'] 以字符串形式返回 choice.id 。
  • HttpResponseRedirect 只接收一个参数:将要被重定向的 URL 。
  • reverse() 函数避免了在视图函数中硬编码 URL。包含想要跳转的视图的名字和对应的 URL 模式中给视图提供的参数。

当用户对 Question 进行投票后,vote() 视图将请求重定向到 Question 的 result 界面。result() 视图函数:

from django.shortcuts import get_object_or_404, render

def result(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/result.html', {'question': question})

创建一个 polls/result.html 模板:

{{ question.question_text }}

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

配置 polls/url.py 来映射到视图:

from django.urls import path
from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
    path('<int:question_id>/result/', views.result, name='result'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

 

posted @ 2019-04-03 18:23  PIPO2  阅读(139)  评论(0编辑  收藏  举报