Реверс для 'результатов' с аргументами '(' ',)' не найден. 1 шаблон (ы) пробовали: ['опросы / (? P [0-9] +) / Результаты / $ '] - PullRequest
0 голосов
/ 07 января 2020

Я только что попал в общий c раздел просмотра Django учебника на их веб-сайте, но я застрял в этой части и продолжаю получать эту ошибку. Этот вопрос уже отвечался ранее, но для более старой версии учебника и Django. Я надеялся, что кто-то здесь сможет мне помочь. Вот код:

urls.py

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

views.py

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

def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    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_id' : question_id})

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.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,)))

деталь. 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>

результаты . html

<h1>{{ question.question_text }}</h1>

<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'polls:results' question.id %}">Vote again?</a>

есть указанное сообщение c, указывающее на последнюю строку результатов. Hmtl

In template C:\Users\Erenildo\Desktop 2\Python\Django\DjangoTut\Djanguiho\mysite\polls\templates\polls\results.html, error at line 9

edit1: models.py

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

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


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

    def __str__(self):
        return self.choice_text

Ответы [ 2 ]

1 голос
/ 07 января 2020

Проблема в вашем results виде. Вы должны включить question в контекст шаблона, а не question_id.

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})
0 голосов
/ 07 января 2020

Попробуйте просто сделать это для results.py

<h1>{{ question.question_text }}</h1>

<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'results' question_id=question.id %}">Vote again?</a>

Пока у вас есть только один шаблон URL с пространством имен results, с вами все будет в порядке.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...