【问题标题】:Django Polls Tutorial No answer detected in choice.votes pollsDjango 投票教程 在 choice.votes 投票中未检测到答案
【发布时间】:2022-12-17 20:30:43
【问题描述】:

我决定学习 Django,并从我认为最简单的“Django Polls App”开始,我掌握了它的工作原理,但我被卡住了。为了更好地学习,我将原始文档中的变量和名称更改为我自己的。

示例:question_text = q_text,Choice = Choices,choice_text = choice.. 等等。

现在我无法弄清楚我的代码有什么问题,因为我无法进行民意调查。没有错误代码,但它根本不显示票数或显示成功标志。我还关注了 Traversy Media 的 Django 速成课程(民意调查应用程序)。

我的代码:

视图.py

from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.template import loader

from .models import Question, Choices


def index(request):
    latest_ques = Question.objects.order_by('-published')[:5]
    context = {'latest_ques': latest_ques}
    return render(request, 'polls/index.html', context)


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


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.choices_set.get(pk=request.POST['choices'])
    except (KeyError, Choices.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,)))

模型.py

from django.db import models


class Question(models.Model):
    q_text = models.CharField(max_length=200)
    published = models.DateTimeField('date published')

    def __str__(self):
        return self.q_text


class Choices(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice

细节.html

{% extends 'base.html' %}
{% block content %}
<a class="btn btn-secondary btn-sm mb-3" href="{% url 'polls:index' %}">Back To Polls</a>
<h1 class="text-center mb-3">{{ question.q_text }}</h1>

{% if error_message %}
<p class="alert alert-danger">
  <strong>{{ error_message }}</strong>
</p>
{% endif %}

<form action="{% url 'polls:vote' question.id %}" method="post">
  {% csrf_token %}
  {% for choices in question.choices_set.all %}
    <div class="form-check">
      <input type="radio"
             name="choices"
             class="form-check-input"
             id="choices{{ forloop.counter }}"
             value="{{ choices.id }}">
      <label for="choices{{ forloop.counter }}">{{ choices.choice }}</label>
    </div>
  {% endfor %}
  <input type="submit" value="Vote" class="btn btn-success btn-lg btn-block mt-4" />
</form>
{% endblock %}

结果.html

{% extends 'base.html' %}
{% block content %}
<h1 class="mb-5 text-center">{{ question.q_text }}</h1>

<ul class="list-group mb-5">
  {% for choices in question.choices_set.all %}
  <li class="list-group-item">
    {{ choices.choice }} <span class="badge badge-success float-right">{{ choices.votes }} vote{{ choices.votes | pluralize }}</span>
  </li>
  {% endfor %}
</ul>
<a class="btn btn-secondary" href="{% url 'polls:index' %}">Back To Polls</a>
<a class="btn btn-dark" href="{% url 'polls:detail' question.id %}">Vote Again?</a>
{% endblock %}

网址.py

from django.urls import path

from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:question_id>/', views.detail, name='detail'),
    path('<int:question_id>/results/', views.results, name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

我已经上网几个小时了,无法弄清楚。没有得到正确的答案。以为我会在这里碰碰运气。

我试图更改多个变量的名称,整个过程中出现了很多错误,但我无法弄清楚这个错误。该解决方案实际上非常简单,我知道,但不能真正指出它。谢谢。

【问题讨论】:

    标签: python django django-models django-views django-templates


    【解决方案1】:

    没关系,我发现有一些拼写错误的变量。在我逐行查找错误后,它起作用了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-26
      • 2014-09-18
      • 2014-02-01
      • 2012-10-29
      • 1970-01-01
      • 2012-03-15
      • 2012-07-25
      • 1970-01-01
      相关资源
      最近更新 更多