#25574 closed Cleanup/optimization (fixed)
A minor enhancement to "for" tag description in the reference
| Reported by: | wodny | Owned by: | Jacek Bzdak |
|---|---|---|---|
| Component: | Documentation | Version: | 1.8 |
| Severity: | Normal | Keywords: | for tag lookup order dict defaultdict |
| Cc: | Triage Stage: | Accepted | |
| Has patch: | yes | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | yes | UI/UX: | no |
Description
I would like to propose a minor enhancement to a paragraph which gives an example on using the "for" tag with dictionaries:
{% for key, value in data.items %} {{ key }}: {{ value }} {% endfor %}
Currently it doesn't recall the reader that the lookup order would cause different output if the "dict" dictionary contains the "items" key than when it doesn't.
On the other hand a paragraph about defaultdict on another page suggests using dict instead of defaultdict. But while it solves the problem of creating an entry by making a lookup it doesn't solve the problem of "items" key within a dictionary.
I thought that maybe one or both pages could contain a reminder that the view author should remember not to pass a dictionary with the "items" key if the template author wants to use that "for key, value" construct.
Change History (6)
comment:1 by , 10 years ago
| Easy pickings: | set |
|---|---|
| Triage Stage: | Unreviewed → Accepted |
| Type: | Uncategorized → Cleanup/optimization |
comment:2 by , 10 years ago
| Owner: | changed from to |
|---|---|
| Status: | new → assigned |
comment:3 by , 10 years ago
| Has patch: | set |
|---|
Here is the PR link: https://github.com/django/django/pull/5450.
Here is full wording (maybe a bit verbose):
Keep in mind that ``items`` key in a dictionary will shadow ``items()``
function. This lookup order can cause some unexpected behavior.
In normal situations Django template expression ``{{ data.items }}`` will
return result of following python code: ``data.items()``, however if
``data`` dictionary will contain ``items`` key, the same django expression
will return: ``data['items']``, which is most probably *not what you want*.
You should avoid adding dictionary entries whose keys are named like methods
of dictionary instance for example: ``items``, ``values``, ``keys``, to
dictionaries that will be passed to Django templates.
For additional information see
:ref:`documentation of template variables <template-variables>`.
If this is OK (I don't really know what is the protocol) I'll do this issue.