Django-mptt-按类别对帖子进行排序

时间:2018-07-30 04:21:26

标签: python django django-mptt

我是新来的django。我正在尝试在我的网站上创建一个类别系统。我使用了Django-mptt。我想要一个按类别对帖子进行排序的视图。

树:

Category
    -Subcategory
    -Subcategory
Category
    -Subcategory
    -Subcategory

models.py

class Post(models.Model):
    title = models.CharField(max_length=250)
    category = TreeForeignKey('Category', on_delete=models.CASCADE, related_name='post')

class Category(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE)
    slug = models.SlugField()

    class MPTTMeta:
        order_insertion_by = ['name']

    class Meta:
        unique_together = (('parent', 'slug',))
        verbose_name_plural = 'categories'

    def get_absolute_url(self):
        return reverse('list_of_post_by_category', args=[self.slug])

    def __str__(self):
        return self.name

    def get_slug_list(self):
        try:
            ancestors = self.get_ancestors(include_self=True)
        except:
            ancestors = []
        else:
            ancestors = [ i.slug for i in ancestors]
            slugs = []
        for i in range(len(ancestors)):
            slugs.append('/'.join(ancestors[:i+1]))
        return slugs

views.py

def list_of_post_by_category(request, slug):
    categories = Category.objects.all()
    category=get_object_or_404(Category, slug = slug)
    posts = Post.objects.filter(category=category)
    return render(request, "account/list_of_post_by_category.html", {'categories': categories, 'posts': posts, 'category': category})

urls.py

url(r'^category/(?P<slug>[-\w]+)/$', views.list_of_post_by_category, name= 'list_of_post_by_category')

list_of_post_by_category.html

{% for post in posts %}
    <div class="single_post">
        <a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
        <br/>
        <br/>
        <div>
           {{ post.publish }}
           {% for parent in post.category.get_ancestors %}
              {{ parent.name }} / 
           {% endfor %}
           {{ post.category }}
        </div>
    </div>
{% endfor %}

我的问题是该网站没有显示任何帖子。我认为问题出在视图函数中。请帮忙。

0 个答案:

没有答案