I am using a Django model to represent day-hour combinations. The goal is to render a matrix-like form with the days on the x-axis and the hours on the y-axis. The user can check each combination to define when a vehicle is available during a week.
The model looks as follows:
class TimeMatrix(models.Model):
MO00 = models.BooleanField(default=False)
MO01 = models.BooleanField(default=False)
MO02 = models.BooleanField(default=False)
MO03 = models.BooleanField(default=False)
....
SO22 = models.BooleanField(default=False)
SO23 = models.BooleanField(default=False)
I like to render the corresponding form coming from the CreateView as the mentioned matrix. The html to do this requires a list of days = ['MON', 'TUE', ..., 'SUN']
and hours = ['00', '01', ..., '23']
in order to render the form dynamically. The following html shows this without using the form the Django CreateView
provides:
<form action="#">
<div class="table-responsive">
<table class="table">
<thead class="thead-light">
<tr>
<th scope="col">Day</th>
{% for h in hours %}
<th scope="col">{{h}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for d in days %}
<tr>
<th scope="row" class="wt-col">{{d}}</th>
{% for h in hours %}
<td><input type="checkbox" name="{{d}}{{h}}" value="{{d}}{{h}}" id="id_{{d}}{{h}}"></td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
</form>
Since I like to use the security measures build into Django forms I like this to make use of the form
the CreateView
provides. Following this explanation, the individual form can be accessed using form.<field_name>
. Combining this with the html would require a dynamic way to access the form fields, which for me raises two questions:
- Following this advice I was able to implement getattr functionality for the templates which works with my models, but fails on the
form
the CreateView provides (e.g.{{form|getattribute:'MON00'}}
). What am I missing? - Since I cannot concat the day and hour string in the template (
{{form|getattribute:d+h}}
will not work), what is a suitable way to access the required form field?