djangoの汎用ビューを使用したときのの質問です。
あるobject(Question)の詳細表示をするというコードです
モデルQuestionは
import datetime from django.db import models from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now
viewのコードは
from django.http import HttpResponseRedirect #from django.template import loader from django.shortcuts import get_object_or_404, render #from django.http import Http404 from django.urls import reverse from django.views import generic from .models import Question, Choice # class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.order_by('-pub_date')[:5] # class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.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>
質問
上記class DetailViewではmodel = Questionでモデルの情報を渡していて、テンプレートpolls/detail.htmlでは<h1>{{ question.question_text }}</h1>で参照している。
大文字Questionと小文字qestionでは解決できないのではないでしょうか。
ところがこのコードは実際正常に動作しています。
解説文では**__ Django モデル (Question) を使用していて、 Django はコンテキスト変数にふさわしい名前を決めることができるからです。__**
とありますがどうなんでしょうか。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/09/26 09:13