0
votes

I'm using a class based view DetailView to handle the layout of a blog post.

In the template, I need to implement a button to show previous/next posts ordered by timestamp. For this reason, I need to override the context by customising the get_context_data(self) method. In the context I thus need to add the instances of prev/next entries by insertion_date relative to current post.

views.py

class EntryDetailView(DetailView):
    model = Entry

    def get_context_data(self, **kwargs):
        context = super(EntryDetailView, self).get_context_data(**kwargs)
        context['base_url'] = self.request.build_absolute_uri("/").rstrip("/")

        return context

models.py

from .managers import EntryManager

class Entry(models.Model):
    """ Blog Entry
    """
    insertion_date = models.DateTimeField('inserimento', auto_now_add=True)

Thank you for any help you could provide.

1
thank you @DanielRoseman, but how can I get the current entry instance in get_context_data(self, **kwargs)? - user123892
I don't see why you need to, since you can call that method from the template. But it's in self.object, see the docs. - Daniel Roseman
it works! good stuff to know, thank you! - user123892

1 Answers

0
votes

Just use the Django's get_previous_by_created and get_next_by_created qweryset

Note the created should be a field in your Post model

example

<ul class="post-nav group">
                   {% if post.get_previous_by_created %}
                    <li class="prev">
                        <strong>Previous Article</strong>
                        <a rel="prev" href="{{post.get_previous_by_created.get_absolute_url }}">
                            {{ post.get_previous_by_created}}</a>
                    </li>
                   {% endif %}
               {% if post.get_next_by_created%}
                     <li class="next">
                        <strong>Next Article</strong>
                         <a rel="next" href="{{ post.get_next_by_created.get_absolute_url}}">
                             {{ post.get_next_by_created.slug}}
                         </a>
                     </li>
               {% endif %}

Note post should be context variable in your post detail view