我通过django的官方文档学习Django但是当我完成第四个教程来制作民意调查应用程序时。我没有得到正确的结果,当我点击民意调查时,它会给我一个错误:
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
我的 urls.py ( C:\ Users \ Krt_zox \ mysite \ polls )
from django.conf.urls import url
from . import views
app_name ='polls'
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'),
]
我的 index.py ( C:\ 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 %}
我的 views.py ( C:\ Users \ Krt_zox \ 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,)))
我是初学者,所以任何帮助都会受到赞赏。