django系列8:最佳化vote頁面,使用通用視圖降低代碼冗餘

來源:互聯網
上載者:User

標籤:直接   結果   csharp   通用   djang   rgs   self   short   red   

修改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, HttpResponseRedirectfrom django.shortcuts import get_object_or_404, renderfrom django.urls import reversefrom .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, renderdef 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 pathfrom . import viewsapp_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 HttpResponseRedirectfrom django.shortcuts import get_object_or_404, renderfrom django.urls import reversefrom django.views import genericfrom .models import Choice, Questionclass 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頁面,使用通用視圖降低代碼冗餘

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.