I would like to show the latest 3 posts in the Latest Posts section of my page. How can I do it without using for loop or is that the only way?
I was successful to get the result in the shell console, however, I am not able to show it in the HTML template. Please help
models.py
from typing import Any
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from ckeditor.fields import RichTextField
class BlogPost(models.Model):
blogpic = models.CharField(max_length=1000)
title = models.CharField(max_length=255)
description = models.CharField(max_length=100, default='Enter a short desctiption', editable=True)
body = RichTextField(blank=True, null=True)
category = models.CharField(max_length=50, default='banking', editable=True)
tag = models.CharField(max_length=50, default='consulting', editable=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
blog_date = models.DateField(default=timezone.now, editable=True,)
def __str__(self):
return self.title ' | ' str(self.author)
views.py
from django.views.generic import ListView, DetailView
from . models import BlogPost
class BlogView(ListView):
model = BlogPost
template_name = 'blog.html'
ordering = ['-blog_date']
class BlogDetailsView(DetailView):
model = BlogPost
template_name = 'blog_details.html'
urls.py
from django.urls import path
from AssayBlog.models import BlogPost
from . views import BlogView, BlogDetailsView
urlpatterns = [
path('', BlogView.as_view(), name="blog"),
path('_detail/<int:pk>', BlogDetailsView.as_view(), name="blog_details"),
blog_details.html
<h3 >Latest Posts</h3>
<ul >
<li>
<div >
<img src="{% static 'assets/images/blog/lp-1-1.jpg' %}" alt="">
</div>
<div >
<h3>
<a href="#" ><i ></i>2 Comments</a>
<a href="news-details.html">going global with transformation</a>
</h3>
</div>
</li>
</ul>
CodePudding user response:
You can use get_context_data funtion in any views.py.
class BlogDetailsView(DetailView):
model = BlogPost
template_name = 'blog_details.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['latests_posts'] = BlogPost.objects.all()[-3:] # or [:3] depending on model ordering
return context
In template use:
{% for post in latest_posts %}
{{ post.title }}
# rest of single post section
{% endfor %}
