Fill-in 2D table with backreferencing
I'm trying to build a table with Django that:
- Uses a Many-to-Many relationship between the rows and columns.
- Allows for blanks.
- Is expandable.
- Stores a value that can be retrieved with the row and column name. I'm trying to use an intermediate model to do this (not sure if this is the best way).
I'm getting stuck referencing the values. My HTML table needs to list all possible rows and columns, and I don't think I can do that by looping over the table values since some may not exist.
Here's an example of what开发者_如何学编程 I'm trying to do...
models.py
from django.db import models
class Row(model.Models):
name = models.CharField(max_length=8)
class Col(model.Models):
rows = ManyToManyField(Row, through='Table')
name = models.CharField(max_length=8)
class Table(model.Models):
row = ForeignKey(Row)
col = ForeignKey(Col)
value = models.FloatField()
The view:
views.py
from django.shortcuts import *
from test.app.models import *
def table(request):
rows = Row.objects.all()
cols = Col.objects.all()
values = Table.objects.all()
return render_to_response(
'app/table.html',
{'row_list': rows, 'col_list': cols, 'value_list': values}
)
Html code (getting stuck trying to access the values):
table.html
{% extends "base.html" %}
{% block content %}
<h2>My Table</h2>
<ul>
<TABLE border=4 bgcolor=lightgray align=center>
<TR>
<TD align=center bgcolor=darkgray><strong></strong></TD>
{% for col in col_list %}
<TD align=center bgcolor=darkgray><strong>{{ col.name }}</strong></TD>
{% endfor %}
</TR>
{% for row in row_list %}
<TR>
<TD align=center bgcolor=darkgray><strong>{{ col.name }}</strong></TD>
{% for col in col_list %}
{% if row in col.rows.all %}
<!-- How can I access the table values here? -->
<TD align=left><input type="text" name="value" value="???" id="id_{{ col.id }}_{{ row.id }}" /></TD>
{% else %}
<TD align=left><input type="text" name="value" value="" id="{{col.id}}_{{row.id}}" /></TD>
{% endif %}
{% endfor %}
</TR>
{% endfor %}
</ul>
{% endblock %}
I ultimately want to make it a form that will update the values, but right now I just need to get my html code working. Any help would be appreciated.
You should create a two dimensional array with your values:
col_lookup = dict([(col.id, i) for i, col in enumerate(cols)])
row_lookup = dict([(row.id, i) for i, row in enumerate(rows)])
# create an "empty" two dimensional array.
# each row is a tuple in the format (row, [False, False, False...])
table = [(row, [False for x in xrange(len(col_lookup))]) for row in rows]
for cell in Table.objects.all():
table[row_lookup[cell.row_id]][1][col_lookup[cell.col_id]] = cell.value
Now render table
. Use {%for row, values in table%}
...{{row.name}}
...{%for value in values%}
(I did not test the code. Suggestion: rename your Table
model to Cell
)
精彩评论