【发布时间】:2019-10-28 21:25:43
【问题描述】:
我是 django 新手,通常是编程新手。现在我写了我的第一个项目——这将是我的个人博客,它几乎完成了,除了一个功能: 我在右侧面板的页面上显示了类别列表。
1) 问题是如何按这些类别对我的帖子进行排序/过滤?我的意思是我想点击右侧面板中的其中一个类别,然后查看提到该类别的帖子(帖子可能有多个类别)。
我尝试了很多组合,在 stackoverflow 上找到了,但我之前没有这样做,所以无法理解如何在我的项目中实现该功能。
models.py
class Category(models.Model):
title = models.CharField(max_length=20)
def __str__(self):
return self.title
class Post(models.Model):
title = models.CharField(max_length=100)
overview = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
content = HTMLField('Content')
author = models.ForeignKey(Author, on_delete=models.CASCADE)
thumbnail = models.ImageField()
categories = models.ManyToManyField(Category)
featured = models.BooleanField()
previous_post = models.ForeignKey('self', related_name='previous', on_delete=models.SET_NULL, blank=True, null=True)
next_post = models.ForeignKey('self', related_name='next', on_delete=models.SET_NULL, blank=True, null=True)
def __str__(self):
return self.title
views.py
def filter_by_category(request):
post_list = Post.objects.filter(categories=)
context = {
'post_list': post_list
}
return render(request, 'post_by_category.html', context)
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', index),
path('blog/', blog, name='post-list'),
path('search/', search, name='search'),
path('blog/filter_by_category/', filter_by_category, name='filter_by_category'),
path('subscribe/', email_list_signup, name='subscribe'),
path('create/', post_create, name='post-create'),
path('post/<id>/', post, name='post-detail'),
path('post/<id>/update/', post_update, name='post-update'),
path('post/<id>/delete/', post_delete, name='post-delete'),
path('tinymce/', include('tinymce.urls')),
path('accounts/', include('allauth.urls')),
sidebar.html
<div class="widget categories">
<header>
<h3 class="h6">Categories</h3>
</header>
{% for cat in category_count %}
<div class="item d-flex justify-content-between">
<a href="{% url 'filter_by_category' %}">{{ cat.categories__title }}</a><span>{{ cat.categories__title__count }}</span></div>
{% endfor %}
</div>
鉴于代码不起作用,我知道views.py 中的问题。我完全搞砸了如何正确编写它。 请帮我解决这个问题。
更新: 已经解决了,非常感谢 Landcross。 在某些时候,我很接近那个决定,但搞砸了。谢谢!
【问题讨论】:
标签: python django python-3.x filter