Django学习(4)

• 编写一个用于问题显示的表单(form)

form是HTML的一个元素,修改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>

这部分涉及HTML相关内容,不再赘述

• 添加投票界面的相关内容

添加关于polls/views.py的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,)))

相关内容说明:
1、request.POST是类似于字典的对象,可让您通过键名访问提交的数据。在这种情况下, request.POST[‘choice’]以字符串形式返回所选选项的IDrequest.POST值始终是字符串。

请注意,Django还提供request.GET了以相同方式访问GET数据的方法-但我们request.POST在代码中明确使用,以确保仅通过POST调用更改数据。

2、如果没有提供POST数据,那么就会产生KEYERROR异常,重新显示问题表单。

3、在此示例reverse()中,我们在HttpResponseRedirect构造函数中使用该函数 。此功能有助于避免在视图功能中对URL进行硬编码。它提供了我们想要将控制权传递给的视图的名称,以及指向该视图的URL模式的可变部分。在这种情况下,使用我们在教程3中设置的URLconf ,此reverse()调用将返回一个字符串,例如’/polls/3/results/’,其中3是的值question.id。然后,此重定向的URL将调用**‘results’**视图以显示最后一页。

• 投票结果页面相关内容

进行投票之后,vote()视图将重定向到该问题的结果页面,故编写视图在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})

同时创建polls/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>

现在可以运行服务器,来看一看问题页面、投票页面和投票结果显示页面,

• 使用通用视图来减少代码量

detail()results() 的视图函数是非常短并且相似,所以重复的代码是冗余的。
这些视图代表了基本Web开发的一种常见情况:根据URL中传递的参数从数据库获取数据,加载模板并返回渲染的模板。因为这很常见,所以Django提供了一个捷径,称为“通用视图”系统。
为了转换为通用视图系统,需要经过一些步骤:
1. 转换URLconf。
2. 删除一些旧的不需要的视图。
3. 根据Django的通用视图介绍新视图。

修改URL配置
首先对polls/urls.py的URLconf进行修改:

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

修改视图
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.

在这里使用了两个通用视图ListViewDetailView,分别抽象了“显示对象列表”和“显示特定类型的对象的详细信息页面”的概念。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值