2 Utilities for providing backwards compatibility for the maxlength argument,
3 which has been replaced by max_length. See ticket #2101.
6 from warnings
import warn
8 def get_maxlength(self
):
11 def set_maxlength(self
, value
):
12 self
.max_length
= value
14 def legacy_maxlength(max_length
, maxlength
):
16 Consolidates max_length and maxlength, providing backwards compatibilty
17 for the legacy "maxlength" argument.
19 If one of max_length or maxlength is given, then that value is returned.
20 If both are given, a TypeError is raised. If maxlength is used at all, a
21 deprecation warning is issued.
23 if maxlength
is not None:
24 warn("maxlength is deprecated. Use max_length instead.", DeprecationWarning, stacklevel
=3)
25 if max_length
is not None:
26 raise TypeError("Field cannot take both the max_length argument and the legacy maxlength argument.")
27 max_length
= maxlength
30 def remove_maxlength(func
):
32 A decorator to be used on a class's __init__ that provides backwards
33 compatibilty for the legacy "maxlength" keyword argument, i.e.
34 name = models.CharField(maxlength=20)
36 It does this by changing the passed "maxlength" keyword argument
37 (if it exists) into a "max_length" keyword argument.
39 def inner(self
, *args
, **kwargs
):
40 max_length
= kwargs
.get('max_length', None)
41 # pop maxlength because we don't want this going to __init__.
42 maxlength
= kwargs
.pop('maxlength', None)
43 max_length
= legacy_maxlength(max_length
, maxlength
)
44 # Only set the max_length keyword argument if we got a value back.
45 if max_length
is not None:
46 kwargs
['max_length'] = max_length
47 func(self
, *args
, **kwargs
)
50 # This metaclass is used in two places, and should be removed when legacy
51 # support for maxlength is dropped.
52 # * oldforms.FormField
53 # * db.models.fields.Field
55 class LegacyMaxlength(type):
57 Metaclass for providing backwards compatibility support for the
58 "maxlength" keyword argument.
60 def __init__(cls
, name
, bases
, attrs
):
61 super(LegacyMaxlength
, cls
).__init
__(name
, bases
, attrs
)
62 # Decorate the class's __init__ to remove any maxlength keyword.
63 cls
.__init
__ = remove_maxlength(cls
.__init
__)
64 # Support accessing and setting to the legacy maxlength attribute.
65 cls
.maxlength
= property(get_maxlength
, set_maxlength
)