[Django] 4. ドラムのチュートリアル.4


今日は3から続けて、コードダイエットをポイントに
Write a minimal form
polls/detail.htmlに簡単なフォームを追加します.
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
<fieldset>
    <legend><h1>{{ question.question_text }}</h1></legend>
    {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
    {% 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 %}
</fieldset>
<input type="submit" value="Vote">
</form>
  • 各質問オプションのラジオボタンが表示されます.各ラジオボタンの値は、関連する問題選択項目のIDであり、すなわち、いずれかのラジオボタンを選択してフォームを発行すると、POSTデータchoice=#(選択した項目のID)が送信される.
  • アクションPOSTによりサーバ側データの変更を要求する
  • .
  • forloop.counterはfor文を
  • 回繰り返します
  • 倉庫から提供される{%csrf token%}により、クロスサイト要求キュー(CSRF)
  • を心配する必要はありません.
    CSRF?
    サイト間請求を偽造する.Webサイトの脆弱性攻撃は、ユーザーが自分の意思に基づいて特定のWebサイトに攻撃者を要求できるようにする攻撃です.
    これで、コミットされたデータを処理し、これらのデータを使用していくつかの操作を実行する長期ビューを作成できます.
    # pols/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は、鍵によって送信されたデータにアクセスできる辞書のようなオブジェクトである.ここでお願いpost「choice」は、選択したアンケートのIDを文字列
  • に返す
  • 選択されていない場合、KeyError
  • が発生します.
  • リバース()を使用するURLをハードコーディングする
  • .
    調査が終わったら、直接結果ページに入ります.
    # polls/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>
    Genericビューの使用
    ここで作成したビューはURLから渡され、基本的なWeb開発の一般的な状況を表します.つまり、パラメータに基づいてデータベースからデータをインポートし、テンプレートをロードし、レンダリングテンプレートに戻ります.ドラムはこの一般的な状況に「エネルギービュー」という近道を提供しています
    変換
  • URLconf
  • の不要なビューから一部のビューを削除する
  • 汎用ビューに基づいて新しいビュー
  • を導入する.
    URLConfの修正
    # polls/urls.py
    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'),
    ]
    ビューの変更
    # 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.
    ListViewとDetailViewの2つのGenericビューを使用します.
    各Genericビューはmodelプロパティを使用して、どのモデルが適用されるかを知っています.
    確かにJENNERICviewを使ったらコードがもっとセクシーになった!