Fixed #7013: Polish translation updated. Thank you, Piotr Lewandowski.
[fdr-django.git] / django / utils / maxlength.py
bloba616541f854c66a7a8d531f523b7f8a5a034becb
1 """
2 Utilities for providing backwards compatibility for the maxlength argument,
3 which has been replaced by max_length. See ticket #2101.
4 """
6 from warnings import warn
8 def get_maxlength(self):
9 return self.max_length
11 def set_maxlength(self, value):
12 self.max_length = value
14 def legacy_maxlength(max_length, maxlength):
15 """
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.
22 """
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
28 return max_length
30 def remove_maxlength(func):
31 """
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.
38 """
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)
48 return inner
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):
56 """
57 Metaclass for providing backwards compatibility support for the
58 "maxlength" keyword argument.
59 """
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)