我使用get_absolute_url方法返回一个将在我的网址中替换的slug字段。
由于某种原因,返回的值为空,
models.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 })
urls.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'),
)
catalog_tags.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
}
catalog_list.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返回空白。
答案 0 :(得分:1)
使用此:
from django.core.urlresolvers import reverse
def get_absolute_url(self):
return reverse('catalog_category', kwargs={'category_slug': self.slug})
答案 1 :(得分:0)
您是否要求用户在进行数据输入时设置slug或者是否是从名称字段以编程方式创建的slug?
帮助文本建议后者,但我看不到代码?您需要覆盖保存方法: