I use formset to produce extra fields, but i don’t know how to change the label for extra field produced by formset.
My code:
class GetMachine(forms.Form):
Number_of_Lines = forms.IntegerField(max_value=4)
class GetLine(forms.Form):
beamline_name = forms.CharField(max_length=15, label='Name of Beamline-%i')
def install(request):
MachineFormSet = formset_factory(GetMachine, extra=1)
formset = MachineFormSet()
if request.method == 'POST':
# formset = MachineFormSet(request.POST)
# if formset.is_valid(): # All validation rules pass
line_no = request.POST['form-0-Number_of_Lines']
GetLineFormSet = formset_factory(GetLine, extra=int(line_no))
formset = GetLineFormSet()
return render_to_response('install.html', { 'formset': formset, 'action': 'step1'})
return render_to_response('install.html', { 'formset': formset, })
install.html template:
{% for form in formset.forms %}
{% for field in form %}
<tr>
<td>{{ field.label_tag }}</td> <td>{{ field }}</td><td>{{ field.errors }}</td>
</tr>
{% endfor %}
{% endfor %}
For example if the “Number_of_Lines” = 2, then i expect the next form with the labels,
Name of Beamline-1:
Name of Beamline-2:
I’m assuming you want the result of the first form to determine the number of fields and their labels of the second, you might want to look into Django form wizards. But here’s a simple, non-form-wizard (and probably less ideal/maintainable) way to do it, utilising the
__init__method of the formset to modify the form labels*:forms.py:
views.py:
urls.py:
get_no_of_lines.html:
line_form.html:
The reason why I say this approach is probably not the best way to do this is because you have to validate
no_of_linesbeing passed toline_formview (which could be > 4, so you’ll have to perform validation here and introduce validation logic rather than having it one place — the form). And if you need to add a new field to the first form, you’ll likely end up having to modify the code. So hence why I’d recommend looking into form wizards.