Miquel
Miquel

Reputation: 858

Django - how to render a matrix

I need to render a dynamic matrix form (nrows x ncols) in Django.

The form is the following:

class MatrixForm(forms.Form):

    def __init__(self, *args, **kwargs):
        self.ncols = kwargs.pop('ncols', 1)
        self.nrows = kwargs.pop('nrows', 1)

        super(MatrixForm, self).__init__(*args, **kwargs)

        for i in range(0,self.ncols):
            for j in range(0,self.nrows):
                field = forms.CharField(label="",max_length=2)
                self.fields['c_' + str(i) + '_' + str(j)] = field

The view is the following:

def my_matrix(request):
    [nrows,ncols] = [3,4]

    my_form = MatrixForm(nrows=nrows,ncols=ncols)

    return render_to_response('my_matrix.html', RequestContext(request, 
                        {'matrix_form':my_form,"nrows":range(nrows),"ncols":range(ncols)}))

But I am stucked with the template. My idea is to perform a typical double loop (columns and rows) and then refer individually to each element of the matrix, but it is not possible in Django: I should access the fields with something like {{ matrix_form.c_{{ row }}_{{ col }} }}...

What are your recommendations to perform it?

Upvotes: 1

Views: 1617

Answers (1)

fsalazar_sch
fsalazar_sch

Reputation: 455

I've copied the solution in another question here

The table — including labels — should be built in the view. forloop.first can be used to put the labels in

s. table = [
     ['', 'Foo', 'Bar', 'Barf'],
     ['Spam', 101, 102, 103],
     ['Eggs', 201, 202, 203], ]

<table>
    {% for row in table %}
        <tr>
        {% for cell in row %}
            {% if forloop.first or forloop.parentloop.first %} <th> {% else %} <td> {% endif %}
                {{ cell }}
            {% if forloop.first or forloop.parentloop.first %} </th> {% else %} </td> {% endif %}
        {% endfor %}
        </tr>
    {% endfor %}
</table>

Upvotes: 1

Related Questions