Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking data into multiple display columns with Django

Overlap in terminology makes search for answers difficult for this one.

I'm looking for advice on the best way to implement a multiple-column display of my QuerySet that fills each column top to bottom over X columns. Meaning that the number of items in each column equals the QuerySet count divided by X (number of columns).

Using Offset doesn't work for this because I would like my data to grow into 4 columns without updating the offset manually. CSS floats work visually, but leave the data out of order.

like image 586
Sam Avatar asked Feb 26 '23 03:02

Sam


2 Answers

Something like that should work for you, pass the number of columns as columns to the template:

{% for item in items %}
    {% if forloop.first %}<div style="float:left;">{% endif %}
    {{ item }}
    {% if forloop.counter|divisibleby:columns %}
        </div><div style="float:left">
    {% endif %}
    {% if forloop.last %}</div>{% endif %}    
{% endfor %}
<div style="clear:both;"></div>
like image 146
Bernhard Vallant Avatar answered Mar 05 '23 14:03

Bernhard Vallant


It seems like lazerscience's answer is on the right track - but I think the OP wants the data to alphabetically sort the data down the column and then start back at the top of the next column. Using divisibleby: works to break the line after 'X' items, but I think it'll take a more complex template to do what the OP wants.

Not sure if it's possible, but in the view could you: Get item count, divide by 'columns' and used that # in Divisibleby to break into the next DIV column (the visual flow will be CSS)

As Lazers's example is now you're constructing Rows and then breaking it into columns, leaving the sort order across and then down.

Sorry if I missed something.

-K

like image 20
Kim Avatar answered Mar 05 '23 13:03

Kim