Code

Opened 5 years ago

Closed 4 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: UI/UX:

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.

Attachments (0)

Change History (4)

comment:1 Changed 5 years ago by jacob

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Design 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 Changed 5 years ago by jfw

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 Changed 5 years ago by emulbreh

See #11687.

comment:4 Changed 4 years ago by jezdez

  • Resolution set to duplicate
  • Status changed from new to closed

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

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.