我正在使用django-categories制作自定义类别模型。
我有一个与该类别相关的文章模型,但我如何在文章模型上get_absolute_url
像这样/category-path/article-slug
/category-path/
可以是这样的路径:/top-level-category/sub-level-category/sub-sub-level-category/
这是我的models.py
class Category(CategoryBase):
order = models.IntegerField(default=0)
description = models.TextField(blank=True, null=True)
class MPTTMeta:
order_insertion_by = ('order', 'name')
def get_absolute_url(self):
"""Return a path"""
prefix = reverse('categories_tree_list')
ancestors = list(self.get_ancestors()) + [self, ]
return prefix + '/'.join([force_unicode(i.slug) for i in ancestors]) + '/'
class Article(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255)
category = models.ForeignKey(Category)
我的urls.py
from django.conf.urls import patterns, url
from apps.news.views import CategoryList
urlpatterns = patterns('',
#Startpage for app
url(r'^$', CategoryList.as_view(), name="categories_tree_list")
)
urlpatterns += patterns('apps.news.views',
url(r'^(?P<path>.+)/$', 'category_detail', name='categories_category'),
)
答案 0 :(得分:0)
我不知道Category
是否有slug
属性,如果没有,你可以自己添加。
models.py
class Article(models.Model):
...
category = models.ForeignKey(Category)
def get_absolute_url(self):
arguments = (self.category.slug, self.slug)
return reverse('article-detail',arguments)
views.py
def article_detail(request,category_slug,article_slug):
article = Article.objects.get(category__slug=category_slug,
slug=article_slug)
return render(request, 'article_detail_template.html',
{'article':article})
urls.py
urlpatterns += patterns('',
url(r'^(?P<category_slug>.+)/(?P<article_slug>.+)$',
'app.views.article_detail', name='article-detail'),
)
在模板中使用以下内容链接到特殊文章
<a href="{{ article_obj.get_absolute_url }}">{{ article_obj.title }}</a>