Reorder fields directly in the ModelForm

 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

  1. ModelForm Class saving m2m by ckarrie2 2 years, 6 months ago
  2. filtered ModelChoiceField queries by robharvey 6 years, 1 month ago
  3. Class ModelInfo for show object info by marinho 5 years, 9 months ago
  4. change a widget attribute in ModelForm without define the field by jedie 5 years, 8 months ago
  5. unique validation for ModelForm by whiskybar 6 years, 1 month ago

Comments

danux (on July 11, 2008):

Line 19 should read:

    self.fields.insert(new_pos, 'c', value)

Otherwise an excellent snippet that just saved my skin, thank you

#

obioma (on September 5, 2008):

Thanks for the snippet, here a little bit more generic:

def __init__(self, *args, **kwargs):
    super(DemoForm, self).__init__(*args, **kwargs)
    # order now: a b c
    order = ('b', 'c', 'a')
    tmp = copy(self.fields)
    self.fields = SortedDict()
    for item in order:
        self.fields[item] = tmp[item]

I wonder if it would make sense to include this order in the meta class part and do internally.

#

(Forgotten your password?)