I have written a factory function to create dynamic forms, as described towards the end of James Bennett’s helpful post http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/.
The form works perfectly well, but the items are shown in a somewhat random looking order, due (I assume) to the fact that fields is a dictionary (please see code sample below). How can I prescribe a defined display order for the form fields?
def make_form(assessment):
'''
Factory function to build and return dynamic AssessmentForms
'''
entries = assessment.entry_set.all()
fields = {}
for entry in entries:
fields[entry.name] = forms.ChoiceField(
required=False,
initial=entry.rating,
choices=CHOICES,
widget=forms.RadioSelect()
)
return type('AssessmentForm', (forms.BaseForm,), { 'base_fields': fields })
Use a
SortedDict(djangos implementation ofOrderedDict2.7+)https://github.com/django/django/blob/master/django/utils/datastructures.py