How can I make transitions to the next article from the post_details(DetailView), so that both the next article and the previous one are available ?
vievs.py
class HomeView(ListView):
model = Post
#queryset = Post.objects.filter(status=1)
cats = Category.objects.all()
template_name = 'home.html'
#ordering = ['-post_date']
paginate_by = 6
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(HomeView, self).get_context_data(*args, **kwargs)
context["cat_menu"] = cat_menu
return context
class ArticleDetailView(HitCountDetailView):
model = Post
template_name = 'post_detail.html'
count_hit = True
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(ArticleDetailView, self).get_context_data(*args, **kwargs)
stuff = get_object_or_404(Post, id=self.kwargs['pk'])
total_likes = stuff.total_likes()
context["cat_menu"] = cat_menu
context["total_likes"] = total_likes
return context
Sort by date and ID
If you want the previous or next item based on a DateTimeField
, you can work with .get_previous_by_fieldname(…)
[Django-doc] or .get_next_by_fieldname(…)
[Django-doc]. You thus can obtain the previous/next item for stuff
with:
try:
prev_stuff = stuff.get_previous_by_post_date()
except Stuff.DoesNotExist:
prev_stuff = None
try:
next_stuff = stuff.get_next_by_post_date()
except Stuff.DoesNotExist:
next_stuff = None