[Django]-How can get Post data form Category in Django?

3👍

In your detail view, you pass a single Category object with the name category, not categories. You can iterate over the posts with {% for post in category.post_set.all %}:

<h1> {{ category.title }} </h1>
<div class="container">
    <div class="row">
        {% for post in category.post_set.all %}
        <div class="column">
            <div class="card" style="width: 20rem;">
                <img class="card-img-top" src="{{ post.content_images.url }}" alt="{{ post.title }}">
                <div class="card-body">
                    <b><p class="card-text"> <a href="{% url 'post_detail' post.slug %}"> {{ post.categories.title }} </a></p></b>
                    <p>{{ post.author }}</p>
                    <p class="card-text"> {{ post.content|safe|slice:":200" }}</p>
                    <div align="center"><button type="button" class="btn btn-outline-secondary"> <a href="{% url 'post_detail' post.slug %}"></a></button> </div>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
</div>

A ForeignKey [Django-doc], django makes a manager in the “target model” to query in the opposite direction. If you do not specify the related_name=… parameter [Django-doc], the related name is the name of the “target model” in lowercase, and a _set suffix (here post_set), so that is the way how you can query the related Posts for a given Category.

Leave a comment