晚上好。我是Django的新手,我在玩民意調查教程。我添加了一個新的模型「部分」,作爲一組問題的父母。這是工作正常,因爲它顯示了一個頁面上的一節的所有問題。對象不可迭代和/或NoReverseMatch
我現在要做的是每頁僅顯示一個問題,將答案保存到數據庫並從該部分獲取下一個問題。我嘗試了幾種不同的方式,但沒有任何效果。我希望你們能引導我走向正確的方向。
URLS.PY
urlpatterns = patterns('',
url(
regex=r'^$',
view=UmfrageView.as_view(),
name='umfrage'
),
url(
regex=r'^(?P<slug>[-\w]+)/$',
view=DetailView.as_view(),
name='detail'
),
url(
regex=r'^(?P<question_id>\d+)/$',
view=vote,
name='vote'
),
)
試圖從一節的第一個問題:
VIEWS.PY
class DetailView(ListView):
model = Question
context_object_name = 'latest_question_list'
template_name = 'itbarometer/detail.html'
def get_queryset(self, **kwargs):
# Get question set via section slug
slug = self.kwargs.get('slug') or kwargs.get('slug')
qs = Question.objects.filter(section__slug=slug).order_by('pub_date')
try:
return qs[0]
except IndexError:
return None
def vote(request, question_id):
p = get_object_or_404(Question, pk=question_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form
return render(request, 'itbarometer/umfrage.html', {
'question': p,
'error_message': "Bitte eine Antwort auswählen.",})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:umfrage'))
HTML模板detail.html:
{% if latest_question_list %}
{% for question in latest_question_list %}
<form action="{% url 'polls:vote' question.id %}" method="post">
<fieldset>
<legend>{{ question.question_text }}</legend>
{% 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 %}
</fieldset>
<input class="button small" type="submit" value="Save" />
</form>
{% endfor %}
{% endif %}
但我會得到
異常值:
'問題'對象不可迭代
當detail.html刪除「在latest_question_list問題:」我會得到
異常類型:NoReverseMatch 異常值: [R EVERSE爲「投票」與參數「(」「)」和關鍵字參數'{}' 未找到。嘗試1個模式:[u'umfragen /(?P \ d +)/ $']
如果我從表單操作中進一步刪除「{%url」polls:vote'question.id%}「將會得到一個空的表單佈局。我懷疑沒有數據傳輸。
可能是什麼問題?
編輯:models.py
class Section(models.Model):
section_text = models.CharField(max_length=255)
section_description = models.TextField(blank=False)
slug = models.SlugField(unique=True, null=True)
def __unicode__(self):
return self.section_text
def save(self, *args, **kwargs):
self.slug = slugify(self.section_text)
super(Section, self).save(*args, **kwargs)
class Question(models.Model):
section = models.ForeignKey(Section)
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question_text
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date < now
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
感謝您的大開眼界。 –