Views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from . models import Question
from django.template import loader, RequestContext
# Create your views here.
def index(request):
latest_questions = Question.objects.all()[:5]
context = {'latest_questions': latest_questions}
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': question})
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():
return render(request, 'polls/detail.html', {'question': question, 'error_message' : "Please select a choice"})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
由于它不是有效的视图函数,因此我得到的结果没有反向匹配。我是django的新手。我该如何解决?这是否意味着我的view.py代码存在问题,或者在我学习本教程时可能是问题所在。
polls/urls.py
from django.conf.urls import url
from . import views
urlpatterns=[
url(r'^$', views.index,name='index'),
url(r'^(?P<question_id>[0-2]+)/$', views.detail, name='detail'),
url(r'^(?P<question_id>[0-2]+)/results', views.results, name='result'),
url(r'^(?P<question_id>[0-2]+)/votes', views.vote, name='vote'),
]
这是polls / templates / polls / results.html文件
Results.html
{% extends 'polls/base.html' %}
{% block main_content %}
<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:detail' question.id %}">Vote Again?</a>
{% endblock %}
我在其中使用命名空间的mysite / urls.py。可能是什么问题。
Mysite/urls.py
from django.contrib import admin
from django.conf.urls import url, include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^polls/', include(('polls.urls', 'polls'), namespace='polls')),
]
答案 0 :(得分:1)
您已在视图reverse
中使用vote
。将第一个参数从“ polls:results ”更改为“ polls:result ”或“ result ”。
Reverse
用于指向urls.py
中定义的URL模式。查看urlpatterns中的第三个条目,为它提供了名称“ result ”。
那应该可以解决您的问题。