How can I create a book index with Python?

I have a section, and in this section, I have topics, for example, book chapters. But, on this section page, I only have the last three chapters, so, when I click, I can move forward to the single page where I am. This is my HTML template.

<ul>
          {% for chapter in book %}
            <li>
                <a href="#{{ chapter }}">{{ chapter }}</a>
            </li>
          {% endfor %}
</ul>

But, how can I access a section in example/book?page=2#chapter_five?

I tried to create a function to find the chapter in a for loop with all the pages, but I got that the object was not iterable.

I tried it in my views.

chapter = chapters.object_list
        chapters_pages = paginator.num_pages
        for page in chapters_pages:
            if page.contains(chapter):
                context["chapter_page"] = page

So I could do it, but it not worked.

<ul>
          {% for chapter in book %}
            <li>
                <a href="?page=chapter_page#{{ chapter }}">{{ chapter }}</a>
            </li>
          {% endfor %}
</ul>

The url is wrong, it should be like this:

?page={{ chapter_page }}&#{{ chapter }}
                        ^

Because these are two different querystring, hence should be differentiated by an &. Apart from that, the chapter_page should be a variable which is an integer. Finally, you are iterating through an integer (chapter.num_pages). It should be a list (paginator.page_range). For example:

for page in paginator.page_range:
        if page.contains(chapter):
            context["chapter_page"] = page.number

To be honest, you do not need this code based on my understanding. Because you want to pass the page number as chapter page, then you can pass the value of page number:

context["chapter_page"] = chapters.number

More information can be found in documentation.

Back to Top