Django Polls Tutorial Не обнаружен ответ в опросах choice.votes

Я решил изучать Django и начал с "Django Polls App", который, как я полагал, будет самым простым, я понял, как он работает, но я застрял. Чтобы немного лучше научиться, я изменил переменные и имена из оригинальной документации на свои собственные.

Пример : question_text = q_text, Choice = Choices, choice_text = choice... и т.д.

Теперь я не могу понять, что не так с моим кодом, поскольку я не могу заставить опросы работать. Нет никакого кода ошибки, но он просто не отображает количество голосов и не показывает знак успеха. Я также следовал Django Crash Course (Polls App) от Traversy Media.

Мой код :

views.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,)))

models.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

details.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 %}

results.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 %}

urls.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'),
]

Я уже несколько часов сижу в интернете и не могу разобраться. Не получаю нормального ответа. Решил попытать счастья здесь.

Я пытался изменить имена нескольких переменных, у меня было много ошибок, но эту я не могу понять. Решение на самом деле было бы довольно простым, я знаю его, но не могу его найти. Спасибо.

Неважно, я обнаружил, что были неправильно указаны переменные. Все заработало после того, как я прошел строку за строкой, чтобы найти ошибку.

Вернуться на верх