如何解决Django错误“页面未找到(404)”
我正在按照教程创建一个django应用,现在已经到了第四部分,具体内容可以在这个链接找到:https://docs.djangoproject.com/en/dev/intro/tutorial04/
这个应用展示了一个简单的投票,点击后会显示一些选项和一个投票按钮。
问题是,当我点击投票时,页面显示“未找到”。我觉得问题可能出在重定向上,但我不知道具体在哪里出错。首页是index.html,显示问题,然后是detail.html,显示选项和问题。我知道当我点击投票时,它会返回到应用的URL配置,然后这个配置会执行视图函数,最后视图函数会执行结果。
我的detail.html内容是:
<h1>{{ poll.question }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="/myapp/{{ poll.id }}/vote/" method="post">
{% csrf_token %}
{% for choice in poll.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>
我在myapp里的urls.py是:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls import patterns, include, url
urlpatterns = patterns('myapp.views',
url(r'^$', 'index'),
url(r'^(?P<poll_id>\d+)/$', 'detail'),
url(r'^(?P<poll_id>\d+)/results/$', 'results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
)
我的views.py是:
from django.http import HttpResponse
from myapp.models import Poll ,choice
from django.template import Context, loader
from django.http import Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
return render_to_response('myapp/index.html', {'latest_poll_list': latest_poll_list})
def results(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('myapp/results.html', {'poll': p})
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render_to_response('myapp/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
}, context_instance=RequestContext(request))
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('myapp.views.results', args=(p.id,)))
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('myapp/detail.html', {'poll': p},
context_instance=RequestContext(request))
我的results.html是:
<h1>{{ poll.question }}</h1>
<ul>
{% for choice in poll.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
<a href="/myapp/{{ poll.id }}/">Vote again?</a>
谢谢你的帮助。如果我能让这个应用正常工作,这将是我第一次成功的应用。
我的主URL配置是:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^polls/', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls)),
)
2 个回答
不要写死网址
你不应该在任何地方写死网址,就像处理文件路径一样。这样做不仅会让你的代码变得脆弱,还会造成其他问题!
使用反向网址!
首先了解一下反向网址,然后再学习命名网址,最后再看看{% url %} 模板标签,这就像是甜点。
等你消化完这些知识,你就会成为Django网址系统的高手了B)
阅读教程
在你链接的教程中,他们没有写死网址:
{% url 'polls:vote' poll.id %}
这才是正确的做法!!
确保你的模板中没有任何写死的网址,这样你的问题就能解决了。
把表单的 action 部分中的 "myapp" 去掉。
应该是这样的:
<form action="polls/{{poll.id}}/vote" method="post">
这样就能和你在 urls.py 文件里的正则表达式匹配上了:
url(r'^polls/', include('myapp.urls')),
然后在 myapp.urls 里:
url(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
include
这个函数的意思是,django 正在尝试匹配 ^polls/(?P<poll_id>\d+)/vote/$
。
如果你查看你遇到的错误页面,就能看到 django 正在尝试匹配的 URL(这些 URL 都不包含 'myapp',应该是 polls)。
重要提示
当你在教程中深入学习时,你会发现不应该在模板中硬编码 URL(正如 jpic 正确指出的那样)。在这个阶段,你需要把表单的 action 替换成 {% url 'polls:vote' poll.id %}
。