Sometimes the order of the fields you get from a model needs to be adjusted when displaying its modelform. If it's just a few fields you can do it in the template, but what if you want to iterate over the form?
The fields are stored in a SortedDict, so you can change the order in the init of the form. A bit clunky, yes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | # This code is Public Domain where the Public Domain exists,
# and covered by an MIT-license everywhere else (that is:
# do as you wish with it, but you don't get to blame me
# for anything)
class Demo(models.Model):
a = models.IntegerField()
b = models.IntegerField()
c = models.IntegerField()
class DemoForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(DemoForm, self).__init__(*args, **kwargs)
# order now: a b c
value = self.fields.pop('c')
new_pos = self.fields.keyOrder.index('b')
self.fields.insert(pos, 'c', value)
# order now: a c b
class Meta:
model = 'Demo'
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Line 19 should read:
Otherwise an excellent snippet that just saved my skin, thank you
#
Thanks for the snippet, here a little bit more generic:
I wonder if it would make sense to include this order in the meta class part and do internally.
#
Please login first before commenting.