'Django. How to filter posts with a date less than the current post?
I'm new to programming. And I don't understand methods. On the detailview post page I want to display a list of the next posts (i.e. whose time is less than the time of the current post) How do I access the date of the current post? I try:
class PostDetailView(DetailView):
model = Post
slug_field = 'url'
context_object_name = 'post'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['earlier_posts'] =
Post.objects.filter(publication_date__lte=self.publication_date)
return context
Then I have an error: 'PostDetailView' object has no attribute 'publication_date'
Thank you in advance
Solution 1:[1]
You get this error because self here refers to the PostDetailView instance, not the Post instance. You can get the model instance using DetailView.get_object()
current_post = self.get_object()
context['earlier_posts'] = self.get_queryset().filter(publication_date__lte=current_post.publication_date)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HÃ¥ken Lid |
