Odif Yltsaeb
Odif Yltsaeb

Reputation: 5676

django modelform and additional fields and their order

I have a modelform and im creating additional fields (that do not exist in model) for its form.

I know you can reorder the fields in modelform like it says in the docs.

But the problem is - i want the additional fields to be rendered BEFORE the other fields.

Is it possible to somehow reorder the fields of the form before rendering? How does form object keep track of the order of its fields anyway?

Alan

Upvotes: 2

Views: 1796

Answers (3)

Puyb
Puyb

Reputation: 11

The solutions above no longer works with django 2 (I don't know since when)...

But now, there's an ordered dict fields property on ModelForm that we can use to reorder the fields...

class MyForm(forms.ModelForm):
    class Meta:
        fields = ['model_field1', 'model_field2']
        model = MyModel
    extra_field = forms.CharField()
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for k in self._meta.fields:
            self.fields.move_to_end(k)

Upvotes: 1

Odif Yltsaeb
Odif Yltsaeb

Reputation: 5676

No matter. It seems i found answer already and this seems to do the trick, since i have added 2 additional fields:

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)

        self.build_fields()
        l = len(self.fields.keyOrder)
        for i in range(0,2):
            f = self.fields.keyOrder[l-1]
            self.fields.keyOrder.pop(l-1)
            self.fields.keyOrder.insert(0, f)

This above was my initial fix. Later on i found out that it did not cut any more. Then i did this :

class AlertForm(forms.ModelForm):
    class Meta:
        model = Message
        fields = model_fields

    def __init__(self, *args, **kwargs):
        super(AlertForm, self).__init__(*args, **kwargs)

        self.build_fields()
        newKeyOrder = []
        newKeyOrder.append('field_that_had_to_be_first')
        if typechange:
            newKeyOrder.append('field_thats_sometimes_necessary')
        newKeyOrder += model_fields 
        self.fields.keyOrder = newKeyOrder

Upvotes: 1

Iain Shelvington
Iain Shelvington

Reputation: 32314

The fields attribute of your ModelForm`s Meta class define which fields to show and in which order.

Use the fields attribute of the ModelForm's inner Meta class. This attribute, if given, should be a list of field names to include in the form. The order in which the fields names are specified in that list is respected when the form renders them.

Upvotes: 0

Related Questions