steveclark
steveclark

Reputation: 537

Django pagination with dictionary where key is a list

I have a dictionary in my views.py file where the values are lists. In my template I have the following html:

{% for key, values in my_dict %}
    <tr>
        <td colspan="6" class="key">{{ key }}</td>
    </tr>
    {% for value in values %}
        <tr>
            <td colspan="6" class="value">{{ value }}</td>
        </tr>
    {% endfor %}
{% endfor %}

which prints out the name of the key followed by the list items inside the value. However, I want to be able to paginate the keys such that only 10 keys with their values appear per page.

I have the following code to do the pagination inside my index method in views.py:

paginator = Paginator(myDict, 10)
page_num = requests.GET.get('page', 1)
page = paginator.page(page_num)

I updated my template to {% for key, values in page %} and of course I get a TypeError because it's a hashable type. I'm just wondering how I can go about producing the same results as before but without using a dictionary.

I found this answer that suggests using tuples instead of dictionaries, but that doesn't seem to work for me and I'm guessing because my values are lists.

Upvotes: 3

Views: 5224

Answers (1)

bellum
bellum

Reputation: 3710

I am not sure if it can be count as good answer but anyway: I have just tried to replicate your problem and solution with tuple and it worked. So I think the problem can be in your code. My test code:

>>> from django.core.paginator import Paginator
>>> d = {'a': [1,2], 'b': [3,4]}
>>> p = Paginator(d, 1)
>>> p1 = p.page(1)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type
>>> t = tuple(d.items())
>>> t
(('a', [1, 2]), ('b', [3, 4]))
>>> p = Paginator(t, 1)
>>> p.page(1).object_list
(('a', [1, 2]),)
>>> p.page(2).object_list
(('b', [3, 4]),)

UPDATE: and looping also works. So can you show what structures do you have?

Upvotes: 6

Related Questions