Home > database >  Django get_next_by_date conditions not rendering properly in template
Django get_next_by_date conditions not rendering properly in template

Time:04-13

I have a model named "Manga". In this model I have manytomanyfield object called chapters with this model.

class Chapter(models.Model):
    chapter=models.IntegerField()
    manga=models.ForeignKey(Manga, null=True, on_delete=models.CASCADE)
    images=models.ManyToManyField(Image, blank=True)
    date= models.DateTimeField()
    def __str__(self):
        return f"{self.manga} Chapter {self.chapter}"
    
    class Meta:
        ordering = ('-date',)

I get Chapter in my view with

def chapterview(request, manga_id, chapter_id):
    manga=Manga.objects.get(id=manga_id)
    chapter=Chapter.objects.filter(manga=manga).get(id=chapter_id)
    pages=chapter.images.all()

And next and previous chapters with:

    try:
        nextchapter=chapter.get_next_by_date
    except Chapter.DoesNotExist:
        nextchapter=None
    try:
        prevchapter=chapter.get_previous_by_date
    except Chapter.DoesNotExist:
        prevchapter=None

The problem is that these template conditions Don't work properly:

{% if nextchapter and not prevchapter %},
{% elif nextchapter and prevchapter %},
{% else %}

Only {% elif nextchapter and prevchapter %} works. And since this conditions are for next/previous buttons to render, I get error because next chapter does not exist but there is the button to go to that page which I click beforehand. I want to prefferably get rid of get_next_by_date method and just get the next Chapter of manytomanyfield. How can I achieve this?

CodePudding user response:

You need to call the methods, so:

try:
    nextchapter = chapter.get_next_by_date()
except Chapter.DoesNotExist:
    nextchapter = None
try:
    prevchapter = chapter.get_previous_by_date()
except Chapter.DoesNotExist:
    prevchapter = None
  • Related