Way to show latest 4 blog posts on my page

I want to be able to show the latest 4 blog posts only. I can't seem to get them to show. Any help would be greatly appreciated.

Here is my code:


class BlogPost(models.Model):
    blog_title = models.CharField(max_length=48)
    blog_article = RichTextUploadingField(null=True, blank=True, default="ici")
    blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png")
    blog_date = models.DateField(auto_now_add=True)
    blog_published = models.BooleanField(default=False)
    blog_featured = models.BooleanField(default=False)

    def publish(self):
        self.blog_date = timezone.now()

    def __str__(self):
        return self.blog_title


def blogTest(request):
    posts = BlogPost.objects.filter(blog_date__lte=timezone.now()).order_by('blog_date')
    context_blog = {'posts': posts}

    return render(request, 'blogtest.html', context_blog)

def latestPosts(request):
    latest = BlogPost.objects.filter(blog_date__lte=timezone.now()).reverse()[:3]
    return render(request, 'blogtest.html', {'latest': latest})


 <div class="blog-post-container">
      <div class="row">
        <h1 id="lastest-blogs-title" style="text-align: center;">Latest Blogs</h1>
        {% for latestpost in latest %} {% if latestpost.blog_published is True %}
          <div class="col-md-4" id="bloggrid1">
              <div class="blog-post">
                <div class="blog-content">
                      <img class="blog-img"src="{{latestpost.blog_image.url}}"alt="My image"/>
                      <h2 class="blog-title">{{latestpost.blog_title}}</h2>
                      <hr id="blog-hr" style="width: 90%" />
                      <article class="blog-article">
                      <a href="{% url 'viewblog' post.id %}"class="btn btn-secondary"type="button"class="blog-button">Read More...</a>
                      <p class="blog-date">Posted on: {{latestpost.blog_date}}</p>
              {% endif %} {% empty %}
              <h3>No Blog Uploads</h3>
              {% endfor %}

I have followed many other tutorials but I can't seem to see what I'm doing wrong here.

You need to sort queryset but not filter the queryset with blog_date

qs = BlogPost.objects.filter(blog_date__lte=timezone.now()).order_by('-blog_date')[:3]

Try this if you want to get last 4 added entries based on primary key...

latest = BlogPost.objects.order_by('-pk')[:4]

Try this if you want to get last 4 added entries based on your date field

latest = BlogPost.objects.order_by('-blog_date')[:4]

Your template code is good to load entries passed through context

Back to Top