我是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。 片刻之后,我已经接近那个决定,但是搞砸了。谢谢!
答案 0 :(得分:2)
首先,像这样扩展您的网址定义:
path('blog/filter_by_category/<str:category>', filter_by_category, name='filter_by_category'),
现在,您要在网址中定义一个名为“ category”的变量(该字符串为字符串,因此为str),该变量可以传递给视图:
def filter_by_category(request, category):
post_list = Post.objects.filter(categories__title=category)
context = {
'post_list': post_list
}
return render(request, 'post_by_category.html', context)
并更改模板,以便将参数添加到url:
<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' category=cat.categories__title %}">{{ cat.categories__title }}</a><span>{{ cat.categories__title__count }}</span></div>
{% endfor %}
</div>
如果您更喜欢或更适合自己(例如,如果类别标题可以包含重复项),还可以将url更改为int,并更改模板以使用类别ID代替标题。