Opened 10 years ago

Closed 10 years ago

#22294 closed Cleanup/optimization (fixed)

length filter changes type of output to string if passed safe string

Reported by: steve.pike@… Owned by: nobody
Component: Template system Version: dev
Severity: Normal Keywords: filter safe
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

if you do:

{% if some_string|length > 123 %}
Hurrah!
{% endif %}

what happens is what you expect to happen - the length of the string is determined and compared to the integer given in the condition.

However if you do this:

{% if some_safe_string|length > 123 %}
Booo!
{% endif %}

Then the result is non obvious, since passing a safe_string to length results in the output also being marked safe and thus changed into a safe *string*... on which you cannot do simple comparisons to integers in this way... (see: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#filters-and-auto-escaping and https://github.com/django/django/blob/master/django/template/defaultfilters.py#L581 )

This seems like a bug rather than a feature, but since the type of the result of the length filter is not stated in the docs ( https://docs.djangoproject.com/en/1.5/ref/templates/builtins/#length ) this is really misleading.

Change History (2)

comment:1 by Baptiste Mispelon, 10 years ago

Triage Stage: UnreviewedAccepted
Type: UncategorizedCleanup/optimization
Version: 1.5master

Hi,

I agree that this behavior is not obvious and could lead to hard-to-debug issues.

I don't really see a reason why length needs is_safe=True, since it should normally return either integers, or an empty string in case of an error.

In fact, making this change doesn't seem to break any existing test which is a good sign.

comment:2 by Claude Paroz <claude@…>, 10 years ago

Resolution: fixed
Status: newclosed

In bc315266c86f371ab04d05c43383775267e8595a:

Fixed #22294 -- Prevented converting length filter output to string

Thanks Steve Pike for the report.

Note: See TracTickets for help on using tickets.
Back to Top