Home > Back-end >  How can I show last 4 posts in django?
How can I show last 4 posts in django?

Time:09-23

I try to show last 4 posts with Django by using Class-Based Views, but No data (post) shows on page. that's code: views.py :

class PostList(ListView):
    model=Post
    paginate_by=10
    context_object_name='all_posts'
    ordering=['-created_at']
    latest=model.objects.order_by('-created_at')[:4]

templates/post_list.html :

{% for post in latest  %}
                <div class="col-sm-12 col-md-6 col-lg-3" >
                    <!-- cards-->
                    <div class="card ">
                        
                        <img src="{{post.image.url}}" class="card-img-top" alt="...">
                        <div class="card-body">
                        <h5 class="card-title">{{post.title}}</h5>
                        <p class="card-text">{{post.content}}</p>
                        <a href="#" class="btn btn-primary">Go somewhere</a>
                        </div>
                    </div>

                    <!-- ends cards-->
                </div>
                {% endfor %} 

my thanks

CodePudding user response:

Use get_aueryset() to do that!

Here is the Django documentations

class PostList(ListView):
    template_name = "templates/post_list.html"
    model = Post
    ordering = ["-created_at"]
    context_object_name = "all_posts"

    def get_queryset(self):
        queryset = super().get_queryset()
        data = queryset[:4]
        return data
  • Related