django系列8:优化vote页面,使用通用视图降低代码冗余

Posted zhizhiyin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django系列8:优化vote页面,使用通用视图降低代码冗余相关的知识,希望对你有一定的参考价值。

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

  

修改views.py中vote的部分,和detail.html联合起来,记录票数,编辑对应的操作反馈

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

  

里面用到了重定向,HttpResponseRedirect,重定向页面到 polls:results,传入的content是question.id,这里对投票完成页面的results的views做优化

 

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>

 

details和results的view 有很多代码相同之处,这里修改为使用通用视图,降低代码冗余

修改conf

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‘),
]

  修改views

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.

  

 

至此,教程结束。

剩余的测试代码部分,优化界面部分,打包和引用部分,已经执行过,但是篇幅太长,建议直接登录官网查阅文档。

https://docs.djangoproject.com/en/2.1/intro/tutorial06/

 

以上是关于django系列8:优化vote页面,使用通用视图降低代码冗余的主要内容,如果未能解决你的问题,请参考以下文章

十Django学习之优化表单提交(GETPOST登录注册)

如何利用 django 通用视图?

django 中用于简单通用视图的 extra_context 函数

使用Python Django框架创建一个小型博客

Django REST framwork-03-使用mixin和基于类的通用(generics)视图

Django视图views--白话聊Django系列