NoReverseMatch:使用参数'()'和未找到的关键字参数反转'对象详细信息'

时间:2013-02-21 13:03:02

标签: django django-models django-views

我正在尝试获取绝对网址...并且出错。

这是我的models.py

class News(models.Model):
    date = models.DateField(auto_now=True)
    title = models.CharField(max_length=100)
    slug = models.CharField(max_length=100)
    text = models.TextField()

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return ('object detail', {}, {
            'slug': self.slug,
            'year': self.date.strftime('%Y'),
            'month': self.date.strftime('%b'),
            'day': self.date.strftime('%d')
        })

    class Meta:
        verbose_name_plural = "News"
        ordering = ('-date',)

这是我的urls.py

dictionary = {
    'queryset': News.objects.all(),
    'date_field': 'date',
}

urlpatterns= patterns(
    'django.views.generic.date_based',
    url(
        r'(?P<year>d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/(?P<slug>[-w]+)/$',
        'object_detail',
        dict(dictionary, slug_field = 'slug', template_name = 'cms/news/object.html'),
        name='object detail'
    ),
)

当我这样做是django shell

>> from cms.models import News
>> all = News.objects.all()
>> for single in all:
>>     single.get_absolute_url()

我在控制台中收到以下错误。

Traceback (most recent call last):
  File "<console>", line 2, in <module>
  File "/Users/mouse/.virtualenvs/proj/lib/python2.7/site-packages/django/utils/functional.py", line 11, in _curried
    return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))
  File "/Users/mouse/.virtualenvs/proj/lib/python2.7/site-packages/django/db/models/base.py", line 883, in get_absolute_url
    return settings.ABSOLUTE_URL_OVERRIDES.get('%s.%s' % (opts.app_label, opts.module_name), func)(self, *args, **kwargs)
  File "/Users/mouse/.virtualenvs/proj/lib/python2.7/site-packages/django/db/models/__init__.py", line 35, in inner
    return reverse(bits[0], None, *bits[1:3])
  File "/Users/mouse/.virtualenvs/proj/lib/python2.7/site-packages/django/core/urlresolvers.py", line 476, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "/Users/mouse/.virtualenvs/proj/lib/python2.7/site-packages/django/core/urlresolvers.py", line 396, in _reverse_with_prefix
    "arguments '%s' not found." % (lookup_view_s, args, kwargs))
NoReverseMatch: Reverse for 'object detail' with arguments '()' and keyword arguments '{'year': '2013', 'slug': u'2013-season-details', 'day': '19', 'month': 'Feb'}' not found.

在哪里和我可能做错了什么?

1 个答案:

答案 0 :(得分:2)

除了year之外,您还需要在get_absolute_url方法中满足monthdayslug关键字参数。对于位置参数,我也会传入一个空元组而不是None