我在他们的网站上开始了Django教程的通用视图部分,我不断收到此错误。我知道之前已经问过这个问题,但这些答案并没有解决我的问题。我想知道有没有看到错误?我已经删除了导入以整理代码。
urls.py:
app_name = 'polls'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(),
name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
views.py:
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Questions.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Questions
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Questions
template_name = 'polls/results.html'
def vote(request, question_id):
question = get_object_or_404(Questions, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=
(question.id,)))
detail.html:
<h1>{{ object.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' question_id=object.id %}" method="post">
{% csrf_token %}
{% for choice in object.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>
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:results' question.id %}">Vote again?</a>
答案 0 :(得分:0)
您已将模型命名为Questions
,而不是像教程那样命名Question
。详细信息视图使用小写的模型名称作为模板中的模型实例。在您的情况下,这是questions
,与使用question
的模板中的教程不匹配。
这意味着您需要将context_object_name
设置为'question'
,以便您的模板有效:
class ResultsView(generic.DetailView):
model = Questions
context_object_name = 'question'
或者您需要更改模板以使用questions
代替question
。
<h1>{{ questions.question_text }}</h1>
<ul>
{% for choice in questions.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{
choice.votes|pluralize }}</li>
{% endfor %}
</ul>
<a href="{% url 'polls:results' questions.id %}">Vote again?</a>
将模型重命名为Question
是个好主意 - Django中的标准是使用单数而不是复数来表示模型名称。如果您这样做,则必须运行makemigrations
,然后migrate
重命名模型。如果这会导致问题,则可能更容易删除迁移和数据库,然后在新数据库上运行makemigrations
和migrate
。