Alex Kondrashov
Alex Kondrashov

Reputation: 61

How to display the second last object from DB in Django?

I have a model for news. It looks like:

class Post (models.Model):
    title = models.CharField(max_length=50)
    body = models.TextField()
    image = models.ImageField(upload_to='news_image', blank=True)

    def __str__(self):
        return self.title

views.py looks like:

class PostListView(ListView):
    model = Post
    template_name = 'html/main.html'


class PostDetailView(DetailView):
    model = Post
    template_name = 'html/post_detail.html'

Each news has it's own url:

urlpatterns = [
    path('', views.PostListView.as_view(), name='main'),
    path('news/<int:pk>/', views.PostDetailView.as_view(), name='news_page')]

I use django admin to add posts.
On main.html I want to display title and image of the second last post from database. I also need a link to that post.

<img src="?????" href="????">
<p>{{ ??? }}</p> 

How can I do it?

Upvotes: 0

Views: 297

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599530

That is not something you do in the template. Instead, add it to the context in your view by defining get_context_data.

class PostListView(ListView):
    model = Post
    template_name = 'html/main.html'

    def get_context_data(self, **kwargs):
        kwargs['second_last_post'] = Post.objects.all().reverse()[1]
        return super().get_context_data(**kwargs)

(Note, since you don't define any ordering, what consists of the "second last post" is fairly arbitrary.)

Upvotes: 2

Related Questions