【问题标题】:NoReverseMatch for get_absolute_url() newbie questionget_absolute_url() 新手问题的 NoReverseMatch
【发布时间】:2011-04-27 18:35:29
【问题描述】:

刚开始玩 django,对 get_absolute_url 功能感到困惑。

当我尝试访问一个对象的 url 时,我得到一个 NoReverseMatch 错误。这是堆栈跟踪

$ python manage.py shell
Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from food.models import *
>>> r = Restaurant.objects.get(pk=1)
>>> r
<Restaurant: East Side Marios>
>>> r.get_absolute_url()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 55, in _curried
    return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py", line 887, in get_absolute_url
    return settings.ABSOLUTE_URL_OVERRIDES.get('%s.%s' % (opts.app_label, opts.module_name), func)(self, *args, **kwargs)
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/__init__.py", line 35, in inner
    return reverse(bits[0], None, *bits[1:3])
  File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py", line 391, in reverse
    *args, **kwargs)))
  File "/usr/local/lib/python2.6/dist-packages/django/core/urlresolvers.py", line 337, in reverse
    "arguments '%s' not found." % (lookup_view_s, args, kwargs))
NoReverseMatch: Reverse for 'food.views.restaurant_details' with arguments '()' and keyword arguments '{'restaurant_id': ['1']}' not found.

这是我目前所拥有的

server/urls.py

from django.conf.urls.defaults import *

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',

  # ADMIN
  (r'^admin/doc/', include('django.contrib.admindocs.urls')),
  (r'^admin/', include(admin.site.urls)),

  # Restaurants
  (r'^restaurants/$', 'food.views.restaurant_index'),
  (r'^restaurants/(\d+)/$', 'food.views.restaurant_details'),
)

server/food/models.py

class Restaurant(models.Model):
  name        = models.CharField(max_length=50, unique=True)
  description = models.TextField()
  website     = models.URLField(verify_exists=True)
  def __unicode__(self):
    return self.name
  @models.permalink
  def get_absolute_url(self):
    return ('food.views.restaurant_details', (), {'restaurant_id': [str(self.id)]})

server/food/views.py

from food.models import *
from django.shortcuts import render_to_response, get_object_or_404

# Restaurant

def restaurant_index(request):
    restaurant_list = Restaurant.objects.all()
    return render_to_response('food/restaurant/index.html', {'restaurant_list': restaurant_list})

def restaurant_details(request, restaurant_id):
    restaurant = get_object_or_404(Restaurant, pk=restaurant_id)
    menu_list  = Menu.objects.filter(restaurant=restaurant_id)
    return render_to_response('food/restaurant/detail.html', {'restaurant': restaurant, 'menu_list': menu_list})

restaurant_index 的网站渲染得很好,当然,任何餐馆的 url 都是空字符串

模板

{% if restaurant_list %}
  <ul>
    {% for restaurant in restaurant_list %}
      <li><a href="{{ restaurant.get_absolute_url }}">{{ restaurant }}</a></li>
    {% endfor %}
  </ul>
{% else %}
  <p>No restaurants are currently listed.</p>
{% endif %}

html

<ul>
  <li><a href="">East Side Marios</a></li>
</ul>

【问题讨论】:

    标签: python django url


    【解决方案1】:
    (r'^restaurants/(\d+)/$', 'food.views.restaurant_details'),
    

    您的 URL 模式将 restaurant_id 捕获为非命名组,因此您需要提供 restaurant_id 作为位置参数,或更改 url 模式以将 restaurant_id 捕获为命名组

    将 URL 模式更改为此

    (r'^restaurants/(?P<restaurant_id>\d+)/$', 'food.views.restaurant_details'),
    

    或者从get_absolute_url返回这个

    return ('food.views.restaurant_details', (str(self.id),), {})
    

    【讨论】:

      【解决方案2】:

      除了 Imran 提供的解决方案,您可能还想研究命名 URL 模式:

      urls.py

      urlpatterns = patterns('',
        url(r'^restaurants/(\d+)/$', 'food.views.restaurant_details', name='restaurant_detail'),
      )
      

      restaurant_index.html

      <a href="{% url restaurant_detail restaurant.id%}">{{ restaurant }}</a>
      

      这样,您就不必绑定到视图的函数名称,并且可以更轻松地切换到通用视图。

      【讨论】:

        猜你喜欢
        • 2014-07-07
        • 1970-01-01
        • 2012-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多