python - Django 教程 html css python for 循环不起作用

标签 python html css django

我在 djangogirls 教程和 djangoproject.com 的 django 教程中都遇到过这个错误我真的很想学习 django,但我不明白哪里出了问题。

我的 html 页面将不再打印出在我的投票中循环遍历我的选择的 for 循环。

for 循环应该显示输出的地方没有显示任何数据。没有进行 for 循环。

这是我的页面

polls\details.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>

投票\index.html

{% load staticfiles %}

<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

投票\模型.py

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')

    def was_published_recently(self):
        now = timezone.now()
        # return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
        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?'

    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question) # each choice is related to a single question
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

class Answer(models.Model):
    question = models.ForeignKey(Question) # each answer is related to a single question
    answer = models.ForeignKey(Choice) # each answer is related to the choices above # is this set up correctly?
    answer_text = models.CharField(max_length=200)

    def __str__(self):
        return self.answer_text

投票\views.py

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone

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 (not including those set to be
        published in the future).
        """
        return Question.objects.filter(
            pub_date__lte=timezone.now()
        ).order_by('-pub_date')[:5] 

     #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):
    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, 'polls/detail.html', {
            'question': p,
            '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=(p.id,)))

最佳答案

将选择更改为选择。有时它可能会纠正。因为这些数据是从数据库中的表中检索的。

关于python - Django 教程 html css python for 循环不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30439431/

相关文章:

python - django i18n 翻译中的性别问题

python - 如何修剪掉数组元素的\x部分?

jquery - 允许 textarea 不仅可以修改 CSS,还可以修改 JQuery?

python - 如何在python中超时功能,超时不到一秒

html - Flexbox 在垂直堆叠的盒子上保持相同的高度

java - 如何避免在 Jsoup 解析中包围 html head 标签

javascript - #id 以数字结尾的通用 CSS

html - float 子 div 仅填充剩余空间

html - 从按钮元素中删除边框

python - 匹配多个正则表达式组并删除它们