Code

Ticket #11687: add_filter.diff

File add_filter.diff, 2.6 KB (added by gruszczy, 5 years ago)

coercing to int, then ducktyping + tests + docs

Line 
1Index: django/template/defaultfilters.py
2===================================================================
3--- django/template/defaultfilters.py   (wersja 11440)
4+++ django/template/defaultfilters.py   (kopia robocza)
5@@ -649,7 +649,13 @@
6 
7 def add(value, arg):
8     """Adds the arg to the value."""
9-    return int(value) + int(arg)
10+    try:
11+        return int(value) + int(arg)
12+    except (ValueError, TypeError):
13+        try:
14+            return value + arg
15+        except:
16+            return value
17 add.is_safe = False
18 
19 def get_digit(value, arg):
20Index: tests/regressiontests/templates/filters.py
21===================================================================
22--- tests/regressiontests/templates/filters.py  (wersja 11440)
23+++ tests/regressiontests/templates/filters.py  (kopia robocza)
24@@ -326,4 +326,15 @@
25         'date02': (r'{{ d|date }}', {'d': datetime(2008, 1, 1)}, 'Jan. 1, 2008'),
26         #Ticket 9520: Make sure |date doesn't blow up on non-dates
27         'date03': (r'{{ d|date:"m" }}', {'d': 'fail_string'}, ''),
28+       
29+         # base tests for add that assert, that old behaviour, which means
30+         # trying to add two values as ints, is kept
31+         'add01': (r'{{ i|add:"5" }}', {'i': 2000}, '2005'),
32+         'add02': (r'{{ i|add:"napis" }}', {'i': 2000}, '2000'),
33+         'add03': (r'{{ i|add:16 }}', {'i': 'not_an_int'}, 'not_an_int'),
34+         'add04': (r'{{ i|add:"16" }}', {'i': 'not_an_int'}, 'not_an_int16'),
35+         # further additions using dynamic typing
36+         'add05': (r'{{ l1|add:l2 }}', {'l1': [1, 2], 'l2': [3, 4]}, '[1, 2, 3, 4]'),
37+         'add06': (r'{{ t1|add:t2 }}', {'t1': (3, 4), 't2': (1, 2)}, '(3, 4, 1, 2)'),
38+         'add07': (r'{{ d|add:t }}', {'d': date(2000, 1, 1), 't': timedelta(10)}, '2000-01-11'),
39     }
40Index: docs/ref/templates/builtins.txt
41===================================================================
42--- docs/ref/templates/builtins.txt     (wersja 11440)
43+++ docs/ref/templates/builtins.txt     (kopia robocza)
44@@ -858,6 +858,19 @@
45 
46 If ``value`` is ``4``, then the output will be ``6``.
47 
48+.. versionadded:: 1.2
49+
50+At first filter tries to add two values coerced into integers and if this fails, it adds those two values using duck typing.
51+
52+For example:
53+
54+    {{ first_list|add:second_list }}
55+   
56+If ``first_list`` is ``[1, 2, 3]`` and ``second_list`` is ``[4, 5, 6]``, then the output will be ``[1, 2, 3, 4, 5, 6]``.
57+
58+Keep in mind, that for two strings, that can be coerced to integer, it will return a sum, rather than
59+a concatenation, as in the first example.
60+
61 .. templatefilter:: addslashes
62 
63 addslashes