Opened 16 years ago

Closed 15 years ago

#10143 closed (duplicate)

"add" template filter always converts arguments to integers

Reported by: jfw Owned by: nobody
Component: Template system Version: 1.0
Severity: Keywords:
Cc: Triage Stage: Design decision needed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The "add" template filter currently converts its arguments to integers. This makes using it with, for example, Decimals, impossible

It seems that changing it might break existing code, so perhaps another filter could be made? Obviously, I could make my own, but it seems like a useful thing for everyone. At the very least, the documentation on it should be updated--it made me think I was crazy until I looked at the code for the filter.

Change History (4)

comment:1 by Jacob, 16 years ago

Triage Stage: UnreviewedDesign decision needed

There has to be a cast to make it work in a sane manner since the argument passed to filters always comes in as a string. So if you've got {{ foo|add:"1" }}, Django has no way of knowing if you meant "add 1 to the number foo" (which should fail if foo isn't an integer) or "append the string '1' to the variable foo" (which should fail if foo isn't a string).

Bright ideas welcome, but I don't see a good way to solve this without a huge tree of isinstance checks, which would be nasty.

comment:2 by jfw, 16 years ago

I see how that would be a pain. Here's an idea--feel free to shoot it down. What about coercing the second argument to be the same type as the first? Presumably (and I know there would be cases where this presumption is wrong,) the first type *should* be the "right" type for the situation--it's most likely coming from the context, and therefore probably won't be a string (unless that's the intent.) Something like this:

def add(value, arg):
    try:
        return value + type(value)(arg)
    except ValueError:
        return int(value) + int(arg)

Thoughts?

comment:3 by Johannes Dollinger, 15 years ago

See #11687.

comment:4 by Jannis Leidel, 15 years ago

Resolution: duplicate
Status: newclosed

Closing this in favor of #11687 which has a smart solution.

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