Django 2.1入门教程(四)

本文将集中讲解处理表单和精简我们的代码。

写一个简单的表单

编辑polls/detail.html文件如下:

{{ question.question_text }}

{% if error_message %}

{{ error_message }}

{% endif %}
{% csrf_token %} {% for choice in question.choice_set.all %}
{% endfor %}

这样每个问题选项的前面将显示一个单选按钮。

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

处理完POST请求后应该返回一个Redirect,这是一个好的Web开发实践。

vote后跳转到了results视图,编辑polls/views.py文件,修改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})

创建polls/results.html模板如下:

{{ question.question_text }}

    {% for choice in question.choice_set.all %}
  • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}
  • {% endfor %}
Vote again?

使用通用视图来精简代码

detail()results()index()三个视图都是先根据URL中的参数从数据库中读取数据,然后加载模板,最后返回渲染后的模板。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('/', views.DetailView.as_view(), name='detail'),
    path('/results/', views.ResultsView.as_view(), name='results'),
    path('/vote/', views.vote, name='vote'),
]

修改视图

修改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,ListView用于显示一系列对象,DetailView用于显示某个对象的详情。DetailView需要从URL中获取“pk”作为查询参数。

参考:https://docs.djangoproject.com/en/2.1/intro/tutorial04/

 

你可能感兴趣的:(Django)