Django - 如何渲染矩阵

时间:2013-07-01 17:16:31

标签: django django-templates

我需要在Django中渲染动态矩阵形式(nrows x ncols)。

表格如下:

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

视图如下:

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)}))

但我被模板困扰了。我的想法是执行一个典型的双循环(列和行)然后单独引用矩阵的每个元素,但在Django中是不可能的:我应该使用像{{matrix_form.c _ {{row}这样的字段访问字段} _ {{col}}}} ...

你有什么建议来执行它?

1 个答案:

答案 0 :(得分:1)

我已在另一个问题here

中复制了该解决方案
  

表格 - 包括标签 - 应该在视图中构建。   forloop.first可用于将标签放入

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>