如何在我的视图函数中创建面包屑?

时间:2012-10-14 06:44:34

标签: django

(偶然的,我删除了我的上一个问题)

如何在我的视图功能中创建面包屑?

class Category(MPTTModel):
    name = models.CharField(max_length=50, verbose_name=u'Name')
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
    slug = models.SlugField()

class Product(models.Model):
    name = models.CharField(max_length=50, verbose_name=u'Name')
    slug = models.SlugField()
    #category = models.ManyToManyField(Category, verbose_name=u'Category')
    category = models.ForeignKey(Category)

#views
def post_content(request, product_id):
    product = get_object_or_404(Product, id = product_id)
    return render_to_response('product_info.html', {'product':product},context_instance=RequestContext(request))

product_info.html

{{ product.name }}

我希望在我的单个帖子信息(post_content)包含类别的面包屑中。 像这样:类别>子类别>子子类别。,,,

有人告诉我使用get_ancestors:

示例:

{% for parent in category.get_ancestors %}
  <a href="{{ parent }}">{{ parent.name }}</a> &gt;
{% endfor %}
{{ category.name }}

如何用我的模型实现这个?

谢谢。我将不胜感激。

1 个答案:

答案 0 :(得分:2)

如果category = models.ForeignKey(Category),请执行:

{% for parent in product.category.get_ancestors %}
  <a href="{{ define_url_to_parent }}">{{ parent.name }}</a>
{% endfor %}