我是Django框架的新手,似乎無法確定爲什麼我的detail.html不能正確呈現。看起來好像我的forloop迭代選擇問題.choice_set.all沒有被擊中。如果有人能幫助確定爲什麼它會非常有幫助。Django教程:.choice_set.all不被調用
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 %}
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}
</label><br />
<input type="radio" name="choice" id="choice{{ forloop.counter }}"
value="{{ choice.id }}" />
{% endfor %}
<input type="submit" value="Vote" />
</form>
Views.py
from django.http import HttpResponseRedirect, HttpResponse
from django.template import loader
from django.urls import reverse
from django.shortcuts import get_object_or_404, render
from .models import Choice, Question
# Long Method of return HttpResponse
# def index(request):
# latest_question_list = Question.objects.order_by('-pub_date')[:5]
# template = loader.get_template('polls/index.html')
# context = {
# 'latest_question_list': latest_question_list,
# }
def index(request):
latest_question_list = Question.objects.order_by('pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
# render takes the request (object,template,dictionary<optional>)
# def detail(request, question_id):
# try:
# question = Question.objects.get(pk=question_id)
# except Question.DoesNotExist:
# raise Http404("Question does not exist")
# return render(request, 'polls/detail.html', {'question': question})
# SHORTCUT TO USE GET AND RASIE 404
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': 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,)))
urls.py
# map views to url
from django.conf.urls import url
from django.conf.urls import include
from . import views
app_name = 'polls'
urlpatterns = [
#ex: polls/
url(r'^$', views.index, name='index'),
#ex: /polls/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
#ex: /polls/5//results/
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
#ex: /polls/5/vote
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
**這裏是我的數據模型** model.py
# Pythons Imports for built in modules
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
#string method for question object representation
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
# Running python manage.py makemigrations polls instructs django of
# changes to your model
問題模型好嗎? – Bobby
我已經添加了我的模型,也是由於錯誤,我指的是我的輸出在我的Forloop中繼續下降到「你沒有選擇一個選項」。 – user3728367
我在下面的回答不正確。 choice_set在模板中完全有效。解決辦法也很好。我不確定現在究竟是什麼造成了這個問題。 – Bobby