Reputation: 327
How can I set order fields in Django ModelForm, when I dont know the number and the exact name of the fields?
I have a model named FormEntry, for which I want to create a ModelForm.
The only displaced Field should be plugin_data and dynamically created custom derivatives of it (label, initial,..) with language prefix (based on languages settings).
So if I have set in the settings the languages cs and en, then those fields must be available:
plugin_data, label_cs,label_en,initial_cs,initial_en,...
The new fields are dynamically created in __init__
, and I don't know how can I use new feature (Form.field_order) in Django 1.9 when I don't know the names of the fields in advance.
Upvotes: 1
Views: 943
Reputation: 327
Nevermind, solved it myself:
class someForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(FormElementEntryTransForm, self).__init__(*args, **kwargs)
# creating new fields
#...
self.order_fields(sorted(self.fields.keys())) # sort fields alphabetically
Upvotes: 3