Home > Blockchain >  Way to show latest 4 blog posts on my page
Way to show latest 4 blog posts on my page

Time:01-21

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:

Models.py

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 __str__(self):
        return self.blog_title

Views.py

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})

Template

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

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

CodePudding user response:

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]

CodePudding user response:

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

  • Related