【问题标题】:How do I properly decouple URLConf in Django tutorial 3?如何在 Django 教程 3 中正确解耦 URLConf?
【发布时间】:2012-07-29 17:09:03
【问题描述】:

我正在关注 Django 教程,并已在教程 3 中访问Decoupling the URLConfs。在此步骤之前,一切正常。现在,当我执行删除模板中的硬编码 URL 的最后一步时,会发生变化

<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>

<li><a href="{% url 'polls.views.detail' poll.id %}">{{ poll.question }}</a></li>

我收到此错误:

NoReverseMatch at /polls/

Reverse for ''polls.views.detail'' with arguments '(1,)' and keyword arguments '{}' not found.

Request Method:     GET
Request URL:    http://localhost:8000/polls/
Django Version:     1.4
Exception Type:     NoReverseMatch
Exception Value:    

Reverse for ''polls.views.detail'' with arguments '(1,)' and keyword arguments '{}' not found.

Exception Location:     e:\Django\development\tools\PortablePython\PortablePython2.7.3.1\App\lib\site-packages\django\template\defaulttags.py in render, line 424
Python Executable:  e:\Django\development\tools\PortablePython\PortablePython2.7.3.1\App\python.exe

我的views.py 看起来像这样:

from django.shortcuts import render_to_response, get_object_or_404
from polls.models import Poll

def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})

def detail(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    return render_to_response('polls/detail.html', {'poll': p})

def results(request, poll_id):
    return HttpResponse("You're looking at the results of poll %s." % poll_id)

def vote(request, poll_id):
    return HttpResponse("You're voting on poll %s." % poll_id)

我的项目urls.py 如下所示:

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

polls/urls.py 看起来像这样:

from django.conf.urls import patterns, include, url

urlpatterns = patterns('polls.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'),
)

显然我错过了一些东西,但我已经完成了第 3 部分几次,无法弄清楚我错过了什么。我需要更正什么才能正确解耦这些 URL?

【问题讨论】:

    标签: python django django-views urlconf


    【解决方案1】:

    这是版本问题。当您使用 1.4 版时,您不知何故找到了 Django 开发版本的链接。自发布以来发生的变化之一是模板中的 URL 名称过去不需要引号,但现在它们需要引号。这就是错误消息的 URL 名称包含在两组引号内的原因。

    您应该使用 this version of the tutorial 来匹配您拥有的 Django 版本。 (您可以安装开发版本,但不建议这样做 - 坚持使用该版本。)

    【讨论】:

    • 谢谢。我什至没有注意到 URL 中的dev
    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 2012-08-21
    • 2014-05-20
    • 1970-01-01
    • 2013-06-01
    相关资源
    最近更新 更多