Monday, 19 July 2021

Adding a maximum limit to the number of post using python

I need to limit the number of posts in Django queries. I have tried to add a min and max but nothing seemed to have worked.

Example: I should only have the 15 most recent posts in my blog. The rest can be seen by clicking on the category button.

view.py:

class HomeView(ListView):
    model = Post
    template_name = 'home.html'
    ordering = ['-id']

    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

models.py:

class Post(models.Model):
    title = models.CharField(max_length=255)
    header_image = models.ImageField(null=True, blank=True, upload_to='images/')
    title_tag = models.CharField(max_length=255)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = RichTextField(blank=True, null=True)
    post_date = models.DateField(auto_now_add=True)
    category = models.CharField(max_length=255, default='intro')
    snippet = models.CharField(max_length=255)
    likes = models.ManyToManyField(User, related_name='post_likes')
    dislikes = models.ManyToManyField(User, related_name='post_dislikes')


from Adding a maximum limit to the number of post using python

No comments:

Post a Comment