Ticket #8462: add_template_length_filters_tests_2.diff

File add_template_length_filters_tests_2.diff, 2.3 KB (added by SmileyChris, 6 years ago)

PEP8 pedantry and one more test

  • django/template/defaultfilters.py

     
    507507
    508508def length(value):
    509509    """Returns the length of the value - useful for lists."""
    510     return len(value)
     510    try:
     511        return len(value)
     512    except (ValueError, TypeError):
     513        return ''
    511514length.is_safe = True
    512515
    513516def length_is(value, arg):
    514517    """Returns a boolean of whether the value's length is the argument."""
    515     return len(value) == int(arg)
     518    try:
     519        return len(value) == int(arg)
     520    except (ValueError, TypeError):
     521        return ''
    516522length_is.is_safe = False
    517523
    518524def random(value):
  • tests/regressiontests/templates/tests.py

     
    811811            'invalidstr05': ('{{ var }}', {}, ('', 'INVALID %s', 'var')),
    812812            'invalidstr06': ('{{ var.prop }}', {'var': {}}, ('', 'INVALID %s', 'var.prop')),
    813813
     814            # Usage of length and length_is filters.
     815            'length01': ('{{ lengthless_number|length }}', {'lengthless_number': 7}, ''),
     816            'length02': ('{{ some_list|length }}', {'some_list': ['4', None, True, {}]}, '4'),
     817            'length03': ('{{ some_list|length }}', {'some_list': []}, '0'),
     818            'length04': ('{{ None|length }}', {'None': None}, ''),
     819            'length_is01': ('{{ lengthless_number|length_is:"1" }}', {'lengthless_number': 7}, ''),
     820            'length_is02': ('{% if some_list|length_is:"4" %}Four{% endif %}', {'some_list': ['4', None, True, {}]}, 'Four'),
     821            'length_is03': ('{% if some_list|length_is:"4" %}Four{% else %}Not Four{% endif %}', {'some_list': ['4', None, True, {}, 17]}, 'Not Four'),
     822            'length_is04': ('{% if nested_list|length_is:"4" %}Four{% endif %}', {'nested_list': ['4', [4, 3, 1], True, ['a', None]]}, 'Four'),
     823            'length_is05': ('{% if nested_list|length_is:"fish" %}Fish?!{% endif %}', {'nested_list': [1, 2, 3]}, ''),
     824
    814825            ### MULTILINE #############################################################
    815826
    816827            'multiline01': ("""
Back to Top