【问题标题】:Filter posts based on category根据类别过滤帖子
【发布时间】: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


    【解决方案1】:

    首先,像这样扩展您的 url 定义:

    path('blog/filter_by_category/<str:category>', filter_by_category, name='filter_by_category'),
    

    现在你在 url 中定义了一个名为 '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 而不是标题。

    【讨论】:

    • 这很棒。我可以修改 以使 URL 中的类别名称为小写字母吗?我的 Urls 像 /posts/Maths/ 等一样构建。我希望类别为小写。
    • @JulianOtto 您的 url 是大写还是小写不是由 url/path 定义定义的,而是由生成您的 url 的任何内容定义的。如果您在上面的模板中“手动”构建 url,您可以使用较低的模板标签使您的文本全部小写:docs.djangoproject.com/en/dev/ref/templates/builtins/#lower 但是,我也可以建议您查看 django SlugField 和/或中的 slugify 方法django.utils.text.
    猜你喜欢
    • 2020-11-14
    • 2015-11-10
    • 2021-11-28
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多