使用@permalink和get_absolute_url()时的NoReverseMatch

时间:2013-03-31 17:09:09

标签: python django

我知道这似乎是许多解决方案的常见问题,但即使在尝试了我遇到的每个解决方案后,我仍然遇到此问题。

型号:

class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True,
                        help_text='Unique value for product page URL, created form name.')
description = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords",max_length=255, 
                                 help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField("Meta Description", max_length=255,
                                    help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

class Meta:
    db_table = 'categories'
    ordering = ['name']
    verbose_name_plural = 'Categories'

def __unicode__(self):
    return self.name

@models.permalink
def get_absolute_url(self):
    #return ('catalog.views.show_category',(),{'category_slug' : str(self.slug)})
    return ('catalog_category', (), { 'category_slug' : str(self.slug) })

查看:

def index(request, template_name="catalog/index.html"):
    page_title = 'Anime and Manga'
    return render_to_response(template_name, locals(), context_instance=RequestContext(request))

def show_category(request, category_slug, template_name="catalog/category.html"):
    c = get_object_or_404(Category, slug=category_slug)
    products = c.product_set.all()
    page_title = c.name
    meta_keywords = c.meta_keywords
    meta_description = c.meta_description
    return render_to_response(template_name, locals(), context_instance=RequestContext(request))

的url:

urlpatterns = patterns('catalog.views', 
                   (r'^$', 'index', { 'template_name':'catalog/index.html' },  'catalog_home'),
                   (r'^category/(?P<category_slug>[-\W]+)/$', 'show_category', 
                    {'template_name':'catalog/category.html'}, 'catalog_category'),

当我进入shell并尝试:

  

反向('catalog_home')

...它返回:

  

'/'

......这是正确的。但是,当我尝试:

  

reverse('catalog_category',kwargs = {'category_slug':'action'}

...它返回:

  

NoReverseMatch:反向'catalog_category',参数'()'和关键字参数'{'category_slug':'action'}'找不到。

尽管我输入了代码示例,但我的实际代码中的缩进是正确的,因此永久链接位于Category Class下。

1 个答案:

答案 0 :(得分:4)

您在正则表达式中使用了\W,这意味着“任何字符除了字母数字”。我希望你的意思是\w