Opened 8 years ago

Closed 8 years ago

#27986 closed Cleanup/optimization (invalid)

Change BaseModelForm dictionary variable object_data to be OrderedDict

Reported by: Edvinas Jurevicius Owned by: nobody
Component: Forms Version: 1.10
Severity: Normal Keywords: BaseModelForm, object_data, OrderedDict
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Can we change dictionary variable object_data to be OrderedDict this would help if we pass initial data as OrderedDict and want to loop through initial form values to be in the same order?

In [4]: initial
Out[4]: OrderedDict([(u'id', u'111'), (u'category', u'1'), (u'title', u'Chief Executives and Senior Officials')])

In [5]: object_data = OrderedDict()

In [6]: object_data.update(initial)

In [7]: object_data
Out[7]: OrderedDict([(u'id', u'111'), (u'category', u'1'), (u'title', u'Chief Executives and Senior Officials')])

https://github.com/django/django/blob/master/django/forms/models.py#L280

Change History (5)

comment:1 by Tim Graham, 8 years ago

Component: UncategorizedForms
Type: UncategorizedCleanup/optimization

The Django test suite passes with the change, so the only downside might be a small performance penalty.

Could you elaborate on the use case for looping over initial?

comment:2 by Edvinas Jurevicius, 8 years ago

Probably it's not worth adding if this going to effect the overall perfomance, but let me give you a quick example:

I have this code below where I loop through CSV file and building the initial data for the FormSets:

                for row in csv_file:

                    # Zip values from csv row to defined fields in csv_inline
                    zipped_data = OrderedDict(zip(self.csv_import_fields, row))

                    initial_data.append(zipped_data)

                ModelFormSet = modelformset_factory(self.model, ModelForm, extra=len(initial_data))
                formset = ModelFormSet(initial=initial_data)

In the view, I loop through FormSets initial data to display in the table as the read-only data but this data doesn't match the defined table headers for example my table headers are ID, Category but initial gives me first Category and then ID.

 {% for form in formset %}
   <tr>
     {% for value in form.initial.values %}
       <td>{{ value }}</td>
      {% endfor %}
    </tr>
     <tr>
        <td class="hidden">
          {{ form.as_p }}
         </td>
       </tr>
{% endfor %}

comment:3 by Tim Graham, 8 years ago

For this use case, I'm inclined to say it would be best to write a template tag or add a method to the form that returns the data in the desired order. Would that work?

comment:4 by Edvinas Jurevicius, 8 years ago

Yep, this would work thanks for your time!

comment:5 by Edvinas Jurevicius, 8 years ago

Resolution: invalid
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top