django笔记--4

编写一个简单的表单

更新一下前面编写的投票详细页面的模板("polls/detail.html"),让它包含一个 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>

简要说明:

  • 上面的模板在 Question 的每个 Choice 前添加一个单选按钮。
    • 每个单选按钮的 value 属性是对应的各个 Choice 的 ID。
    • 每个单选按钮的 name 是 “choice”。
    • 这意味着,当有人选择一个单选按钮并提交表单时,它将发送一个 POST 数据 choice=#,其中 # 为选择的 Choice 的 ID。这是 HTML 表单的基本概念。
  • 我们设置表单的 action 为 {% url 'polls:vote' question.id %},并设置 method="post"。
    • 使用 method="post"(与其相对应的是 method="get")是非常重要的,因为这个提交表单的行为会改变服务器端的数据。
    • 无论何时,**当你需要创建一个改变服务器端数据的表单时,请使用 method="post" 。
    • 这不是 Django 的特定技巧;这是优秀的网站开发技巧。
  • forloop.counter 指示 for 标签已经循环多少次。
  • 由于我们创建一个 POST 表单(它具有修改数据的作用),所以我们需要小心跨站点请求伪造。
    • 不用太担心,因为 Django 自带了一个非常有用的防御系统。简而言之,所有针对内部 URL 的 POST 表单都应该使用 {% csrf_token %} 模板标签。

创建一个 Django 视图来处理提交的数据。在前面我们已经为投票应用创建了一个 URLconf(polls/urls.py文件中),包含:path('<int:question_id>/vote/', views.vote, name='vote'),
还创建了一个 vote() 函数的虚拟现实。将下面代码添加到 polls/views.py

from django.http import HttpResponse, 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:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            '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=(question.id,)))

简要说明:

  • request.POST 是一个类字典对象,让你可以通过关键字的名字获取提交的数据。
    • 例子中,request.POST['choice'] 以字符串形式返回选择的 Choice 的 ID。
    • request.POST 的值永远是字符串。
    • 注意,Django 还以同样的方式提供 request.GET 用于访问 GET 数据--但我们在代码中显式地使用 request.POST,以保证数据只能通过 POST 调用改动。
  • 如果在 request.POST['choice'] 数据中没有提供 choice,POST 将引发一个 KeyError。
    • 上面的代码检查 KeyError,如果没有给出 choice 将重新显示 Questin 表单和一个错误信息。
  • 在增加 Choice 的得票数之后,代码返回一个 HTTPResponseRedirect 而不是常用的 HttpResponse。
    • HTTPResponseRedirect 只接收一个参数:用户将要被重定向的 URL。

正如上面的Python注释所指出的,在成功处理POST数据之后,应该始终返回HttpResponseRedirect。这篇技巧并不是针对Django的;一般来说,它是一个很好的Web开发实践。

  • 在这个例子中,我们在 HTTPResponseRedirect 的构造函数中使用 reverse() 函数。
    • 这个函数避免了我们在视图函数中硬编码 URL。
    • 它需要我们给出想要跳转的视图的名字和该视图所对应的 URL 模式中需要给该视图提供参数。

在前面代码中,重定向的 URL 将调用 ‘results’ 视图来显示最终的页面。
HTTPRequest 是一个 HTTPRequest 对象,请求和相应的文档

当有人对 Question 投票后,vote() 视图将请求重定向到 Question 的结果界面。
polls/views.py 添加

from django.shortcuts import get_object_or_404, render


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

hare
2020.12.16

原文地址:https://www.cnblogs.com/hare1925/p/14133742.html