django初学教程 投票应用 04 编写表单
https://docs.djangoproject.com/zh-hans/3.2/intro/tutorial04/
编写一个简单的表单
form表示表单:
# detail.html
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
<fieldset>
    <legend><h1>{{ question.question_text }}</h1></legend>
    {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
    {% 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 %}
</fieldset>
<input type="submit" value="Vote">
</form>
投票会修改服务器端数据的表单,需要设置method="post"。
for循环:在question的每个choice前添加一个单选按钮(参考input标签)。
forloop.counter 指示 for 标签已经循环多少次。
csrf_token这个标签用于 CSRF(Cross-site request forgery) 保护,跨站请求伪造保护。
vote视图
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,)))
请求和响应对象参考:
https://docs.djangoproject.com/zh-hans/3.2/ref/request-response/
https://www.runoob.com/django/django-views.html
- 
request.POST是一个类字典对象,让你可以通过关键字的名字获取提交的数据。 这个例子中,request.POST['choice']以字符串形式返回选择的 Choice 的 ID。request.POST的值永远是字符串。注意,Django 还以同样的方式提供 request.GET用于访问 GET 数据 —— 但我们在代码中显式地使用request.POST,以保证数据只能通过 POST 调用改动。
- 
如果在 request.POST['choice']数据中没有提供choice, POST 将引发一个KeyError。上面的代码检查KeyError,如果没有给出choice将重新显示 Question 表单和一个错误信息。
- 
在增加 Choice 的得票数之后,代码返回一个 HttpResponseRedirect,它只接收一个参数:用户将要被重定向的 URL。
- 
reverse函数用于反转results和question.id的位置,获得正确的url链接。 
修改results视图:
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})
创建results.html模板:
<h1>{{ question.question_text }}</h1>
<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/1/:

投票结果:

使用通用视图:代码精简
detail、results、index视图存在冗余问题,共同特点:
根据URL中的参数从数据库中获取数据、载入模板文件然后返回渲染后的模板。
Django提供快捷方式:通用视图系统。
将投票应用转换成通用视图步骤:
- 转换 URLconf。
- 删除一些旧的、不再需要的视图。
- 基于 Django 的通用视图引入新的视图。
改良URLconf
# polls/urls.py
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]
路径字符串中匹配模式的名称已经由 <question_id> 改为 <pk>(更改的部分原因参考下方改良视图部分)。
改良视图
# polls/views.py
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from .models import Choice, Question
class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'
    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'
def vote(request, question_id):
    ... # same as above, no changes needed.
使用了两个通用视图:ListView 和 DetailView,分别抽象“显示一个对象列表”和“显示一个特定类型对象的详细信息页面”这两种概念。
- model属性表示通用视图将要作用的模型(Question)
- DetailView期望从URL中捕获名为"- pk"的主键值,所以- URLconf中将- question_id改为- pk。
默认情况下,通用视图 DetailView使用一个叫做 <app name>/<model name>_detail.html 的模板。在我们的例子中,它将使用 "polls/question_detail.html" 模板。template_name 属性是用来告诉 Django 使用一个指定的模板名字,而不是自动生成的默认名字。 我们也为 results 列表视图指定了 template_name —— 这确保 results 视图和 detail 视图在渲染时具有不同的外观,即使它们在后台都是同一个 DetailView 。
类似地,ListView 使用一个叫做 <app name>/<model name>_list.html 的默认模板;我们使用 template_name 来告诉 ListView使用我们创建的已经存在的 "polls/index.html" 模板。
在之前的教程中,提供模板文件时都带有一个包含 question 和 latest_question_list 变量的 context。对于 DetailView , question 变量会自动提供—— 因为我们使用 Django 的模型(Question), Django 能够为 context 变量决定一个合适的名字。然而对于 ListView, 自动生成的 context 变量是 question_list。为了覆盖这个行为,我们提供 context_object_name 属性,表示我们想使用 latest_question_list。作为一种替换方案,你可以改变你的模板来匹配新的 context 变量 —— 这是一种更便捷的方法,告诉 Django 使用你想使用的变量名。
重新启动服务器,结果正常:

下一部分学习怎样测试投票应用。
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号