为Django app创建视图(下)

上一篇为Django app创建视图(上)写到创建视图,初步创建了index和detail页面,这篇继续写创建视图。首先是创建表单。

创建表单

逻辑与普通页面类似,只不过需要对detail页面进行更新,使其具有提交表单的功能。改写polls/templates/polls/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>

这里
{% csrf_token %}用来防止跨站点请求伪造。
{{ forloop.counter }}用来记录for标记循环的次数

编写视图函数

在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’]以字符串形式返回所选选项的ID。request.POST值总是字符串。

注意,Django还提供request.GET用于以相同的方式访问GET数据–但是我们显式地使用request.POST在我们的代码中,确保只通过POST调用更改数据。

request.POST如果POST数据中没有提供choice,[‘choice’]将引发KeyError。上面的代码检查KeyError,如果没有给出选择,则重新显示带有错误消息的问题表单。

在计数之后,代码返回一个HttpResponseRedirect,而不是一个普通的HttpResponse。HttpResponseRedirect只接受一个参数:用户将被重定向到的URL。

这是一种很好的Web开发实践,即在成功处理POST数据之后,应该始终返回httpresponseredict。

在本例中,我们在HttpResponseRedirect构造函数中使用reverse()函数。此函数有助于避免在view函数中硬编码URL。它提供了我们要传递控制的视图的名称以及指向该视图的URL模式的变量部分。在本例中,使用我们在教程3中设置的URLconf,这个reverse()调用将返回如下字符串。

results()视图函数

根据业务逻辑,当人提交完表单后,浏览器会跳转到结果页面。result()视图函数如下:

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>

总结

这部分主要注意为了防止跨站点请求伪造需要加上{% csrf_token %}以及HttpResponseRedirect的重定向

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值