Django如果在本文中,请显示本文类别中的所有文章标题

时间:2018-11-26 20:55:19

标签: python django

你好,我需要一点帮助。

我创建django cms。

我无法在帖子页面中过滤类别。

我想,如果我在帖子页面中,我想查看该类别中的其他帖子标题。

让我解释一下; 我有三个职位。帖子标题是这样的;

1-bmw3series

2-bmw5series

3-teslaroadster

“宝马”类别中的第一和第二条帖子

“特斯拉”类别中的第三条帖子

我想在左侧区域显示帖子类别。但我想显示该帖子类别的帖子标题。

例如,如果我在bmw5series页面中,我只希望看到bmw3series和bmw5series帖子标题的左侧类别区域。

当我使用以下代码时

<div class="container">


  <div class="row">
    <div class="col-3">
      <div class="bg-custom-light2 p-0">
        <h2 class="font-weight-bold text-custom-blue-dark h5 border-color p-2">Title</h2>
        <ul class="list-group">

          <li class="list-group-item d-flex justify-content-between align-items-center">
            <div>
              <h6 class="font-weight-bold text-custom-blue-dark">Test title example for
                example test post</h6>
              <p>post date date</p>
            </div>
            <img class="ml-2" src="https://via.placeholder.com/50" alt="">
          </li>
          <li class="list-group-item d-flex justify-content-between align-items-center">
            <div>
              <h6 class="font-weight-bold text-custom-blue-dark">Test title example for
                example test post</h6>
              <p>post date date</p>
            </div>
            <img class="ml-2" src="https://via.placeholder.com/50" alt="">
          </li>
        </ul>
      </div>
    </div>
  </div>
</div>

所有帖子标题都已列出...因此,如果我在bmw5series中发布帖子,我只需要查看bmw类别中的文章即可。...

如何过滤它们?

views.py

 {% for category in category %}
{% for article in category.get_article %}
<li><a title="{{ article.title }}" href="{% url 'article:detail' slug=article.slug %}">{{ article.title }}</a></li>
{% endfor %}
 {% endfor %}

models.py

from django.shortcuts import render,  get_object_or_404
from .models import Article, Category

def index(request):
    articles = Article.objects.all()
    category = Category.objects.all()

    context = {
        "articles": articles,
        "category": category,

         }

    return render(request, 'index.html', context)

def detail(request,slug):
    article = get_object_or_404(Article, slug = slug)
    category = Category.objects.all()

    return render(request, "detail.html", {"article":article, "category":category,})



def category_detail(request,slug):
    template = "category_detail.html"

    category=get_object_or_404(Category,slug=slug)
    article=Article.objects.filter(category=category)

    context = {
        'article' : article,
    }
    return render(request,template,context)

1 个答案:

答案 0 :(得分:2)

尝试重命名

{% for category in category %}
{% for article in category.get_article %}

对此

{% for cat in category %}
{% for article in cat.get_article %}

更新

如果我对您的理解正确,那么无论何时显示文章,都希望显示该文章类别的文章。如果正确,则必须更改

category = Category.objects.all() 

category = Category.objects.filter(article=article)