from django import newforms as forms from django.newforms.forms import BoundField from django.template import Context, Template class MedForm(forms.Form): """Dynamically assigned/rendered newforms fields using BoundField >>> m = MedForm({'med_1':"Lipitor",'dosage_1':"80mg QHS PO", \ 'med_2':"Lasix",'dosage_2':"40mg QD PO"}) >>> t = Template('''{% for med in form.med_list %} ... {{med.name.label}}: {{ med.name.bf }} {{ med.dosage.bf }} ... {% endfor %}''') >>> print t.render(Context({'form':m})) med_1: med_2: med_3: med_4: >>> """ def __init__(self, *args, **kwargs): number_of_meds = kwargs.pop('number_of_meds', 4) super(MedForm, self).__init__(*args, **kwargs) self.med_list = [] for i in range(1, number_of_meds+1): k1 = 'med_%d' % i self.fields[k1] = forms.CharField(required=False, label=k1) self.fields[k1].bf = BoundField(self, self.fields[k1], k1) k2 = 'dosage_%d' % i self.fields[k2] = forms.CharField(required=False, label=k2) self.fields[k2].bf = BoundField(self, self.fields[k2], k2) self.med_list.append({'name': self.fields[k1], 'dosage': self.fields[k2]}) if __name__ == '__main__': import doctest doctest.testmod()