Django

Code

Ticket #2101: max_length.5.diff

File max_length.5.diff, 124.4 kB (added by gwilson, 1 year ago)

Use PendingDeprecationWarning instead of default UserWarning.

  • django/utils/maxlength.py

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

    old new  
     1# Test access to max_length while still providing full backwards compatibility 
     2# with legacy maxlength attribute. 
     3""" 
     4 
     5Don't print out the deprecation warnings during testing. 
     6>>> from warnings import filterwarnings 
     7>>> filterwarnings("ignore") 
     8 
     9# legacy_maxlength function 
     10 
     11>>> from django.utils.maxlength import legacy_maxlength 
     12 
     13>>> legacy_maxlength(None, None) 
     14 
     15 
     16>>> legacy_maxlength(10, None) 
     1710 
     18 
     19>>> legacy_maxlength(None, 10) 
     2010 
     21 
     22>>> legacy_maxlength(10, 12) 
     23Traceback (most recent call last): 
     24... 
     25TypeError: field can not take both the max_length argument and the legacy maxlength argument. 
     26 
     27>>> legacy_maxlength(0, 10) 
     28Traceback (most recent call last): 
     29... 
     30TypeError: field can not take both the max_length argument and the legacy maxlength argument. 
     31 
     32>>> legacy_maxlength(0, None) 
     330 
     34 
     35>>> legacy_maxlength(None, 0) 
     360 
     37 
     38#=============================================================================== 
     39# Fields 
     40#=============================================================================== 
     41 
     42# Set up fields 
     43>>> from django.db.models import fields 
     44>>> new = fields.Field(max_length=15) 
     45>>> old = fields.Field(maxlength=10) 
     46 
     47# Ensure both max_length and legacy maxlength are not able to both be specified 
     48>>> fields.Field(maxlength=10, max_length=15) 
     49Traceback (most recent call last): 
     50    ... 
     51TypeError: field can not take both the max_length argument and the legacy maxlength argument. 
     52 
     53# Test max_length 
     54>>> new.max_length 
     5515 
     56>>> old.max_length 
     5710 
     58 
     59# Test accessing maxlength 
     60>>> new.maxlength 
     6115 
     62>>> old.maxlength 
     6310 
     64 
     65# Test setting maxlength 
     66>>> new.maxlength += 1 
     67>>> old.maxlength += 1 
     68>>> new.max_length 
     6916 
     70>>> old.max_length 
     7111 
     72 
     73# SlugField __init__ passes through max_length so test that too 
     74>>> fields.SlugField('new', max_length=15).max_length 
     7515 
     76>>> fields.SlugField('empty').max_length 
     7750 
     78>>> fields.SlugField('old', maxlength=10).max_length 
     7910 
     80 
     81#=============================================================================== 
     82# (old)forms 
     83#=============================================================================== 
     84 
     85>>> from django import oldforms 
     86 
     87# Test max_length attribute 
     88 
     89>>> oldforms.TextField('new', max_length=15).render('') 
     90u'<input type="text" id="id_new" class="vTextField" name="new" size="30" value="" maxlength="15" />' 
     91 
     92>>> oldforms.IntegerField('new', max_length=15).render('') 
     93u'<input type="text" id="id_new" class="vIntegerField" name="new" size="10" value="" maxlength="15" />' 
     94 
     95>>> oldforms.SmallIntegerField('new', max_length=15).render('') 
     96u'<input type="text" id="id_new" class="vSmallIntegerField" name="new" size="5" value="" maxlength="15" />' 
     97 
     98>>> oldforms.PositiveIntegerField('new', max_length=15).render('') 
     99u'<input type="text" id="id_new" class="vPositiveIntegerField" name="new" size="10" value="" maxlength="15" />' 
     100 
     101>>> oldforms.PositiveSmallIntegerField('new', max_length=15).render('') 
     102u'<input type="text" id="id_new" class="vPositiveSmallIntegerField" name="new" size="5" value="" maxlength="15" />' 
     103 
     104>>> oldforms.DatetimeField('new', max_length=15).render('') 
     105u'<input type="text" id="id_new" class="vDatetimeField" name="new" size="30" value="" maxlength="15" />' 
     106 
     107>>> oldforms.EmailField('new', max_length=15).render('') 
     108u'<input type="text" id="id_new" class="vEmailField" name="new" size="50" value="" maxlength="15" />' 
     109>>> oldforms.EmailField('new').render('') 
     110u'<input type="text" id="id_new" class="vEmailField" name="new" size="50" value="" maxlength="75" />' 
     111 
     112>>> oldforms.URLField('new', max_length=15).render('') 
     113u'<input type="text" id="id_new" class="vURLField" name="new" size="50" value="" maxlength="15" />' 
     114>>> oldforms.URLField('new').render('') 
     115u'<input type="text" id="id_new" class="vURLField" name="new" size="50" value="" maxlength="200" />' 
     116 
     117>>> oldforms.IPAddressField('new', max_length=15).render('') 
     118u'<input type="text" id="id_new" class="vIPAddressField" name="new" size="15" value="" maxlength="15" />' 
     119>>> oldforms.IPAddressField('new').render('') 
     120u'<input type="text" id="id_new" class="vIPAddressField" name="new" size="15" value="" maxlength="15" />' 
     121 
     122>>> oldforms.CommaSeparatedIntegerField('new', max_length=15).render('') 
     123u'<input type="text" id="id_new" class="vCommaSeparatedIntegerField" name="new" size="20" value="" maxlength="15" />' 
     124 
     125 
     126# Test legacy maxlength attribute 
     127 
     128>>> oldforms.TextField('old', maxlength=10).render('') 
     129u'<input type="text" id="id_old" class="vTextField" name="old" size="30" value="" maxlength="10" />' 
     130 
     131>>> oldforms.IntegerField('old', maxlength=10).render('') 
     132u'<input type="text" id="id_old" class="vIntegerField" name="old" size="10" value="" maxlength="10" />' 
     133 
     134>>> oldforms.SmallIntegerField('old', maxlength=10).render('') 
     135u'<input type="text" id="id_old" class="vSmallIntegerField" name="old" size="5" value="" maxlength="10" />' 
     136 
     137>>> oldforms.PositiveIntegerField('old', maxlength=10).render('') 
     138u'<input type="text" id="id_old" class="vPositiveIntegerField" name="old" size="10" value="" maxlength="10" />' 
     139 
     140>>> oldforms.PositiveSmallIntegerField('old', maxlength=10).render('') 
     141u'<input type="text" id="id_old" class="vPositiveSmallIntegerField" name="old" size="5" value="" maxlength="10" />' 
     142 
     143>>> oldforms.DatetimeField('old', maxlength=10).render('') 
     144u'<input type="text" id="id_old" class="vDatetimeField" name="old" size="30" value="" maxlength="10" />' 
     145 
     146>>> oldforms.EmailField('old', maxlength=10).render('') 
     147u'<input type="text" id="id_old" class="vEmailField" name="old" size="50" value="" maxlength="10" />' 
     148 
     149>>> oldforms.URLField('old', maxlength=10).render('') 
     150u'<input type="text" id="id_old" class="vURLField" name="old" size="50" value="" maxlength="10" />' 
     151 
     152>>> oldforms.IPAddressField('old', maxlength=10).render('') 
     153u'<input type="text" id="id_old" class="vIPAddressField" name="old" size="15" value="" maxlength="10" />' 
     154 
     155>>> oldforms.CommaSeparatedIntegerField('old', maxlength=10).render('') 
     156u'<input type="text" id="id_old" class="vCommaSeparatedIntegerField" name="old" size="20" value="" maxlength="10" />' 
     157""" 
     158if __name__ == "__main__": 
     159    import doctest 
     160    doctest.testmod() 
  • django/contrib/admin/models.py

    old new  
    1818    user = models.ForeignKey(User) 
    1919    content_type = models.ForeignKey(ContentType, blank=True, null=True) 
    2020    object_id = models.TextField(_('object id'), blank=True, null=True) 
    21     object_repr = models.CharField(_('object repr'), maxlength=200) 
     21    object_repr = models.CharField(_('object repr'), max_length=200) 
    2222    action_flag = models.PositiveSmallIntegerField(_('action flag')) 
    2323    change_message = models.TextField(_('change message'), blank=True) 
    2424    objects = LogEntryManager() 
  • django/contrib/admin/templatetags/admin_modify.py

    old new  
    192192            t.append(u'document.getElementById("id_%s").onkeyup = function() {' \ 
    193193                     ' var e = document.getElementById("id_%s");' \ 
    194194                     ' if(!e._changed) { e.value = URLify(%s, %s);} }; ' % ( 
    195                      f, field.name, add_values, field.maxlength)) 
     195                     f, field.name, add_values, field.max_length)) 
    196196    return u''.join(t) 
    197197auto_populated_field_script = register.simple_tag(auto_populated_field_script) 
    198198 
  • django/contrib/admin/views/doc.py

    old new  
    291291DATA_TYPE_MAPPING = { 
    292292    'AutoField'                 : _('Integer'), 
    293293    'BooleanField'              : _('Boolean (Either True or False)'), 
    294     'CharField'                 : _('String (up to %(maxlength)s)'), 
     294    'CharField'                 : _('String (up to %(max_length)s)'), 
    295295    'CommaSeparatedIntegerField': _('Comma-separated integers'), 
    296296    'DateField'                 : _('Date (without time)'), 
    297297    'DateTimeField'             : _('Date (with time)'), 
     
    310310    'PhoneNumberField'          : _('Phone number'), 
    311311    'PositiveIntegerField'      : _('Integer'), 
    312312    'PositiveSmallIntegerField' : _('Integer'), 
    313     'SlugField'                 : _('String (up to %(maxlength)s)'), 
     313    'SlugField'                 : _('String (up to %(max_length)s)'), 
    314314    'SmallIntegerField'         : _('Integer'), 
    315315    'TextField'                 : _('Text'), 
    316316    'TimeField'                 : _('Time'), 
  • django/contrib/auth/forms.py

    old new  
    1010    "A form that creates a user, with no privileges, from the given username and password." 
    1111    def __init__(self): 
    1212        self.fields = ( 
    13             oldforms.TextField(field_name='username', length=30, maxlength=30, is_required=True, 
     13            oldforms.TextField(field_name='username', length=30, max_length=30, is_required=True, 
    1414                validator_list=[validators.isAlphaNumeric, self.isValidUsername]), 
    15             oldforms.PasswordField(field_name='password1', length=30, maxlength=60, is_required=True), 
    16             oldforms.PasswordField(field_name='password2', length=30, maxlength=60, is_required=True, 
     15            oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True), 
     16            oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True, 
    1717                validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]), 
    1818        ) 
    1919 
     
    4242        """ 
    4343        self.request = request 
    4444        self.fields = [ 
    45             oldforms.TextField(field_name="username", length=15, maxlength=30, is_required=True, 
     45            oldforms.TextField(field_name="username", length=15, max_length=30, is_required=True, 
    4646                validator_list=[self.isValidUser, self.hasCookiesEnabled]), 
    47             oldforms.PasswordField(field_name="password", length=15, maxlength=30, is_required=True), 
     47            oldforms.PasswordField(field_name="password", length=15, max_length=30, is_required=True), 
    4848        ] 
    4949        self.user_cache = None 
    5050 
     
    111111    def __init__(self, user): 
    112112        self.user = user 
    113113        self.fields = ( 
    114             oldforms.PasswordField(field_name="old_password", length=30, maxlength=30, is_required=True, 
     114            oldforms.PasswordField(field_name="old_password", length=30, max_length=30, is_required=True, 
    115115                validator_list=[self.isValidOldPassword]), 
    116             oldforms.PasswordField(field_name="new_password1", length=30, maxlength=30, is_required=True, 
     116            oldforms.PasswordField(field_name="new_password1", length=30, max_length=30, is_required=True, 
    117117                validator_list=[validators.AlwaysMatchesOtherField('new_password2', _("The two 'new password' fields didn't match."))]), 
    118             oldforms.PasswordField(field_name="new_password2", length=30, maxlength=30, is_required=True), 
     118            oldforms.PasswordField(field_name="new_password2", length=30, max_length=30, is_required=True), 
    119119        ) 
    120120 
    121121    def isValidOldPassword(self, new_data, all_data): 
     
    133133    def __init__(self, user): 
    134134        self.user = user 
    135135        self.fields = ( 
    136             oldforms.PasswordField(field_name='password1', length=30, maxlength=60, is_required=True), 
    137             oldforms.PasswordField(field_name='password2', length=30, maxlength=60, is_required=True, 
     136            oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True), 
     137            oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True, 
    138138                validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]), 
    139139        ) 
    140140 
  • django/contrib/auth/models.py

    old new  
    5050 
    5151    Three basic permissions -- add, change and delete -- are automatically created for each Django model. 
    5252    """ 
    53     name = models.CharField(_('name'), maxlength=50) 
     53    name = models.CharField(_('name'), max_length=50) 
    5454    content_type = models.ForeignKey(ContentType) 
    55     codename = models.CharField(_('codename'), maxlength=100) 
     55    codename = models.CharField(_('codename'), max_length=100) 
    5656 
    5757    class Meta: 
    5858        verbose_name = _('permission') 
     
    7070 
    7171    Beyond permissions, groups are a convenient way to categorize users to apply some label, or extended functionality, to them. For example, you could create a group 'Special users', and you could write code that would do special things to those users -- such as giving them access to a members-only portion of your site, or sending them members-only e-mail messages. 
    7272    """ 
    73     name = models.CharField(_('name'), maxlength=80, unique=True) 
     73    name = models.CharField(_('name'), max_length=80, unique=True) 
    7474    permissions = models.ManyToManyField(Permission, verbose_name=_('permissions'), blank=True, filter_interface=models.HORIZONTAL) 
    7575 
    7676    class Meta: 
     
    108108 
    109109    Username and password are required. Other fields are optional. 
    110110    """ 
    111     username = models.CharField(_('username'), maxlength=30, unique=True, validator_list=[validators.isAlphaNumeric], help_text=_("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores).")) 
    112     first_name = models.CharField(_('first name'), maxlength=30, blank=True) 
    113     last_name = models.CharField(_('last name'), maxlength=30, blank=True) 
     111    username = models.CharField(_('username'), max_length=30, unique=True, validator_list=[validators.isAlphaNumeric], help_text=_("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores).")) 
     112    first_name = models.CharField(_('first name'), max_length=30, blank=True) 
     113    last_name = models.CharField(_('last name'), max_length=30, blank=True) 
    114114    email = models.EmailField(_('e-mail address'), blank=True) 
    115     password = models.CharField(_('password'), maxlength=128, help_text=_("Use '[algo]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>.")) 
     115    password = models.CharField(_('password'), max_length=128, help_text=_("Use '[algo]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>.")) 
    116116    is_staff = models.BooleanField(_('staff status'), default=False, help_text=_("Designates whether the user can log into this admin site.")) 
    117117    is_active = models.BooleanField(_('active'), default=True, help_text=_("Designates whether this user can log into the Django admin. Unselect this instead of deleting accounts.")) 
    118118    is_superuser = models.BooleanField(_('superuser status'), default=False, help_text=_("Designates that this user has all permissions without explicitly assigning them.")) 
  • django/contrib/comments/models.py

    old new  
    6565    user = models.ForeignKey(User, raw_id_admin=True) 
    6666    content_type = models.ForeignKey(ContentType) 
    6767    object_id = models.IntegerField(_('object ID')) 
    68     headline = models.CharField(_('headline'), maxlength=255, blank=True) 
    69     comment = models.TextField(_('comment'), maxlength=3000) 
     68    headline = models.CharField(_('headline'), max_length=255, blank=True) 
     69    comment = models.TextField(_('comment'), max_length=3000) 
    7070    rating1 = models.PositiveSmallIntegerField(_('rating #1'), blank=True, null=True) 
    7171    rating2 = models.PositiveSmallIntegerField(_('rating #2'), blank=True, null=True) 
    7272    rating3 = models.PositiveSmallIntegerField(_('rating #3'), blank=True, null=True) 
     
    164164    # A FreeComment is a comment by a non-registered user. 
    165165    content_type = models.ForeignKey(ContentType) 
    166166    object_id = models.IntegerField(_('object ID')) 
    167     comment = models.TextField(_('comment'), maxlength=3000) 
    168     person_name = models.CharField(_("person's name"), maxlength=50) 
     167    comment = models.TextField(_('comment'), max_length=3000) 
     168    person_name = models.CharField(_("person's name"), max_length=50) 
    169169    submit_date = models.DateTimeField(_('date/time submitted'), auto_now_add=True) 
    170170    is_public = models.BooleanField(_('is public')) 
    171171    ip_address = models.IPAddressField(_('ip address')) 
  • django/contrib/comments/views/comments.py

    old new  
    2929            else: 
    3030                return [] 
    3131        self.fields.extend([ 
    32             oldforms.LargeTextField(field_name="comment", maxlength=3000, is_required=True, 
     32            oldforms.LargeTextField(field_name="comment", max_length=3000, is_required=True, 
    3333                validator_list=[self.hasNoProfanities]), 
    3434            oldforms.RadioSelectField(field_name="rating1", choices=choices, 
    3535                is_required=ratings_required and num_rating_choices > 0, 
     
    122122    "Manipulator that handles public free (unregistered) comments" 
    123123    def __init__(self): 
    124124        self.fields = ( 
    125             oldforms.TextField(field_name="person_name", maxlength=50, is_required=True, 
     125            oldforms.TextField(field_name="person_name", max_length=50, is_required=True, 
    126126                validator_list=[self.hasNoProfanities]), 
    127             oldforms.LargeTextField(field_name="comment", maxlength=3000, is_required=True, 
     127            oldforms.LargeTextField(field_name="comment", max_length=3000, is_required=True, 
    128128                validator_list=[self.hasNoProfanities]), 
    129129        ) 
    130130 
  • django/contrib/contenttypes/models.py

    old new  
    3232        CONTENT_TYPE_CACHE = {} 
    3333 
    3434class ContentType(models.Model): 
    35     name = models.CharField(maxlength=100) 
    36     app_label = models.CharField(maxlength=100) 
    37     model = models.CharField(_('python model class name'), maxlength=100) 
     35    name = models.CharField(max_length=100) 
     36    app_label = models.CharField(max_length=100) 
     37    model = models.CharField(_('python model class name'), max_length=100) 
    3838    objects = ContentTypeManager() 
    3939    class Meta: 
    4040        verbose_name = _('content type') 
  • django/contrib/flatpages/models.py

    old new  
    44from django.utils.translation import ugettext_lazy as _ 
    55 
    66class FlatPage(models.Model): 
    7     url = models.CharField(_('URL'), maxlength=100, validator_list=[validators.isAlphaNumericURL], db_index=True, 
     7    url = models.CharField(_('URL'), max_length=100, validator_list=[validators.isAlphaNumericURL], db_index=True, 
    88        help_text=_("Example: '/about/contact/'. Make sure to have leading and trailing slashes.")) 
    9     title = models.CharField(_('title'), maxlength=200) 
     9    title = models.CharField(_('title'), max_length=200) 
    1010    content = models.TextField(_('content')) 
    1111    enable_comments = models.BooleanField(_('enable comments')) 
    12     template_name = models.CharField(_('template name'), maxlength=70, blank=True, 
     12    template_name = models.CharField(_('template name'), max_length=70, blank=True, 
    1313        help_text=_("Example: 'flatpages/contact_page.html'. If this isn't provided, the system will use 'flatpages/default.html'.")) 
    1414    registration_required = models.BooleanField(_('registration required'), help_text=_("If this is checked, only logged-in users will be able to view the page.")) 
    1515    sites = models.ManyToManyField(Site) 
  • django/contrib/redirects/models.py

    old new  
    44 
    55class Redirect(models.Model): 
    66    site = models.ForeignKey(Site, radio_admin=models.VERTICAL) 
    7     old_path = models.CharField(_('redirect from'), maxlength=200, db_index=True, 
     7    old_path = models.CharField(_('redirect from'), max_length=200, db_index=True, 
    88        help_text=_("This should be an absolute path, excluding the domain name. Example: '/events/search/'.")) 
    9     new_path = models.CharField(_('redirect to'), maxlength=200, blank=True, 
     9    new_path = models.CharField(_('redirect to'), max_length=200, blank=True, 
    1010        help_text=_("This can be either an absolute path (as above) or a full URL starting with 'http://'.")) 
    1111 
    1212    class Meta: 
  • django/contrib/sessions/models.py

    old new  
    6565    the sessions documentation that is shipped with Django (also available 
    6666    on the Django website). 
    6767    """ 
    68     session_key = models.CharField(_('session key'), maxlength=40, primary_key=True) 
     68    session_key = models.CharField(_('session key'), max_length=40, primary_key=True) 
    6969    session_data = models.TextField(_('session data')) 
    7070    expire_date = models.DateTimeField(_('expire date')) 
    7171    objects = SessionManager() 
  • django/contrib/sites/models.py

    old new  
    1212        return self.get(pk=sid) 
    1313 
    1414class Site(models.Model): 
    15     domain = models.CharField(_('domain name'), maxlength=100) 
    16     name = models.CharField(_('display name'), maxlength=50) 
     15    domain = models.CharField(_('domain name'), max_length=100) 
     16    name = models.CharField(_('display name'), max_length=50) 
    1717    objects = SiteManager() 
    1818    class Meta: 
    1919        db_table = 'django_site' 
  • django/core/management.py

    old new  
    910910                    field_type, new_params = field_type 
    911911                    extra_params.update(new_params) 
    912912 
    913                 # Add maxlength for all CharFields. 
     913                # Add max_length for all CharFields. 
    914914                if field_type == 'CharField' and row[3]: 
    915                     extra_params['maxlength'] = row[3] 
     915                    extra_params['max_length'] = row[3] 
    916916 
    917917                if field_type == 'DecimalField': 
    918918                    extra_params['max_digits'] = row[4] 
     
    987987        for f in opts.fields: 
    988988            if f.name == 'id' and not f.primary_key and opts.pk.name == 'id': 
    989989                e.add(opts, '"%s": You can\'t use "id" as a field name, because each model automatically gets an "id" field if none of the fields have primary_key=True. You need to either remove/rename your "id" field or add primary_key=True to a field.' % f.name) 
    990             if isinstance(f, models.CharField) and f.maxlength in (None, 0): 
    991                 e.add(opts, '"%s": CharFields require a "maxlength" attribute.' % f.name) 
     990            if isinstance(f, models.CharField) and f.max_length in (None, 0): 
     991                e.add(opts, '"%s": CharFields require a "max_length" attribute.' % f.name) 
    992992            if isinstance(f, models.DecimalField): 
    993993                if f.decimal_places is None: 
    994994                    e.add(opts, '"%s": DecimalFields require a "decimal_places" attribute.' % f.name) 
     
    10131013            if f.db_index not in (None, True, False): 
    10141014                e.add(opts, '"%s": "db_index" should be either None, True or False.' % f.name) 
    10151015 
    1016             # Check that maxlength <= 255 if using older MySQL versions. 
     1016            # Check that max_length <= 255 if using older MySQL versions. 
    10171017            if settings.DATABASE_ENGINE == 'mysql': 
    10181018                db_version = connection.get_server_version() 
    1019                 if db_version < (5, 0, 3) and isinstance(f, (models.CharField, models.CommaSeparatedIntegerField, models.SlugField)) and f.maxlength > 255: 
    1020                     e.add(opts, '"%s": %s cannot have a "maxlength" greater than 255 when you are using a version of MySQL prior to 5.0.3 (you are using %s).' % (f.name, f.__class__.__name__, '.'.join([str(n) for n in db_version[:3]]))) 
     1019                if db_version < (5, 0, 3) and isinstance(f, (models.CharField, models.CommaSeparatedIntegerField, models.SlugField)) and f.max_length > 255: 
     1020                    e.add(opts, '"%s": %s cannot have a "max_length" greater than 255 when you are using a version of MySQL prior to 5.0.3 (you are using %s).' % (f.name, f.__class__.__name__, '.'.join([str(n) for n in db_version[:3]]))) 
    10211021 
    10221022            # Check to see if the related field will clash with any 
    10231023            # existing fields, m2m fields, m2m related objects or related objects 
     
    12521252    from django.db import backend, connection, transaction, models 
    12531253    fields = ( 
    12541254        # "key" is a reserved word in MySQL, so use "cache_key" instead. 
    1255         models.CharField(name='cache_key', maxlength=255, unique=True, primary_key=True), 
     1255        models.CharField(name='cache_key', max_length=255, unique=True, primary_key=True), 
    12561256        models.TextField(name='value'), 
    12571257        models.DateTimeField(name='expires', db_index=True), 
    12581258    ) 
  • django/db/backends/ado_mssql/creation.py

    old new  
    11DATA_TYPES = { 
    22    'AutoField':         'int IDENTITY (1, 1)', 
    33    'BooleanField':      'bit', 
    4     'CharField':         'varchar(%(maxlength)s)', 
    5     'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)', 
     4    'CharField':         'varchar(%(max_length)s)', 
     5    'CommaSeparatedIntegerField': 'varchar(%(max_length)s)', 
    66    'DateField':         'smalldatetime', 
    77    'DateTimeField':     'smalldatetime', 
    88    'DecimalField':      'numeric(%(max_digits)s, %(decimal_places)s)', 
     
    1717    'PhoneNumberField':  'varchar(20)', 
    1818    'PositiveIntegerField': 'int CONSTRAINT [CK_int_pos_%(column)s] CHECK ([%(column)s] > 0)', 
    1919    'PositiveSmallIntegerField': 'smallint CONSTRAINT [CK_smallint_pos_%(column)s] CHECK ([%(column)s] > 0)', 
    20     'SlugField':         'varchar(%(maxlength)s)', 
     20    'SlugField':         'varchar(%(max_length)s)', 
    2121    'SmallIntegerField': 'smallint', 
    2222    'TextField':         'text', 
    2323    'TimeField':         'time', 
  • django/db/backends/mysql/creation.py

    old new  
    55DATA_TYPES = { 
    66    'AutoField':         'integer AUTO_INCREMENT', 
    77    'BooleanField':      'bool', 
    8     'CharField':         'varchar(%(maxlength)s)', 
    9     'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)', 
     8    'CharField':         'varchar(%(max_length)s)', 
     9    'CommaSeparatedIntegerField': 'varchar(%(max_length)s)', 
    1010    'DateField':         'date', 
    1111    'DateTimeField':     'datetime', 
    1212    'DecimalField':      'numeric(%(max_digits)s, %(decimal_places)s)', 
     
    2121    'PhoneNumberField':  'varchar(20)', 
    2222    'PositiveIntegerField': 'integer UNSIGNED', 
    2323    'PositiveSmallIntegerField': 'smallint UNSIGNED', 
    24     'SlugField':         'varchar(%(maxlength)s)', 
     24    'SlugField':         'varchar(%(max_length)s)', 
    2525    'SmallIntegerField': 'smallint', 
    2626    'TextField':         'longtext', 
    2727    'TimeField':         'time', 
  • django/db/backends/mysql_old/creation.py

    old new  
    55DATA_TYPES = { 
    66    'AutoField':         'integer AUTO_INCREMENT', 
    77    'BooleanField':      'bool', 
    8     'CharField':         'varchar(%(maxlength)s)', 
    9     'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)', 
     8    'CharField':         'varchar(%(max_length)s)', 
     9    'CommaSeparatedIntegerField': 'varchar(%(max_length)s)', 
    1010    'DateField':         'date', 
    1111    'DateTimeField':     'datetime', 
    1212    'DecimalField':      'numeric(%(max_digits)s, %(decimal_places)s)', 
     
    2121    'PhoneNumberField':  'varchar(20)', 
    2222    'PositiveIntegerField': 'integer UNSIGNED', 
    2323    'PositiveSmallIntegerField': 'smallint UNSIGNED', 
    24     'SlugField':         'varchar(%(maxlength)s)', 
     24    'SlugField':         'varchar(%(max_length)s)', 
    2525    'SmallIntegerField': 'smallint', 
    2626    'TextField':         'longtext', 
    2727    'TimeField':         'time', 
  • django/db/backends/oracle/creation.py

    old new  
    88DATA_TYPES = { 
    99    'AutoField':                    'NUMBER(11)', 
    1010    'BooleanField':                 'NUMBER(1) CHECK (%(column)s IN (0,1))', 
    11     'CharField':                    'NVARCHAR2(%(maxlength)s)', 
    12     'CommaSeparatedIntegerField':   'VARCHAR2(%(maxlength)s)', 
     11    'CharField':                    'NVARCHAR2(%(max_length)s)', 
     12    'CommaSeparatedIntegerField':   'VARCHAR2(%(max_length)s)', 
    1313    'DateField':                    'DATE', 
    1414    'DateTimeField':                'TIMESTAMP', 
    1515    'DecimalField':                 'NUMBER(%(max_digits)s, %(decimal_places)s)', 
  • django/db/backends/postgresql/creation.py

    old new  
    55DATA_TYPES = { 
    66    'AutoField':         'serial', 
    77    'BooleanField':      'boolean', 
    8     'CharField':         'varchar(%(maxlength)s)', 
    9     'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)', 
     8    'CharField':         'varchar(%(max_length)s)', 
     9    'CommaSeparatedIntegerField': 'varchar(%(max_length)s)', 
    1010    'DateField':         'date', 
    1111    'DateTimeField':     'timestamp with time zone', 
    1212    'DecimalField':      'numeric(%(max_digits)s, %(decimal_places)s)', 
     
    2121    'PhoneNumberField':  'varchar(20)', 
    2222    'PositiveIntegerField': 'integer CHECK ("%(column)s" >= 0)', 
    2323    'PositiveSmallIntegerField': 'smallint CHECK ("%(column)s" >= 0)', 
    24     'SlugField':         'varchar(%(maxlength)s)', 
     24    'SlugField':         'varchar(%(max_length)s)', 
    2525    'SmallIntegerField': 'smallint', 
    2626    'TextField':         'text', 
    2727    'TimeField':         'time', 
  • django/db/backends/sqlite3/creation.py

    old new  
    44DATA_TYPES = { 
    55    'AutoField':                    'integer', 
    66    'BooleanField':                 'bool', 
    7     'CharField':                    'varchar(%(maxlength)s)', 
    8     'CommaSeparatedIntegerField':   'varchar(%(maxlength)s)', 
     7    'CharField':                    'varchar(%(max_length)s)', 
     8    'CommaSeparatedIntegerField':   'varchar(%(max_length)s)', 
    99    'DateField':                    'date', 
    1010    'DateTimeField':                'datetime', 
    1111    'DecimalField':                 'decimal', 
     
    2020    'PhoneNumberField':             'varchar(20)', 
    2121    'PositiveIntegerField':         'integer unsigned', 
    2222    'PositiveSmallIntegerField':    'smallint unsigned', 
    23     'SlugField':                    'varchar(%(maxlength)s)', 
     23    'SlugField':                    'varchar(%(max_length)s)', 
    2424    'SmallIntegerField':            'smallint', 
    2525    'TextField':                    'text', 
    2626    'TimeField':                    'time', 
  • django/db/backends/sqlite3/introspection.py

    old new  
    8181            import re 
    8282            m = re.search(r'^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$', key) 
    8383            if m: 
    84                 return ('CharField', {'maxlength': int(m.group(1))}) 
     84                return ('CharField', {'max_length': int(m.group(1))}) 
    8585            raise KeyError 
    8686 
    8787DATA_TYPES_REVERSE = FlexibleFieldLookupDict() 
  • django/db/models/fields/__init__.py

    old new  
    1111from django.utils.text import capfirst 
    1212from django.utils.translation import ugettext_lazy, ugettext as _ 
    1313from django.utils.encoding import smart_unicode, force_unicode, smart_str 
     14from django.utils.maxlength import LegacyMaxlength 
    1415import datetime, os, time 
    1516try: 
    1617    import decimal 
     
    6364#     getattr(obj, opts.pk.attname) 
    6465 
    6566class Field(object): 
    66  
     67    # Provide backwards compatibility for the maxlength attribute and 
     68    # argument for this class and all subclasses. 
     69    __metaclass__ = LegacyMaxlength 
     70     
    6771    # Designates whether empty strings fundamentally are allowed at the 
    6872    # database level. 
    6973    empty_strings_allowed = True 
     
    7276    creation_counter = 0 
    7377 
    7478    def __init__(self, verbose_name=None, name=None, primary_key=False, 
    75         maxlength=None, unique=False, blank=False, null=False, db_index=False, 
     79        max_length=None, unique=False, blank=False, null=False, db_index=False, 
    7680        core=False, rel=None, default=NOT_PROVIDED, editable=True, serialize=True, 
    7781        prepopulate_from=None, unique_for_date=None, unique_for_month=None, 
    7882        unique_for_year=None, validator_list=None, choices=None, radio_admin=None, 
     
    8084        self.name = name 
    8185        self.verbose_name = verbose_name 
    8286        self.primary_key = primary_key 
    83         self.maxlength, self.unique = maxlength, unique 
     87        self.max_length, self.unique = max_length, unique 
    8488        self.blank, self.null = blank, null 
    8589        # Oracle treats the empty string ('') as null, so coerce the null 
    8690        # option whenever '' is a possible value. 
     
    244248 
    245249    def prepare_field_objs_and_params(self, manipulator, name_prefix): 
    246250        params = {'validator_list': self.validator_list[:]} 
    247         if self.maxlength and not self.choices: # Don't give SelectFields a maxlength parameter. 
    248             params['maxlength'] = self.maxlength 
     251        if self.max_length and not self.choices: # Don't give SelectFields a max_length parameter. 
     252            params['max_length'] = self.max_length 
    249253 
    250254        if self.choices: 
    251255            if self.radio_admin: 
     
    461465        return smart_unicode(value) 
    462466 
    463467    def formfield(self, **kwargs): 
    464         defaults = {'max_length': self.maxlength} 
     468        defaults = {'max_length': self.max_length} 
    465469        defaults.update(kwargs) 
    466470        return super(CharField, self).formfield(**defaults) 
    467471 
     
    670674 
    671675class EmailField(CharField): 
    672676    def __init__(self, *args, **kwargs): 
    673         kwargs['maxlength'] = 75 
     677        kwargs['max_length'] = 75 
    674678        CharField.__init__(self, *args, **kwargs) 
    675679 
    676680    def get_internal_type(self): 
     
    829833class IPAddressField(Field): 
    830834    empty_strings_allowed = False 
    831835    def __init__(self, *args, **kwargs): 
    832         kwargs['maxlength'] = 15 
     836        kwargs['max_length'] = 15 
    833837        Field.__init__(self, *args, **kwargs) 
    834838 
    835839    def get_manipulator_field_objs(self): 
     
    877881 
    878882class SlugField(Field): 
    879883    def __init__(self, *args, **kwargs): 
    880         kwargs['maxlength'] = kwargs.get('maxlength', 50) 
     884        kwargs['max_length'] = kwargs.get('max_length', 50) 
    881885        kwargs.setdefault('validator_list', []).append(validators.isSlug) 
    882886        # Set db_index=True unless it's been set manually. 
    883887        if 'db_index' not in kwargs: 
     
    963967 
    964968class URLField(CharField): 
    965969    def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs): 
    966         kwargs['maxlength'] = kwargs.get('maxlength', 200) 
     970        kwargs['max_length'] = kwargs.get('max_length', 200) 
    967971        if verify_exists: 
    968972            kwargs.setdefault('validator_list', []).append(validators.isExistingURL) 
    969973        self.verify_exists = verify_exists 
  • django/newforms/fields.py

    old new  
    120120 
    121121    def widget_attrs(self, widget): 
    122122        if self.max_length is not None and isinstance(widget, (TextInput, PasswordInput)): 
     123            # The HTML attribute is maxlength, not max_length. 
    123124            return {'maxlength': str(self.max_length)} 
    124125 
    125126class IntegerField(Field): 
  • django/oldforms/__init__.py

    old new  
    44from django.conf import settings 
    55from django.utils.translation import ugettext, ungettext 
    66from django.utils.encoding import smart_unicode, force_unicode 
     7from django.utils.maxlength import LegacyMaxlength 
    78 
    89FORM_FIELD_ID_PREFIX = 'id_' 
    910 
     
    302303    Subclasses should also implement a render(data) method, which is responsible 
    303304    for rending the form field in XHTML. 
    304305    """ 
     306    # Provide backwards compatibility for the maxlength attribute and 
     307    # argument for this class and all subclasses. 
     308    __metaclass__ = LegacyMaxlength 
    305309 
    306310    def __str__(self): 
    307311        return unicode(self).encode('utf-8') 
     
    390394 
    391395class TextField(FormField): 
    392396    input_type = "text" 
    393     def __init__(self, field_name, length=30, maxlength=None, is_required=False, validator_list=None, member_name=None): 
     397    def __init__(self, field_name, length=30, max_length=None, is_required=False, validator_list=None, member_name=None): 
    394398        if validator_list is None: validator_list = [] 
    395399        self.field_name = field_name 
    396         self.length, self.maxlength = length, maxlength 
     400        self.length, self.max_length = length, max_length 
    397401        self.is_required = is_required 
    398402        self.validator_list = [self.isValidLength, self.hasNoNewlines] + validator_list 
    399403        if member_name != None: 
    400404            self.member_name = member_name 
    401405 
    402406    def isValidLength(self, data, form): 
    403         if data and self.maxlength and len(smart_unicode(data)) > self.maxlength: 
     407        if data and self.max_length and len(smart_unicode(data)) > self.max_length: 
    404408            raise validators.ValidationError, ungettext("Ensure your text is less than %s character.", 
    405                 "Ensure your text is less than %s characters.", self.maxlength) % self.maxlength 
     409                "Ensure your text is less than %s characters.", self.max_length) % self.max_length 
    406410 
    407411    def hasNoNewlines(self, data, form): 
    408412        if data and '\n' in data: 
     
    411415    def render(self, data): 
    412416        if data is None: 
    413417            data = u'' 
    414         maxlength = u'' 
    415         if self.maxlength: 
    416             maxlength = u'maxlength="%s" ' % self.maxlength 
     418        max_length = u'' 
     419        if self.max_length: 
     420            max_length = u'maxlength="%s" ' % self.max_length 
    417421        return u'<input type="%s" id="%s" class="v%s%s" name="%s" size="%s" value="%s" %s/>' % \ 
    418422            (self.input_type, self.get_id(), self.__class__.__name__, self.is_required and u' required' or '', 
    419             self.field_name, self.length, escape(data), maxlength) 
     423            self.field_name, self.length, escape(data), max_length) 
    420424 
    421425    def html2python(data): 
    422426        return data 
     
    426430    input_type = "password" 
    427431 
    428432class LargeTextField(TextField): 
    429     def __init__(self, field_name, rows=10, cols=40, is_required=False, validator_list=None, maxlength=None): 
     433    def __init__(self, field_name, rows=10, cols=40, is_required=False, validator_list=None, max_length=None): 
    430434        if validator_list is None: validator_list = [] 
    431435        self.field_name = field_name 
    432436        self.rows, self.cols, self.is_required = rows, cols, is_required 
    433437        self.validator_list = validator_list[:] 
    434         if maxlength: 
     438        if max_length: 
    435439            self.validator_list.append(self.isValidLength) 
    436             self.maxlength = maxlength 
     440            self.max_length = max_length 
    437441 
    438442    def render(self, data): 
    439443        if data is None: 
     
    710714#################### 
    711715 
    712716class IntegerField(TextField): 
    713     def __init__(self, field_name, length=10, maxlength=None, is_required=False, validator_list=None, member_name=None): 
     717    def __init__(self, field_name, length=10, max_length=None, is_required=False, validator_list=None, member_name=None): 
    714718        if validator_list is None: validator_list = [] 
    715719        validator_list = [self.isInteger] + validator_list 
    716720        if member_name is not None: 
    717721            self.member_name = member_name 
    718         TextField.__init__(self, field_name, length, maxlength, is_required, validator_list) 
     722        TextField.__init__(self, field_name, length, max_length, is_required, validator_list)