1

Возник вопрос по туториалу из документации по джанго.

Мой счетчик выбора не реагирует на результаты голосования,

Начальный список вариантов: введите сюда описание изображения

После выбора одного и при нажатии на кнопку голосования выводится сообщение "You didn't select a choice."

введите сюда описание изображения

и голос не учитывается. Не могу понять, в каком куске кода ошибка.

Как понимаю, везде обрабатывается исключение

файл views.py:

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse

from django.views import generic

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."""
        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)
    print(request.POST)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist) as e:
        print(e)
    # 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()
        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

файл polls/urls.py:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
    url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

file 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 %}
    <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>

file 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 %}
    <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>

UPD:

Terminal output:

[06/Sep/2015 18:45:05] "GET /polls/3/vote/ HTTP/1.1" 200 255
[06/Sep/2015 18:45:09] "GET /polls/ HTTP/1.1" 200 130
[06/Sep/2015 18:48:25] "GET /polls/3/ HTTP/1.1" 200 200
<QueryDict: {'csrfmiddlewaretoken': ['8L4m4ziCq9k9jRQzFeoCtJ8NLjq1qn8j']}>
"'choice'"
[06/Sep/2015 18:48:26] "POST /polls/3/vote/ HTTP/1.1" 200 255
<QueryDict: {'csrfmiddlewaretoken': ['8L4m4ziCq9k9jRQzFeoCtJ8NLjq1qn8j']}>
"'choice'"
[06/Sep/2015 18:48:53] "POST /polls/3/vote/ HTTP/1.1" 200 255

UPD2:

view-source:http://127.0.0.1:8000/polls/3/vote/

<h1>Test1</h1>

<p><strong>You didn&#39;t select a choice.</strong></p>

<form action="/polls/3/vote/" method="post">
<input type='hidden' name='csrfmiddlewaretoken' value='8L4m4ziCq9k9jRQzFeoCtJ8NLjq1qn8j' />

<input type="submit" value="Vote" />
</form>

1 ответ 1

2

По моему вы не правильно все поняли:

  1. На странице /polls вы выбираете не вариант ответа, а сам вопрос.
  2. На странице /polls/1 должен отображаться вопрос и варианты ответа (которые вы должны были создать через админку)
  3. И тогда вы бы могли выбрать вариант ответа и нажать Vote.
1
  • Спасибо! Понял структуру
    – while1pass
    8 сен 2015 в 15:05

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.