Gonzalo Dambra
Gonzalo Dambra

Reputation: 980

Django template integer value iteration

I have the following model

class Table(models.Model):
    # Some not important attrs
    rows = IntegerField(etc)
    cols = IntegerField(etc)

Then I have my view where I'm rendering objects of this model. And I need to build some HTML tables based on the quantity of each objects' rows and cols.

View:

get_tables(request):
    tables = Table.objects.all()
    return render(request, 'tables.html', {'tables': tables})

I'm trying to do something like:

{% for table in tables %}
    <table>
        <thead>
            <tr>
                {% for col in table.cols %}
                    <th>column label here</th>
                {% endfor %}
            </tr>
        </thead>
        <tbody>
            {% for row in table.rows %}
                <tr>my row</tr>
            {% endfor %}
        </tbody>
    </table>
{% endfor %}

I know it is possible to loop for key in dict. But the values cols and rows are integers. How can I achieve this on a Django template?

Upvotes: 0

Views: 409

Answers (2)

Jose Rafael Angulo
Jose Rafael Angulo

Reputation: 54

Try

{% for table in tables %}
    <table>
        <thead>
            <tr>
                {% with ''|center:table.cols as range %}
                {% for _ in range %}
                    <th>column label here</th>
                {% endfor %}
                {% endwith %}
            </tr>
        </thead>
        <tbody>
            {% with ''|center:table.rows as range %}
            {% for _ in range %}
                <tr>my row</tr>
            {% endfor %}
            {% endwith %}
        </tbody>
    </table>
{% endfor %}

Upvotes: 1

Mukul Kumar
Mukul Kumar

Reputation: 2103

# You can take use of filter tags in django template

# For Example

Step 1:- Create 'templatetags' package in your app folder.

Step 2:- Create filter.py in 'templatetags' package

Step 3:- 

from django import template

register = template.Library()

def table_rows(value):
    value_list = [value]
    html_row = ''

    for val in value_list:
        html_row += '<tr></tr>'
    return html_row

def table_cols(value):
    value_list = [value]
    html_cols = ''

    for val in value_list:
        html_cols += '<td>Hello</td>'
    return html_cols


register.filter('table_rows', table_rows)
register.filter('table_cols', table_cols)


Step 4:-

# Your template can be:-

{% load filter %}

{% for table in tables %}
    <table border="1">
    {% autoescape off %}
    {{table.rows|table_rows}}
    {{table.cols|table_cols}}
    {% endautoescape %}
    </table>
{% endfor %}

# You can make changes according to your requirement

Upvotes: 0

Related Questions