0

我使用 get_absolute_url 方法返回一个 slug 字段,它将在我的 url 中替换。

由于某种原因,返回的值是空白的,

模型.py

class Category(models.Model):
    """ model class containing information about a category in the product catalog """
    name = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50, unique=True,
                            help_text='Unique value for product page URL, created automatically from name.')
    description = models.TextField()
    is_active = models.BooleanField(default=True)
    meta_keywords = models.CharField(max_length=255,
                                     help_text='Comma-delimited set of SEO keywords for keywords meta tag')
    meta_description = models.CharField(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)

    #objects = models.Manager()
    #active = ActiveCategoryManager()

    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_category', (), { 'category_slug': self.slug })

网址.py

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'),  
        (r'^product/(?P<product_slug>[-\w]+)/$',  
            'show_product', { 'template_name':'catalog/product.html'},'catalog_product'), 

) 

目录标签.py

@register.inclusion_tag("tags/category_list.html") 
def category_list(request_path): 
    print 'catalog_tags-request_path', request_path
    #active_categories = Category.objects.filter(is_active=True) 
    active_categories = Category.objects.all() 
    return { 
          'active_categories': active_categories, 
          'request_path': request_path 
     } 

目录列表.html

<h3>Categories</h3> 
<ul id="categories">
{% with active_categories as cats %} 
    {% for c in cats %} 

    <li>
     {% ifequal c.get_absolute_url request_path %} 
          {{ c}}<br /> 
     {% else %} 
          <a href="{{ c.get_absolute_url }}" class="category">{{ c.name }}</a><br /> 
     {% endifequal %} 
     </li>
    {% endfor %} 
{% endwith %} 
</ul>       

上述 html 中的 c.get_absolute_url 返回空白。

4

2 回答 2

1

用这个:

from django.core.urlresolvers import reverse

def get_absolute_url(self):
    return reverse('catalog_category', kwargs={'category_slug': self.slug})
于 2012-12-31T18:17:39.050 回答
0

您是在进行数据输入时要求用户设置 slug 还是从名称字段以编程方式创建 slug?

帮助文本建议后者,但我没有看到代码?您需要覆盖保存方法:

如何在 Django 中创建一个独特的 slug

于 2013-07-10T02:09:38.883 回答