I have the following form that is manually rendered in a Django template. By “manually rendered” I mean that there is no corresponding Form or ModelForm object in the code (the reasons/details for not using a Form object are a bit complex, and can be safely left out of this quesion). I have a mental block now and I can’t seem to work out how to get this data in a usable form within the Django view. Specifically, how do I get the respective attendance_value and attendance_remarks for each workers_pks when the form is POSTed?
<form>
<table>
<thead>
<tr>
<th>Sl</th>
<th>Worker</th>
<th>Worker's Gender</th>
<th>Work</th>
<th>Unit cost of work</th>
<th>Job</th>
<th>Attendance</th> {# 1 or less if unit is day, 8 or less if unit is hours #}
<th>Remarks</th> {# if any #}
</tr>
</thead>
<tbody>
{% for result in results %}
<tr>
<th>{{ forloop.counter }}</th>
<td>{{ result.worker.name }} <input type="hidden" name="workers_pks" value="{{ result.worker.pk }}" id="id_workers_pks_{{ forloop.counter }}"></td>
<td>{{ result.worker.get_gender_display }}</td>
<td>{{ result.work.name }}</td>
<td>{{ result.work.unit_cost }} per {{ result.work.work_unit }}</td>
<td>{{ result.job_handover.job.name }}</td>
<td>
<input type='text' name='attendance_value' id='id_attendance_value_{{ forloop.counter }}' />
</td>
<td>
<input type='text' name='attendance_remarks' id='id_attendance_remarks_{{ forloop.counter }}' />
</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
Just to clarify, I know I can get the values by doing something like
workers = request.POST.getlist('workers_pks')
attendance_values = request.POST.getlist('attendance_values')
attendance_remarks = request.POST.getlist('attendance_remarks')
My main concern is how do I get the proper attendance_value and attendance_remarks for each corresponding workers_pks
Use the POST attribute of the request object –
However I see you’ve got lots of inputs with the same name attribute (and the browser will construct the post data using the input names as keys). You’ll need to change that. My recollection is that when django does this (with formsets), it adds a prefix to each name so that it can identify which object the input belongs with. I see you’ve already done this on the ids.
UPDATE
How about adding
worker.pkinto yournameattribute –Then in your view build the corresponding string –
You might want use a different loop (maybe loop through the inputs instead). But you get the idea.