Django模板。获取类别标题

时间:2018-12-28 12:28:58

标签: python html django filter view

我目前正在尝试弄清楚如何显示类别标题 在我的模板中。我正在尝试实现过滤器视图,这是最后一步。目前我得到以下输出

Latest Post's in <QuerySet [<Category: testcategory>]>

template.html

<h1 class="center">Latest Post's in {{ categories }}</h1> < right here!!!
{% for post in posts %}
    <div class="post">
        <h3><u><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></u></h3>
        <p>{{ post.content|safe|slice:":1000"|linebreaksbr}}
            {% if post.content|length > 500 %}
                <a href="{% url 'post_detail' pk=post.pk %}">... more</a>
            {% endif %}</p>
        <div class="date">
            <a>Published by: <a href="{% url 'profile' pk=post.author.pk %}">{{ post.author }}</a></a><br>
            <a>Published at: {{ post.published_date }}</a><br>
            <a>Category: <a href="{% url 'category_by' pk=post.category.pk %}">{{ post.category }}</a></a><br>
            <a>Tag(s): {{ post.tag }}</a><br>
            <a>Comment(s): {{ post.comment_set.count }}</a>
        </div>
    </div>
{% endfor %}

views.py

def category_show(request, pk):
    list_posts = Post.objects.get_queryset().filter(category_id=pk).order_by('-pk')
    paginator = Paginator(list_posts, 10)  # Show 10 Posts per page
    page = request.GET.get('page')
    posts = paginator.get_page(page)
    categories = Category.objects.all()
    return render(request, 'myproject/post_list_by_category.html', {'posts': posts, 'categories': categories})

2 个答案:

答案 0 :(得分:0)

在您的代码中,categories是一个查询集(类别的集合),而不是单个类别。您只需要选择与pk相匹配的类别:

def category_show(request, pk):
    category = Category.objects.get(pk=pk)
    list_posts = Post.objects.filter(category_id=pk).order_by('-pk')
    paginator = Paginator(list_posts, 10)  # Show 10 Posts per page
    page = request.GET.get('page')
    posts = paginator.get_page(page)
    return render(request, 'myproject/post_list_by_category.html', {'posts': posts, 'category': category})

<h1 class="center">Latest Post's in {{ category.title }}</h1>

答案 1 :(得分:0)

Category.objects.all()返回查询集。如果要使用{{Categories.title}},则应使用.get()方法

def category_show(request, pk):
    list_posts = Post.objects.get_queryset().filter(category_id=pk).order_by('-pk')
    paginator = Paginator(list_posts, 10)  # Show 10 Posts per page
    page = request.GET.get('page')
    posts = paginator.get_page(page)
    cat = Category.objects.get(id=pk)
    return render(request, 'myproject/post_list_by_category.html', {'posts': posts, 'cat': cat})

<h1 class="center">Latest Post's in {{ cat.title }}</h1> < right here!!!