Opened 9 years ago
Closed 9 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 , 9 years ago
| Component: | Uncategorized → Forms |
|---|---|
| Type: | Uncategorized → Cleanup/optimization |
comment:2 by , 9 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 , 9 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:5 by , 9 years ago
| Resolution: | → invalid |
|---|---|
| Status: | new → closed |
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?