Link to dynamic number of fields in a template in django

Everything is very simple. I have this form:

class add_basketForm(forms.Form): def __init__(self, selected_subunits, *args, **kwargs): self.selected_subunits = selected_subunits super(add_basketForm, self).__init__(*args, **kwargs) for subunit in self.selected_subunits: self.fields['su%d' % (subunit['unit__id'])] = forms.IntegerField() 

The number of subunits is unknown. I would like to use something like this (you understand):

 {% for unit in selected_subunits %} {{ form.su%s }} % (unit.unit__id) {% endfor %} 

But of course this will not work. My question is, how can I refer to these form fields in the Django template language?

+8
django dynamic templates forms
source share
3 answers

To access the BoundField instances for your dynamic field instances, this gives you access to all the attributes and methods needed to render the field , you need to access the field objects using form form.fieldname , not form.fields[fieldname]

Here's the potential refactoring of your form class:

 class add_basketForm(forms.Form): def __init__(self, selected_subunits, *args, **kwargs): super(add_basketForm, self).__init__(*args, **kwargs) for subunit in self.selected_subunits: self.fields['su%d' % (subunit['unit__id'])] = forms.IntegerField() def su_fields(self): for name in self.fields: if name.startswith('su'): yield(self[name]) 

Then in your template, you will be able to form.su_fields over the fields, as you usually expect, by contacting form.su_fields :

 {% for su_field in form.su_fields %} .... {% endfor %} 

(I struggled with this problem for several hours. Thanks to this answer by Karl Mayer and this article about creating a dynamic form from Jacob Kaplan-Moss to point me in the right direction.)

+7
source share

Group these fields in an optional list, and then just iterate over this list.

In __init__ :

 self.subunit_list = [] for subunit in self.selected_subunits: field = forms.IntegerField() self.fields['su%d' % (subunit['unit__id'])] = field self.subunit_list.append(field) 

In the template:

 {% for field in form.subunit_list %} ... {% endfor %} 
+4
source share

To fix the gruszczy answer, this code worked for me:

In __init__ your form:

 self.subunit_list = [] for subunit in self.selected_subunits: field = forms.IntegerField() self.fields['su%d' % (subunit['unit__id'])] = field self.subunit_list.append(self['su%d' % (subunit['unit__id'])]) 

In your template:

 {% for field in form.subunit_list %} <!-- show form field (inputbox) --> {{ field }} {% endfor %} 
+1
source share

Source: https://habr.com/ru/post/650706/


All Articles