Django 404错误投票:细节不找到了吗?

2024-05-04 20:59:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在通过Django的官方文档学习Django,但当我完成了第4个教程时,我在making polls app中完成了。我没有得到正确的结果,当我点击投票时,它会给我一个错误:

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/polls/(%25%20url%20'polls:detail'%20question.id%20%25)
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/ ^$ [name='index']
^polls/ ^(?P<pk>[0-9]+)$ [name='detail']
^polls/ ^(?P<pk>[0-9]+)/results/$ [name='results']
^polls/ ^(?P<question_id>[0-9]+)/vote/$ [name='vote']
^admin/
The current URL, polls/(% url 'polls:detail' question.id %), didn't match any of these.

我的项目目录是C:\Users\Krt_zox\mysite

我的网址.pyC:\Users\Krt\uox\mysite\polls

^{pr2}$

我的索引.pyC:\Users\Krt_-zox\mysite\polls\templates\polls

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

我的视图.pyC:\Users\Krt\uox\mysite\polls

from django.shortcuts import get_object_or_404,render
from django.http import HttpResponseRedirect
from .models import Question,Choice
from django.urls import reverse
from django.views import generic

# Create your views here.

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):
    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,)))  

我是初学者,所以任何帮助都将不胜感激。在


Tags: djangonamefromimportidusersresultspolls