Fixed #2101 -- Renamed `maxlength` argument to `max_length` for oldforms `FormField`s and db model `Field`s. This is fully backwards compatible at the moment since the legacy `maxlength` argument is still supported. Using `maxlength` will, however, issue a `PendingDeprecationWarning` when used.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@5803 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Gary Wilson Jr 2007-08-05 05:14:46 +00:00
parent 973f44aa4c
commit 212ee65be7
88 changed files with 647 additions and 407 deletions

View File

@ -18,7 +18,7 @@ class LogEntry(models.Model):
user = models.ForeignKey(User) user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType, blank=True, null=True) content_type = models.ForeignKey(ContentType, blank=True, null=True)
object_id = models.TextField(_('object id'), blank=True, null=True) object_id = models.TextField(_('object id'), blank=True, null=True)
object_repr = models.CharField(_('object repr'), maxlength=200) object_repr = models.CharField(_('object repr'), max_length=200)
action_flag = models.PositiveSmallIntegerField(_('action flag')) action_flag = models.PositiveSmallIntegerField(_('action flag'))
change_message = models.TextField(_('change message'), blank=True) change_message = models.TextField(_('change message'), blank=True)
objects = LogEntryManager() objects = LogEntryManager()

View File

@ -192,7 +192,7 @@ def auto_populated_field_script(auto_pop_fields, change = False):
t.append(u'document.getElementById("id_%s").onkeyup = function() {' \ t.append(u'document.getElementById("id_%s").onkeyup = function() {' \
' var e = document.getElementById("id_%s");' \ ' var e = document.getElementById("id_%s");' \
' if(!e._changed) { e.value = URLify(%s, %s);} }; ' % ( ' if(!e._changed) { e.value = URLify(%s, %s);} }; ' % (
f, field.name, add_values, field.maxlength)) f, field.name, add_values, field.max_length))
return u''.join(t) return u''.join(t)
auto_populated_field_script = register.simple_tag(auto_populated_field_script) auto_populated_field_script = register.simple_tag(auto_populated_field_script)

View File

@ -291,7 +291,7 @@ def get_return_data_type(func_name):
DATA_TYPE_MAPPING = { DATA_TYPE_MAPPING = {
'AutoField' : _('Integer'), 'AutoField' : _('Integer'),
'BooleanField' : _('Boolean (Either True or False)'), 'BooleanField' : _('Boolean (Either True or False)'),
'CharField' : _('String (up to %(maxlength)s)'), 'CharField' : _('String (up to %(max_length)s)'),
'CommaSeparatedIntegerField': _('Comma-separated integers'), 'CommaSeparatedIntegerField': _('Comma-separated integers'),
'DateField' : _('Date (without time)'), 'DateField' : _('Date (without time)'),
'DateTimeField' : _('Date (with time)'), 'DateTimeField' : _('Date (with time)'),
@ -310,7 +310,7 @@ DATA_TYPE_MAPPING = {
'PhoneNumberField' : _('Phone number'), 'PhoneNumberField' : _('Phone number'),
'PositiveIntegerField' : _('Integer'), 'PositiveIntegerField' : _('Integer'),
'PositiveSmallIntegerField' : _('Integer'), 'PositiveSmallIntegerField' : _('Integer'),
'SlugField' : _('String (up to %(maxlength)s)'), 'SlugField' : _('String (up to %(max_length)s)'),
'SmallIntegerField' : _('Integer'), 'SmallIntegerField' : _('Integer'),
'TextField' : _('Text'), 'TextField' : _('Text'),
'TimeField' : _('Time'), 'TimeField' : _('Time'),

View File

@ -10,10 +10,10 @@ class UserCreationForm(oldforms.Manipulator):
"A form that creates a user, with no privileges, from the given username and password." "A form that creates a user, with no privileges, from the given username and password."
def __init__(self): def __init__(self):
self.fields = ( self.fields = (
oldforms.TextField(field_name='username', length=30, maxlength=30, is_required=True, oldforms.TextField(field_name='username', length=30, max_length=30, is_required=True,
validator_list=[validators.isAlphaNumeric, self.isValidUsername]), validator_list=[validators.isAlphaNumeric, self.isValidUsername]),
oldforms.PasswordField(field_name='password1', length=30, maxlength=60, is_required=True), oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True),
oldforms.PasswordField(field_name='password2', length=30, maxlength=60, is_required=True, oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True,
validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]), validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
) )
@ -42,9 +42,9 @@ class AuthenticationForm(oldforms.Manipulator):
""" """
self.request = request self.request = request
self.fields = [ self.fields = [
oldforms.TextField(field_name="username", length=15, maxlength=30, is_required=True, oldforms.TextField(field_name="username", length=15, max_length=30, is_required=True,
validator_list=[self.isValidUser, self.hasCookiesEnabled]), validator_list=[self.isValidUser, self.hasCookiesEnabled]),
oldforms.PasswordField(field_name="password", length=15, maxlength=30, is_required=True), oldforms.PasswordField(field_name="password", length=15, max_length=30, is_required=True),
] ]
self.user_cache = None self.user_cache = None
@ -111,11 +111,11 @@ class PasswordChangeForm(oldforms.Manipulator):
def __init__(self, user): def __init__(self, user):
self.user = user self.user = user
self.fields = ( self.fields = (
oldforms.PasswordField(field_name="old_password", length=30, maxlength=30, is_required=True, oldforms.PasswordField(field_name="old_password", length=30, max_length=30, is_required=True,
validator_list=[self.isValidOldPassword]), validator_list=[self.isValidOldPassword]),
oldforms.PasswordField(field_name="new_password1", length=30, maxlength=30, is_required=True, oldforms.PasswordField(field_name="new_password1", length=30, max_length=30, is_required=True,
validator_list=[validators.AlwaysMatchesOtherField('new_password2', _("The two 'new password' fields didn't match."))]), validator_list=[validators.AlwaysMatchesOtherField('new_password2', _("The two 'new password' fields didn't match."))]),
oldforms.PasswordField(field_name="new_password2", length=30, maxlength=30, is_required=True), oldforms.PasswordField(field_name="new_password2", length=30, max_length=30, is_required=True),
) )
def isValidOldPassword(self, new_data, all_data): def isValidOldPassword(self, new_data, all_data):
@ -133,8 +133,8 @@ class AdminPasswordChangeForm(oldforms.Manipulator):
def __init__(self, user): def __init__(self, user):
self.user = user self.user = user
self.fields = ( self.fields = (
oldforms.PasswordField(field_name='password1', length=30, maxlength=60, is_required=True), oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True),
oldforms.PasswordField(field_name='password2', length=30, maxlength=60, is_required=True, oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True,
validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]), validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
) )

View File

@ -50,9 +50,9 @@ class Permission(models.Model):
Three basic permissions -- add, change and delete -- are automatically created for each Django model. Three basic permissions -- add, change and delete -- are automatically created for each Django model.
""" """
name = models.CharField(_('name'), maxlength=50) name = models.CharField(_('name'), max_length=50)
content_type = models.ForeignKey(ContentType) content_type = models.ForeignKey(ContentType)
codename = models.CharField(_('codename'), maxlength=100) codename = models.CharField(_('codename'), max_length=100)
class Meta: class Meta:
verbose_name = _('permission') verbose_name = _('permission')
@ -70,7 +70,7 @@ class Group(models.Model):
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. 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.
""" """
name = models.CharField(_('name'), maxlength=80, unique=True) name = models.CharField(_('name'), max_length=80, unique=True)
permissions = models.ManyToManyField(Permission, verbose_name=_('permissions'), blank=True, filter_interface=models.HORIZONTAL) permissions = models.ManyToManyField(Permission, verbose_name=_('permissions'), blank=True, filter_interface=models.HORIZONTAL)
class Meta: class Meta:
@ -108,11 +108,11 @@ class User(models.Model):
Username and password are required. Other fields are optional. Username and password are required. Other fields are optional.
""" """
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).")) 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)."))
first_name = models.CharField(_('first name'), maxlength=30, blank=True) first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), maxlength=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True)
email = models.EmailField(_('e-mail address'), blank=True) email = models.EmailField(_('e-mail address'), blank=True)
password = models.CharField(_('password'), maxlength=128, help_text=_("Use '[algo]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>.")) password = models.CharField(_('password'), max_length=128, help_text=_("Use '[algo]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>."))
is_staff = models.BooleanField(_('staff status'), default=False, help_text=_("Designates whether the user can log into this admin site.")) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_("Designates whether the user can log into this admin site."))
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.")) 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."))
is_superuser = models.BooleanField(_('superuser status'), default=False, help_text=_("Designates that this user has all permissions without explicitly assigning them.")) is_superuser = models.BooleanField(_('superuser status'), default=False, help_text=_("Designates that this user has all permissions without explicitly assigning them."))

View File

@ -65,8 +65,8 @@ class Comment(models.Model):
user = models.ForeignKey(User, raw_id_admin=True) user = models.ForeignKey(User, raw_id_admin=True)
content_type = models.ForeignKey(ContentType) content_type = models.ForeignKey(ContentType)
object_id = models.IntegerField(_('object ID')) object_id = models.IntegerField(_('object ID'))
headline = models.CharField(_('headline'), maxlength=255, blank=True) headline = models.CharField(_('headline'), max_length=255, blank=True)
comment = models.TextField(_('comment'), maxlength=3000) comment = models.TextField(_('comment'), max_length=3000)
rating1 = models.PositiveSmallIntegerField(_('rating #1'), blank=True, null=True) rating1 = models.PositiveSmallIntegerField(_('rating #1'), blank=True, null=True)
rating2 = models.PositiveSmallIntegerField(_('rating #2'), blank=True, null=True) rating2 = models.PositiveSmallIntegerField(_('rating #2'), blank=True, null=True)
rating3 = models.PositiveSmallIntegerField(_('rating #3'), blank=True, null=True) rating3 = models.PositiveSmallIntegerField(_('rating #3'), blank=True, null=True)
@ -164,8 +164,8 @@ class FreeComment(models.Model):
# A FreeComment is a comment by a non-registered user. # A FreeComment is a comment by a non-registered user.
content_type = models.ForeignKey(ContentType) content_type = models.ForeignKey(ContentType)
object_id = models.IntegerField(_('object ID')) object_id = models.IntegerField(_('object ID'))
comment = models.TextField(_('comment'), maxlength=3000) comment = models.TextField(_('comment'), max_length=3000)
person_name = models.CharField(_("person's name"), maxlength=50) person_name = models.CharField(_("person's name"), max_length=50)
submit_date = models.DateTimeField(_('date/time submitted'), auto_now_add=True) submit_date = models.DateTimeField(_('date/time submitted'), auto_now_add=True)
is_public = models.BooleanField(_('is public')) is_public = models.BooleanField(_('is public'))
ip_address = models.IPAddressField(_('ip address')) ip_address = models.IPAddressField(_('ip address'))

View File

@ -29,7 +29,7 @@ class PublicCommentManipulator(AuthenticationForm):
else: else:
return [] return []
self.fields.extend([ self.fields.extend([
oldforms.LargeTextField(field_name="comment", maxlength=3000, is_required=True, oldforms.LargeTextField(field_name="comment", max_length=3000, is_required=True,
validator_list=[self.hasNoProfanities]), validator_list=[self.hasNoProfanities]),
oldforms.RadioSelectField(field_name="rating1", choices=choices, oldforms.RadioSelectField(field_name="rating1", choices=choices,
is_required=ratings_required and num_rating_choices > 0, is_required=ratings_required and num_rating_choices > 0,
@ -122,9 +122,9 @@ class PublicFreeCommentManipulator(oldforms.Manipulator):
"Manipulator that handles public free (unregistered) comments" "Manipulator that handles public free (unregistered) comments"
def __init__(self): def __init__(self):
self.fields = ( self.fields = (
oldforms.TextField(field_name="person_name", maxlength=50, is_required=True, oldforms.TextField(field_name="person_name", max_length=50, is_required=True,
validator_list=[self.hasNoProfanities]), validator_list=[self.hasNoProfanities]),
oldforms.LargeTextField(field_name="comment", maxlength=3000, is_required=True, oldforms.LargeTextField(field_name="comment", max_length=3000, is_required=True,
validator_list=[self.hasNoProfanities]), validator_list=[self.hasNoProfanities]),
) )

View File

@ -32,9 +32,9 @@ class ContentTypeManager(models.Manager):
CONTENT_TYPE_CACHE = {} CONTENT_TYPE_CACHE = {}
class ContentType(models.Model): class ContentType(models.Model):
name = models.CharField(maxlength=100) name = models.CharField(max_length=100)
app_label = models.CharField(maxlength=100) app_label = models.CharField(max_length=100)
model = models.CharField(_('python model class name'), maxlength=100) model = models.CharField(_('python model class name'), max_length=100)
objects = ContentTypeManager() objects = ContentTypeManager()
class Meta: class Meta:
verbose_name = _('content type') verbose_name = _('content type')

View File

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

View File

@ -4,9 +4,9 @@ from django.utils.translation import ugettext_lazy as _
class Redirect(models.Model): class Redirect(models.Model):
site = models.ForeignKey(Site, radio_admin=models.VERTICAL) site = models.ForeignKey(Site, radio_admin=models.VERTICAL)
old_path = models.CharField(_('redirect from'), maxlength=200, db_index=True, old_path = models.CharField(_('redirect from'), max_length=200, db_index=True,
help_text=_("This should be an absolute path, excluding the domain name. Example: '/events/search/'.")) help_text=_("This should be an absolute path, excluding the domain name. Example: '/events/search/'."))
new_path = models.CharField(_('redirect to'), maxlength=200, blank=True, new_path = models.CharField(_('redirect to'), max_length=200, blank=True,
help_text=_("This can be either an absolute path (as above) or a full URL starting with 'http://'.")) help_text=_("This can be either an absolute path (as above) or a full URL starting with 'http://'."))
class Meta: class Meta:

View File

@ -65,7 +65,7 @@ class Session(models.Model):
the sessions documentation that is shipped with Django (also available the sessions documentation that is shipped with Django (also available
on the Django website). on the Django website).
""" """
session_key = models.CharField(_('session key'), maxlength=40, primary_key=True) session_key = models.CharField(_('session key'), max_length=40, primary_key=True)
session_data = models.TextField(_('session data')) session_data = models.TextField(_('session data'))
expire_date = models.DateTimeField(_('expire date')) expire_date = models.DateTimeField(_('expire date'))
objects = SessionManager() objects = SessionManager()

View File

@ -12,8 +12,8 @@ class SiteManager(models.Manager):
return self.get(pk=sid) return self.get(pk=sid)
class Site(models.Model): class Site(models.Model):
domain = models.CharField(_('domain name'), maxlength=100) domain = models.CharField(_('domain name'), max_length=100)
name = models.CharField(_('display name'), maxlength=50) name = models.CharField(_('display name'), max_length=50)
objects = SiteManager() objects = SiteManager()
class Meta: class Meta:
db_table = 'django_site' db_table = 'django_site'

View File

@ -910,9 +910,9 @@ def inspectdb():
field_type, new_params = field_type field_type, new_params = field_type
extra_params.update(new_params) extra_params.update(new_params)
# Add maxlength for all CharFields. # Add max_length for all CharFields.
if field_type == 'CharField' and row[3]: if field_type == 'CharField' and row[3]:
extra_params['maxlength'] = row[3] extra_params['max_length'] = row[3]
if field_type == 'DecimalField': if field_type == 'DecimalField':
extra_params['max_digits'] = row[4] extra_params['max_digits'] = row[4]
@ -987,8 +987,8 @@ def get_validation_errors(outfile, app=None):
for f in opts.fields: for f in opts.fields:
if f.name == 'id' and not f.primary_key and opts.pk.name == 'id': if f.name == 'id' and not f.primary_key and opts.pk.name == 'id':
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) 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)
if isinstance(f, models.CharField) and f.maxlength in (None, 0): if isinstance(f, models.CharField) and f.max_length in (None, 0):
e.add(opts, '"%s": CharFields require a "maxlength" attribute.' % f.name) e.add(opts, '"%s": CharFields require a "max_length" attribute.' % f.name)
if isinstance(f, models.DecimalField): if isinstance(f, models.DecimalField):
if f.decimal_places is None: if f.decimal_places is None:
e.add(opts, '"%s": DecimalFields require a "decimal_places" attribute.' % f.name) e.add(opts, '"%s": DecimalFields require a "decimal_places" attribute.' % f.name)
@ -1013,11 +1013,11 @@ def get_validation_errors(outfile, app=None):
if f.db_index not in (None, True, False): if f.db_index not in (None, True, False):
e.add(opts, '"%s": "db_index" should be either None, True or False.' % f.name) e.add(opts, '"%s": "db_index" should be either None, True or False.' % f.name)
# Check that maxlength <= 255 if using older MySQL versions. # Check that max_length <= 255 if using older MySQL versions.
if settings.DATABASE_ENGINE == 'mysql': if settings.DATABASE_ENGINE == 'mysql':
db_version = connection.get_server_version() db_version = connection.get_server_version()
if db_version < (5, 0, 3) and isinstance(f, (models.CharField, models.CommaSeparatedIntegerField, models.SlugField)) and f.maxlength > 255: if db_version < (5, 0, 3) and isinstance(f, (models.CharField, models.CommaSeparatedIntegerField, models.SlugField)) and f.max_length > 255:
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]]))) 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]])))
# Check to see if the related field will clash with any # Check to see if the related field will clash with any
# existing fields, m2m fields, m2m related objects or related objects # existing fields, m2m fields, m2m related objects or related objects
@ -1252,7 +1252,7 @@ def createcachetable(tablename):
from django.db import backend, connection, transaction, models from django.db import backend, connection, transaction, models
fields = ( fields = (
# "key" is a reserved word in MySQL, so use "cache_key" instead. # "key" is a reserved word in MySQL, so use "cache_key" instead.
models.CharField(name='cache_key', maxlength=255, unique=True, primary_key=True), models.CharField(name='cache_key', max_length=255, unique=True, primary_key=True),
models.TextField(name='value'), models.TextField(name='value'),
models.DateTimeField(name='expires', db_index=True), models.DateTimeField(name='expires', db_index=True),
) )

View File

@ -1,8 +1,8 @@
DATA_TYPES = { DATA_TYPES = {
'AutoField': 'int IDENTITY (1, 1)', 'AutoField': 'int IDENTITY (1, 1)',
'BooleanField': 'bit', 'BooleanField': 'bit',
'CharField': 'varchar(%(maxlength)s)', 'CharField': 'varchar(%(max_length)s)',
'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)', 'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
'DateField': 'smalldatetime', 'DateField': 'smalldatetime',
'DateTimeField': 'smalldatetime', 'DateTimeField': 'smalldatetime',
'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)', 'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
@ -17,7 +17,7 @@ DATA_TYPES = {
'PhoneNumberField': 'varchar(20)', 'PhoneNumberField': 'varchar(20)',
'PositiveIntegerField': 'int CONSTRAINT [CK_int_pos_%(column)s] CHECK ([%(column)s] > 0)', 'PositiveIntegerField': 'int CONSTRAINT [CK_int_pos_%(column)s] CHECK ([%(column)s] > 0)',
'PositiveSmallIntegerField': 'smallint CONSTRAINT [CK_smallint_pos_%(column)s] CHECK ([%(column)s] > 0)', 'PositiveSmallIntegerField': 'smallint CONSTRAINT [CK_smallint_pos_%(column)s] CHECK ([%(column)s] > 0)',
'SlugField': 'varchar(%(maxlength)s)', 'SlugField': 'varchar(%(max_length)s)',
'SmallIntegerField': 'smallint', 'SmallIntegerField': 'smallint',
'TextField': 'text', 'TextField': 'text',
'TimeField': 'time', 'TimeField': 'time',

View File

@ -5,8 +5,8 @@
DATA_TYPES = { DATA_TYPES = {
'AutoField': 'integer AUTO_INCREMENT', 'AutoField': 'integer AUTO_INCREMENT',
'BooleanField': 'bool', 'BooleanField': 'bool',
'CharField': 'varchar(%(maxlength)s)', 'CharField': 'varchar(%(max_length)s)',
'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)', 'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
'DateField': 'date', 'DateField': 'date',
'DateTimeField': 'datetime', 'DateTimeField': 'datetime',
'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)', 'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
@ -21,7 +21,7 @@ DATA_TYPES = {
'PhoneNumberField': 'varchar(20)', 'PhoneNumberField': 'varchar(20)',
'PositiveIntegerField': 'integer UNSIGNED', 'PositiveIntegerField': 'integer UNSIGNED',
'PositiveSmallIntegerField': 'smallint UNSIGNED', 'PositiveSmallIntegerField': 'smallint UNSIGNED',
'SlugField': 'varchar(%(maxlength)s)', 'SlugField': 'varchar(%(max_length)s)',
'SmallIntegerField': 'smallint', 'SmallIntegerField': 'smallint',
'TextField': 'longtext', 'TextField': 'longtext',
'TimeField': 'time', 'TimeField': 'time',

View File

@ -5,8 +5,8 @@
DATA_TYPES = { DATA_TYPES = {
'AutoField': 'integer AUTO_INCREMENT', 'AutoField': 'integer AUTO_INCREMENT',
'BooleanField': 'bool', 'BooleanField': 'bool',
'CharField': 'varchar(%(maxlength)s)', 'CharField': 'varchar(%(max_length)s)',
'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)', 'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
'DateField': 'date', 'DateField': 'date',
'DateTimeField': 'datetime', 'DateTimeField': 'datetime',
'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)', 'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
@ -21,7 +21,7 @@ DATA_TYPES = {
'PhoneNumberField': 'varchar(20)', 'PhoneNumberField': 'varchar(20)',
'PositiveIntegerField': 'integer UNSIGNED', 'PositiveIntegerField': 'integer UNSIGNED',
'PositiveSmallIntegerField': 'smallint UNSIGNED', 'PositiveSmallIntegerField': 'smallint UNSIGNED',
'SlugField': 'varchar(%(maxlength)s)', 'SlugField': 'varchar(%(max_length)s)',
'SmallIntegerField': 'smallint', 'SmallIntegerField': 'smallint',
'TextField': 'longtext', 'TextField': 'longtext',
'TimeField': 'time', 'TimeField': 'time',

View File

@ -8,8 +8,8 @@ from django.core import management
DATA_TYPES = { DATA_TYPES = {
'AutoField': 'NUMBER(11)', 'AutoField': 'NUMBER(11)',
'BooleanField': 'NUMBER(1) CHECK (%(column)s IN (0,1))', 'BooleanField': 'NUMBER(1) CHECK (%(column)s IN (0,1))',
'CharField': 'NVARCHAR2(%(maxlength)s)', 'CharField': 'NVARCHAR2(%(max_length)s)',
'CommaSeparatedIntegerField': 'VARCHAR2(%(maxlength)s)', 'CommaSeparatedIntegerField': 'VARCHAR2(%(max_length)s)',
'DateField': 'DATE', 'DateField': 'DATE',
'DateTimeField': 'TIMESTAMP', 'DateTimeField': 'TIMESTAMP',
'DecimalField': 'NUMBER(%(max_digits)s, %(decimal_places)s)', 'DecimalField': 'NUMBER(%(max_digits)s, %(decimal_places)s)',

View File

@ -5,8 +5,8 @@
DATA_TYPES = { DATA_TYPES = {
'AutoField': 'serial', 'AutoField': 'serial',
'BooleanField': 'boolean', 'BooleanField': 'boolean',
'CharField': 'varchar(%(maxlength)s)', 'CharField': 'varchar(%(max_length)s)',
'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)', 'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
'DateField': 'date', 'DateField': 'date',
'DateTimeField': 'timestamp with time zone', 'DateTimeField': 'timestamp with time zone',
'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)', 'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
@ -21,7 +21,7 @@ DATA_TYPES = {
'PhoneNumberField': 'varchar(20)', 'PhoneNumberField': 'varchar(20)',
'PositiveIntegerField': 'integer CHECK ("%(column)s" >= 0)', 'PositiveIntegerField': 'integer CHECK ("%(column)s" >= 0)',
'PositiveSmallIntegerField': 'smallint CHECK ("%(column)s" >= 0)', 'PositiveSmallIntegerField': 'smallint CHECK ("%(column)s" >= 0)',
'SlugField': 'varchar(%(maxlength)s)', 'SlugField': 'varchar(%(max_length)s)',
'SmallIntegerField': 'smallint', 'SmallIntegerField': 'smallint',
'TextField': 'text', 'TextField': 'text',
'TimeField': 'time', 'TimeField': 'time',

View File

@ -4,8 +4,8 @@
DATA_TYPES = { DATA_TYPES = {
'AutoField': 'integer', 'AutoField': 'integer',
'BooleanField': 'bool', 'BooleanField': 'bool',
'CharField': 'varchar(%(maxlength)s)', 'CharField': 'varchar(%(max_length)s)',
'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)', 'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
'DateField': 'date', 'DateField': 'date',
'DateTimeField': 'datetime', 'DateTimeField': 'datetime',
'DecimalField': 'decimal', 'DecimalField': 'decimal',
@ -20,7 +20,7 @@ DATA_TYPES = {
'PhoneNumberField': 'varchar(20)', 'PhoneNumberField': 'varchar(20)',
'PositiveIntegerField': 'integer unsigned', 'PositiveIntegerField': 'integer unsigned',
'PositiveSmallIntegerField': 'smallint unsigned', 'PositiveSmallIntegerField': 'smallint unsigned',
'SlugField': 'varchar(%(maxlength)s)', 'SlugField': 'varchar(%(max_length)s)',
'SmallIntegerField': 'smallint', 'SmallIntegerField': 'smallint',
'TextField': 'text', 'TextField': 'text',
'TimeField': 'time', 'TimeField': 'time',

View File

@ -81,7 +81,7 @@ class FlexibleFieldLookupDict:
import re import re
m = re.search(r'^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$', key) m = re.search(r'^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$', key)
if m: if m:
return ('CharField', {'maxlength': int(m.group(1))}) return ('CharField', {'max_length': int(m.group(1))})
raise KeyError raise KeyError
DATA_TYPES_REVERSE = FlexibleFieldLookupDict() DATA_TYPES_REVERSE = FlexibleFieldLookupDict()

View File

@ -11,6 +11,7 @@ from django.utils.itercompat import tee
from django.utils.text import capfirst from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy, ugettext as _ from django.utils.translation import ugettext_lazy, ugettext as _
from django.utils.encoding import smart_unicode, force_unicode, smart_str from django.utils.encoding import smart_unicode, force_unicode, smart_str
from django.utils.maxlength import LegacyMaxlength
import datetime, os, time import datetime, os, time
try: try:
import decimal import decimal
@ -63,6 +64,9 @@ def manipulator_validator_unique(f, opts, self, field_data, all_data):
# getattr(obj, opts.pk.attname) # getattr(obj, opts.pk.attname)
class Field(object): class Field(object):
# Provide backwards compatibility for the maxlength attribute and
# argument for this class and all subclasses.
__metaclass__ = LegacyMaxlength
# Designates whether empty strings fundamentally are allowed at the # Designates whether empty strings fundamentally are allowed at the
# database level. # database level.
@ -72,7 +76,7 @@ class Field(object):
creation_counter = 0 creation_counter = 0
def __init__(self, verbose_name=None, name=None, primary_key=False, def __init__(self, verbose_name=None, name=None, primary_key=False,
maxlength=None, unique=False, blank=False, null=False, db_index=False, max_length=None, unique=False, blank=False, null=False, db_index=False,
core=False, rel=None, default=NOT_PROVIDED, editable=True, serialize=True, core=False, rel=None, default=NOT_PROVIDED, editable=True, serialize=True,
prepopulate_from=None, unique_for_date=None, unique_for_month=None, prepopulate_from=None, unique_for_date=None, unique_for_month=None,
unique_for_year=None, validator_list=None, choices=None, radio_admin=None, unique_for_year=None, validator_list=None, choices=None, radio_admin=None,
@ -80,7 +84,7 @@ class Field(object):
self.name = name self.name = name
self.verbose_name = verbose_name self.verbose_name = verbose_name
self.primary_key = primary_key self.primary_key = primary_key
self.maxlength, self.unique = maxlength, unique self.max_length, self.unique = max_length, unique
self.blank, self.null = blank, null self.blank, self.null = blank, null
# Oracle treats the empty string ('') as null, so coerce the null # Oracle treats the empty string ('') as null, so coerce the null
# option whenever '' is a possible value. # option whenever '' is a possible value.
@ -244,8 +248,8 @@ class Field(object):
def prepare_field_objs_and_params(self, manipulator, name_prefix): def prepare_field_objs_and_params(self, manipulator, name_prefix):
params = {'validator_list': self.validator_list[:]} params = {'validator_list': self.validator_list[:]}
if self.maxlength and not self.choices: # Don't give SelectFields a maxlength parameter. if self.max_length and not self.choices: # Don't give SelectFields a max_length parameter.
params['maxlength'] = self.maxlength params['max_length'] = self.max_length
if self.choices: if self.choices:
if self.radio_admin: if self.radio_admin:
@ -461,7 +465,7 @@ class CharField(Field):
return smart_unicode(value) return smart_unicode(value)
def formfield(self, **kwargs): def formfield(self, **kwargs):
defaults = {'max_length': self.maxlength} defaults = {'max_length': self.max_length}
defaults.update(kwargs) defaults.update(kwargs)
return super(CharField, self).formfield(**defaults) return super(CharField, self).formfield(**defaults)
@ -670,7 +674,7 @@ class DecimalField(Field):
class EmailField(CharField): class EmailField(CharField):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
kwargs['maxlength'] = 75 kwargs['max_length'] = 75
CharField.__init__(self, *args, **kwargs) CharField.__init__(self, *args, **kwargs)
def get_internal_type(self): def get_internal_type(self):
@ -829,7 +833,7 @@ class IntegerField(Field):
class IPAddressField(Field): class IPAddressField(Field):
empty_strings_allowed = False empty_strings_allowed = False
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
kwargs['maxlength'] = 15 kwargs['max_length'] = 15
Field.__init__(self, *args, **kwargs) Field.__init__(self, *args, **kwargs)
def get_manipulator_field_objs(self): def get_manipulator_field_objs(self):
@ -877,7 +881,7 @@ class PositiveSmallIntegerField(IntegerField):
class SlugField(Field): class SlugField(Field):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
kwargs['maxlength'] = kwargs.get('maxlength', 50) kwargs['max_length'] = kwargs.get('max_length', 50)
kwargs.setdefault('validator_list', []).append(validators.isSlug) kwargs.setdefault('validator_list', []).append(validators.isSlug)
# Set db_index=True unless it's been set manually. # Set db_index=True unless it's been set manually.
if 'db_index' not in kwargs: if 'db_index' not in kwargs:
@ -963,7 +967,7 @@ class TimeField(Field):
class URLField(CharField): class URLField(CharField):
def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs): def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs):
kwargs['maxlength'] = kwargs.get('maxlength', 200) kwargs['max_length'] = kwargs.get('max_length', 200)
if verify_exists: if verify_exists:
kwargs.setdefault('validator_list', []).append(validators.isExistingURL) kwargs.setdefault('validator_list', []).append(validators.isExistingURL)
self.verify_exists = verify_exists self.verify_exists = verify_exists

View File

@ -120,6 +120,7 @@ class CharField(Field):
def widget_attrs(self, widget): def widget_attrs(self, widget):
if self.max_length is not None and isinstance(widget, (TextInput, PasswordInput)): if self.max_length is not None and isinstance(widget, (TextInput, PasswordInput)):
# The HTML attribute is maxlength, not max_length.
return {'maxlength': str(self.max_length)} return {'maxlength': str(self.max_length)}
class IntegerField(Field): class IntegerField(Field):

View File

@ -4,6 +4,7 @@ from django.utils.html import escape
from django.conf import settings from django.conf import settings
from django.utils.translation import ugettext, ungettext from django.utils.translation import ugettext, ungettext
from django.utils.encoding import smart_unicode, force_unicode from django.utils.encoding import smart_unicode, force_unicode
from django.utils.maxlength import LegacyMaxlength
FORM_FIELD_ID_PREFIX = 'id_' FORM_FIELD_ID_PREFIX = 'id_'
@ -302,6 +303,9 @@ class FormField(object):
Subclasses should also implement a render(data) method, which is responsible Subclasses should also implement a render(data) method, which is responsible
for rending the form field in XHTML. for rending the form field in XHTML.
""" """
# Provide backwards compatibility for the maxlength attribute and
# argument for this class and all subclasses.
__metaclass__ = LegacyMaxlength
def __str__(self): def __str__(self):
return unicode(self).encode('utf-8') return unicode(self).encode('utf-8')
@ -390,19 +394,19 @@ class FormField(object):
class TextField(FormField): class TextField(FormField):
input_type = "text" input_type = "text"
def __init__(self, field_name, length=30, maxlength=None, is_required=False, validator_list=None, member_name=None): def __init__(self, field_name, length=30, max_length=None, is_required=False, validator_list=None, member_name=None):
if validator_list is None: validator_list = [] if validator_list is None: validator_list = []
self.field_name = field_name self.field_name = field_name
self.length, self.maxlength = length, maxlength self.length, self.max_length = length, max_length
self.is_required = is_required self.is_required = is_required
self.validator_list = [self.isValidLength, self.hasNoNewlines] + validator_list self.validator_list = [self.isValidLength, self.hasNoNewlines] + validator_list
if member_name != None: if member_name != None:
self.member_name = member_name self.member_name = member_name
def isValidLength(self, data, form): def isValidLength(self, data, form):
if data and self.maxlength and len(smart_unicode(data)) > self.maxlength: if data and self.max_length and len(smart_unicode(data)) > self.max_length:
raise validators.ValidationError, ungettext("Ensure your text is less than %s character.", raise validators.ValidationError, ungettext("Ensure your text is less than %s character.",
"Ensure your text is less than %s characters.", self.maxlength) % self.maxlength "Ensure your text is less than %s characters.", self.max_length) % self.max_length
def hasNoNewlines(self, data, form): def hasNoNewlines(self, data, form):
if data and '\n' in data: if data and '\n' in data:
@ -411,12 +415,12 @@ class TextField(FormField):
def render(self, data): def render(self, data):
if data is None: if data is None:
data = u'' data = u''
maxlength = u'' max_length = u''
if self.maxlength: if self.max_length:
maxlength = u'maxlength="%s" ' % self.maxlength max_length = u'maxlength="%s" ' % self.max_length
return u'<input type="%s" id="%s" class="v%s%s" name="%s" size="%s" value="%s" %s/>' % \ return u'<input type="%s" id="%s" class="v%s%s" name="%s" size="%s" value="%s" %s/>' % \
(self.input_type, self.get_id(), self.__class__.__name__, self.is_required and u' required' or '', (self.input_type, self.get_id(), self.__class__.__name__, self.is_required and u' required' or '',
self.field_name, self.length, escape(data), maxlength) self.field_name, self.length, escape(data), max_length)
def html2python(data): def html2python(data):
return data return data
@ -426,14 +430,14 @@ class PasswordField(TextField):
input_type = "password" input_type = "password"
class LargeTextField(TextField): class LargeTextField(TextField):
def __init__(self, field_name, rows=10, cols=40, is_required=False, validator_list=None, maxlength=None): def __init__(self, field_name, rows=10, cols=40, is_required=False, validator_list=None, max_length=None):
if validator_list is None: validator_list = [] if validator_list is None: validator_list = []
self.field_name = field_name self.field_name = field_name
self.rows, self.cols, self.is_required = rows, cols, is_required self.rows, self.cols, self.is_required = rows, cols, is_required
self.validator_list = validator_list[:] self.validator_list = validator_list[:]
if maxlength: if max_length:
self.validator_list.append(self.isValidLength) self.validator_list.append(self.isValidLength)
self.maxlength = maxlength self.max_length = max_length
def render(self, data): def render(self, data):
if data is None: if data is None:
@ -710,12 +714,12 @@ class ImageUploadField(FileUploadField):
#################### ####################
class IntegerField(TextField): class IntegerField(TextField):
def __init__(self, field_name, length=10, maxlength=None, is_required=False, validator_list=None, member_name=None): def __init__(self, field_name, length=10, max_length=None, is_required=False, validator_list=None, member_name=None):
if validator_list is None: validator_list = [] if validator_list is None: validator_list = []
validator_list = [self.isInteger] + validator_list validator_list = [self.isInteger] + validator_list
if member_name is not None: if member_name is not None:
self.member_name = member_name self.member_name = member_name
TextField.__init__(self, field_name, length, maxlength, is_required, validator_list) TextField.__init__(self, field_name, length, max_length, is_required, validator_list)
def isInteger(self, field_data, all_data): def isInteger(self, field_data, all_data):
try: try:
@ -730,30 +734,30 @@ class IntegerField(TextField):
html2python = staticmethod(html2python) html2python = staticmethod(html2python)
class SmallIntegerField(IntegerField): class SmallIntegerField(IntegerField):
def __init__(self, field_name, length=5, maxlength=5, is_required=False, validator_list=None): def __init__(self, field_name, length=5, max_length=5, is_required=False, validator_list=None):
if validator_list is None: validator_list = [] if validator_list is None: validator_list = []
validator_list = [self.isSmallInteger] + validator_list validator_list = [self.isSmallInteger] + validator_list
IntegerField.__init__(self, field_name, length, maxlength, is_required, validator_list) IntegerField.__init__(self, field_name, length, max_length, is_required, validator_list)
def isSmallInteger(self, field_data, all_data): def isSmallInteger(self, field_data, all_data):
if not -32768 <= int(field_data) <= 32767: if not -32768 <= int(field_data) <= 32767:
raise validators.CriticalValidationError, ugettext("Enter a whole number between -32,768 and 32,767.") raise validators.CriticalValidationError, ugettext("Enter a whole number between -32,768 and 32,767.")
class PositiveIntegerField(IntegerField): class PositiveIntegerField(IntegerField):
def __init__(self, field_name, length=10, maxlength=None, is_required=False, validator_list=None): def __init__(self, field_name, length=10, max_length=None, is_required=False, validator_list=None):
if validator_list is None: validator_list = [] if validator_list is None: validator_list = []
validator_list = [self.isPositive] + validator_list validator_list = [self.isPositive] + validator_list
IntegerField.__init__(self, field_name, length, maxlength, is_required, validator_list) IntegerField.__init__(self, field_name, length, max_length, is_required, validator_list)
def isPositive(self, field_data, all_data): def isPositive(self, field_data, all_data):
if int(field_data) < 0: if int(field_data) < 0:
raise validators.CriticalValidationError, ugettext("Enter a positive number.") raise validators.CriticalValidationError, ugettext("Enter a positive number.")
class PositiveSmallIntegerField(IntegerField): class PositiveSmallIntegerField(IntegerField):
def __init__(self, field_name, length=5, maxlength=None, is_required=False, validator_list=None): def __init__(self, field_name, length=5, max_length=None, is_required=False, validator_list=None):
if validator_list is None: validator_list = [] if validator_list is None: validator_list = []
validator_list = [self.isPositiveSmall] + validator_list validator_list = [self.isPositiveSmall] + validator_list
IntegerField.__init__(self, field_name, length, maxlength, is_required, validator_list) IntegerField.__init__(self, field_name, length, max_length, is_required, validator_list)
def isPositiveSmall(self, field_data, all_data): def isPositiveSmall(self, field_data, all_data):
if not 0 <= int(field_data) <= 32767: if not 0 <= int(field_data) <= 32767:
@ -806,10 +810,10 @@ class DecimalField(TextField):
class DatetimeField(TextField): class DatetimeField(TextField):
"""A FormField that automatically converts its data to a datetime.datetime object. """A FormField that automatically converts its data to a datetime.datetime object.
The data should be in the format YYYY-MM-DD HH:MM:SS.""" The data should be in the format YYYY-MM-DD HH:MM:SS."""
def __init__(self, field_name, length=30, maxlength=None, is_required=False, validator_list=None): def __init__(self, field_name, length=30, max_length=None, is_required=False, validator_list=None):
if validator_list is None: validator_list = [] if validator_list is None: validator_list = []
self.field_name = field_name self.field_name = field_name
self.length, self.maxlength = length, maxlength self.length, self.max_length = length, max_length
self.is_required = is_required self.is_required = is_required
self.validator_list = [validators.isValidANSIDatetime] + validator_list self.validator_list = [validators.isValidANSIDatetime] + validator_list
@ -836,7 +840,7 @@ class DateField(TextField):
def __init__(self, field_name, is_required=False, validator_list=None): def __init__(self, field_name, is_required=False, validator_list=None):
if validator_list is None: validator_list = [] if validator_list is None: validator_list = []
validator_list = [self.isValidDate] + validator_list validator_list = [self.isValidDate] + validator_list
TextField.__init__(self, field_name, length=10, maxlength=10, TextField.__init__(self, field_name, length=10, max_length=10,
is_required=is_required, validator_list=validator_list) is_required=is_required, validator_list=validator_list)
def isValidDate(self, field_data, all_data): def isValidDate(self, field_data, all_data):
@ -861,7 +865,7 @@ class TimeField(TextField):
def __init__(self, field_name, is_required=False, validator_list=None): def __init__(self, field_name, is_required=False, validator_list=None):
if validator_list is None: validator_list = [] if validator_list is None: validator_list = []
validator_list = [self.isValidTime] + validator_list validator_list = [self.isValidTime] + validator_list
TextField.__init__(self, field_name, length=8, maxlength=8, TextField.__init__(self, field_name, length=8, max_length=8,
is_required=is_required, validator_list=validator_list) is_required=is_required, validator_list=validator_list)
def isValidTime(self, field_data, all_data): def isValidTime(self, field_data, all_data):
@ -893,10 +897,10 @@ class TimeField(TextField):
class EmailField(TextField): class EmailField(TextField):
"A convenience FormField for validating e-mail addresses" "A convenience FormField for validating e-mail addresses"
def __init__(self, field_name, length=50, maxlength=75, is_required=False, validator_list=None): def __init__(self, field_name, length=50, max_length=75, is_required=False, validator_list=None):
if validator_list is None: validator_list = [] if validator_list is None: validator_list = []
validator_list = [self.isValidEmail] + validator_list validator_list = [self.isValidEmail] + validator_list
TextField.__init__(self, field_name, length, maxlength=maxlength, TextField.__init__(self, field_name, length, max_length=max_length,
is_required=is_required, validator_list=validator_list) is_required=is_required, validator_list=validator_list)
def isValidEmail(self, field_data, all_data): def isValidEmail(self, field_data, all_data):
@ -907,10 +911,10 @@ class EmailField(TextField):
class URLField(TextField): class URLField(TextField):
"A convenience FormField for validating URLs" "A convenience FormField for validating URLs"
def __init__(self, field_name, length=50, maxlength=200, is_required=False, validator_list=None): def __init__(self, field_name, length=50, max_length=200, is_required=False, validator_list=None):
if validator_list is None: validator_list = [] if validator_list is None: validator_list = []
validator_list = [self.isValidURL] + validator_list validator_list = [self.isValidURL] + validator_list
TextField.__init__(self, field_name, length=length, maxlength=maxlength, TextField.__init__(self, field_name, length=length, max_length=max_length,
is_required=is_required, validator_list=validator_list) is_required=is_required, validator_list=validator_list)
def isValidURL(self, field_data, all_data): def isValidURL(self, field_data, all_data):
@ -920,10 +924,10 @@ class URLField(TextField):
raise validators.CriticalValidationError, e.messages raise validators.CriticalValidationError, e.messages
class IPAddressField(TextField): class IPAddressField(TextField):
def __init__(self, field_name, length=15, maxlength=15, is_required=False, validator_list=None): def __init__(self, field_name, length=15, max_length=15, is_required=False, validator_list=None):
if validator_list is None: validator_list = [] if validator_list is None: validator_list = []
validator_list = [self.isValidIPAddress] + validator_list validator_list = [self.isValidIPAddress] + validator_list
TextField.__init__(self, field_name, length=length, maxlength=maxlength, TextField.__init__(self, field_name, length=length, max_length=max_length,
is_required=is_required, validator_list=validator_list) is_required=is_required, validator_list=validator_list)
def isValidIPAddress(self, field_data, all_data): def isValidIPAddress(self, field_data, all_data):
@ -970,7 +974,7 @@ class PhoneNumberField(TextField):
def __init__(self, field_name, is_required=False, validator_list=None): def __init__(self, field_name, is_required=False, validator_list=None):
if validator_list is None: validator_list = [] if validator_list is None: validator_list = []
validator_list = [self.isValidPhone] + validator_list validator_list = [self.isValidPhone] + validator_list
TextField.__init__(self, field_name, length=12, maxlength=12, TextField.__init__(self, field_name, length=12, max_length=12,
is_required=is_required, validator_list=validator_list) is_required=is_required, validator_list=validator_list)
def isValidPhone(self, field_data, all_data): def isValidPhone(self, field_data, all_data):
@ -984,7 +988,7 @@ class USStateField(TextField):
def __init__(self, field_name, is_required=False, validator_list=None): def __init__(self, field_name, is_required=False, validator_list=None):
if validator_list is None: validator_list = [] if validator_list is None: validator_list = []
validator_list = [self.isValidUSState] + validator_list validator_list = [self.isValidUSState] + validator_list
TextField.__init__(self, field_name, length=2, maxlength=2, TextField.__init__(self, field_name, length=2, max_length=2,
is_required=is_required, validator_list=validator_list) is_required=is_required, validator_list=validator_list)
def isValidUSState(self, field_data, all_data): def isValidUSState(self, field_data, all_data):
@ -1001,10 +1005,10 @@ class USStateField(TextField):
class CommaSeparatedIntegerField(TextField): class CommaSeparatedIntegerField(TextField):
"A convenience FormField for validating comma-separated integer fields" "A convenience FormField for validating comma-separated integer fields"
def __init__(self, field_name, maxlength=None, is_required=False, validator_list=None): def __init__(self, field_name, max_length=None, is_required=False, validator_list=None):
if validator_list is None: validator_list = [] if validator_list is None: validator_list = []
validator_list = [self.isCommaSeparatedIntegerList] + validator_list validator_list = [self.isCommaSeparatedIntegerList] + validator_list
TextField.__init__(self, field_name, length=20, maxlength=maxlength, TextField.__init__(self, field_name, length=20, max_length=max_length,
is_required=is_required, validator_list=validator_list) is_required=is_required, validator_list=validator_list)
def isCommaSeparatedIntegerList(self, field_data, all_data): def isCommaSeparatedIntegerList(self, field_data, all_data):

67
django/utils/maxlength.py Normal file
View File

@ -0,0 +1,67 @@
"""
Utilities for providing backwards compatibility for the maxlength argument,
which has been replaced by max_length, see ticket #2101.
"""
from warnings import warn
def get_maxlength(self):
return self.max_length
def set_maxlength(self, value):
self.max_length = value
def legacy_maxlength(max_length, maxlength):
"""
Consolidates max_length and maxlength, providing backwards compatibilty
for the legacy "maxlength" argument.
If one of max_length or maxlength is given, then that value is returned.
If both are given, a TypeError is raised.
If maxlength is used at all, a deprecation warning is issued.
"""
if maxlength is not None:
warn("maxlength is deprecated, use max_length instead.",
PendingDeprecationWarning,
stacklevel=3)
if max_length is not None:
raise TypeError("field can not take both the max_length"
" argument and the legacy maxlength argument.")
max_length = maxlength
return max_length
def remove_maxlength(func):
"""
A decorator to be used on a class's __init__ that provides backwards
compatibilty for the legacy "maxlength" keyword argument, i.e.
name = models.CharField(maxlength=20)
It does this by changing the passed "maxlength" keyword argument
(if it exists) into a "max_length" keyword argument.
"""
def inner(self, *args, **kwargs):
max_length = kwargs.get('max_length', None)
# pop maxlength because we don't want this going to __init__.
maxlength = kwargs.pop('maxlength', None)
max_length = legacy_maxlength(max_length, maxlength)
# Only set the max_length keyword argument if we got a value back.
if max_length is not None:
kwargs['max_length'] = max_length
func(self, *args, **kwargs)
return inner
# This metaclass is used in two places, and should be removed when legacy
# support for maxlength is dropped.
# * oldforms.FormField
# * db.models.fields.Field
class LegacyMaxlength(type):
"""
Metaclass for providing backwards compatibility support for the
"maxlength" keyword argument.
"""
def __init__(cls, name, bases, attrs):
super(LegacyMaxlength, cls).__init__(name, bases, attrs)
# Decorate the class's __init__ to remove any maxlength keyword.
cls.__init__ = remove_maxlength(cls.__init__)
# Support accessing and setting to the legacy maxlength attribute.
cls.maxlength = property(get_maxlength, set_maxlength)

View File

@ -340,14 +340,14 @@ Model style
Do this:: Do this::
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=20) first_name = models.CharField(max_length=20)
last_name = models.CharField(maxlength=40) last_name = models.CharField(max_length=40)
Don't do this:: Don't do this::
class Person(models.Model): class Person(models.Model):
FirstName = models.CharField(maxlength=20) FirstName = models.CharField(max_length=20)
Last_Name = models.CharField(maxlength=40) Last_Name = models.CharField(max_length=40)
* The ``class Meta`` should appear *after* the fields are defined, with * The ``class Meta`` should appear *after* the fields are defined, with
a single blank line separating the fields and the class definition. a single blank line separating the fields and the class definition.
@ -355,8 +355,8 @@ Model style
Do this:: Do this::
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=20) first_name = models.CharField(max_length=20)
last_name = models.CharField(maxlength=40) last_name = models.CharField(max_length=40)
class Meta: class Meta:
verbose_name_plural = 'people' verbose_name_plural = 'people'
@ -364,8 +364,8 @@ Model style
Don't do this:: Don't do this::
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=20) first_name = models.CharField(max_length=20)
last_name = models.CharField(maxlength=40) last_name = models.CharField(max_length=40)
class Meta: class Meta:
verbose_name_plural = 'people' verbose_name_plural = 'people'
@ -375,8 +375,8 @@ Model style
class Meta: class Meta:
verbose_name_plural = 'people' verbose_name_plural = 'people'
first_name = models.CharField(maxlength=20) first_name = models.CharField(max_length=20)
last_name = models.CharField(maxlength=40) last_name = models.CharField(max_length=40)
* The order of model inner classes and standard methods should be as * The order of model inner classes and standard methods should be as
follows (noting that these are not all required): follows (noting that these are not all required):

View File

@ -12,14 +12,14 @@ Throughout this reference, we'll refer to the following models, which comprise
a weblog application:: a weblog application::
class Blog(models.Model): class Blog(models.Model):
name = models.CharField(maxlength=100) name = models.CharField(max_length=100)
tagline = models.TextField() tagline = models.TextField()
def __unicode__(self): def __unicode__(self):
return self.name return self.name
class Author(models.Model): class Author(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
email = models.EmailField() email = models.EmailField()
def __unicode__(self): def __unicode__(self):
@ -27,7 +27,7 @@ a weblog application::
class Entry(models.Model): class Entry(models.Model):
blog = models.ForeignKey(Blog) blog = models.ForeignKey(Blog)
headline = models.CharField(maxlength=255) headline = models.CharField(max_length=255)
body_text = models.TextField() body_text = models.TextField()
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
authors = models.ManyToManyField(Author) authors = models.ManyToManyField(Author)
@ -1806,8 +1806,8 @@ following model::
('F', 'Female'), ('F', 'Female'),
) )
class Person(models.Model): class Person(models.Model):
name = models.CharField(maxlength=20) name = models.CharField(max_length=20)
gender = models.CharField(maxlength=1, choices=GENDER_CHOICES) gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
...each ``Person`` instance will have a ``get_gender_display()`` method. Example:: ...each ``Person`` instance will have a ``get_gender_display()`` method. Example::

View File

@ -37,11 +37,11 @@ this document, we'll be working with the following model, a "place" object::
) )
class Place(models.Model): class Place(models.Model):
name = models.CharField(maxlength=100) name = models.CharField(max_length=100)
address = models.CharField(maxlength=100, blank=True) address = models.CharField(max_length=100, blank=True)
city = models.CharField(maxlength=50, blank=True) city = models.CharField(max_length=50, blank=True)
state = models.USStateField() state = models.USStateField()
zip_code = models.CharField(maxlength=5, blank=True) zip_code = models.CharField(max_length=5, blank=True)
place_type = models.IntegerField(choices=PLACE_TYPES) place_type = models.IntegerField(choices=PLACE_TYPES)
class Admin: class Admin:
@ -388,7 +388,7 @@ for a "contact" form on a website::
def __init__(self): def __init__(self):
self.fields = ( self.fields = (
forms.EmailField(field_name="from", is_required=True), forms.EmailField(field_name="from", is_required=True),
forms.TextField(field_name="subject", length=30, maxlength=200, is_required=True), forms.TextField(field_name="subject", length=30, max_length=200, is_required=True),
forms.SelectField(field_name="urgency", choices=urgency_choices), forms.SelectField(field_name="urgency", choices=urgency_choices),
forms.LargeTextField(field_name="contents", is_required=True), forms.LargeTextField(field_name="contents", is_required=True),
) )

View File

@ -33,8 +33,8 @@ This example model defines a ``Person``, which has a ``first_name`` and
from django.db import models from django.db import models
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
``first_name`` and ``last_name`` are *fields* of the model. Each field is ``first_name`` and ``last_name`` are *fields* of the model. Each field is
specified as a class attribute, and each attribute maps to a database column. specified as a class attribute, and each attribute maps to a database column.
@ -69,13 +69,13 @@ attributes.
Example:: Example::
class Musician(models.Model): class Musician(models.Model):
first_name = models.CharField(maxlength=50) first_name = models.CharField(max_length=50)
last_name = models.CharField(maxlength=50) last_name = models.CharField(max_length=50)
instrument = models.CharField(maxlength=100) instrument = models.CharField(max_length=100)
class Album(models.Model): class Album(models.Model):
artist = models.ForeignKey(Musician) artist = models.ForeignKey(Musician)
name = models.CharField(maxlength=100) name = models.CharField(max_length=100)
release_date = models.DateField() release_date = models.DateField()
num_stars = models.IntegerField() num_stars = models.IntegerField()
@ -142,14 +142,18 @@ For large amounts of text, use ``TextField``.
The admin represents this as an ``<input type="text">`` (a single-line input). The admin represents this as an ``<input type="text">`` (a single-line input).
``CharField`` has an extra required argument, ``maxlength``, the maximum length ``CharField`` has an extra required argument, ``max_length``, the maximum length
(in characters) of the field. The maxlength is enforced at the database level (in characters) of the field. The max_length is enforced at the database level
and in Django's validation. and in Django's validation.
``CommaSeparatedIntegerField`` Django veterans: Note that the argument is now called ``max_length`` to
provide consistency throughout Django. There is full legacy support for
the old ``maxlength`` argument, but ``max_length`` is prefered.
``CommaSeparatedIntegerField``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A field of integers separated by commas. As in ``CharField``, the ``maxlength`` A field of integers separated by commas. As in ``CharField``, the ``max_length``
argument is required. argument is required.
``DateField`` ``DateField``
@ -217,7 +221,7 @@ The admin represents this as an ``<input type="text">`` (a single-line input).
~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
A ``CharField`` that checks that the value is a valid e-mail address. A ``CharField`` that checks that the value is a valid e-mail address.
This doesn't accept ``maxlength``; its ``maxlength`` is automatically set to This doesn't accept ``max_length``; its ``max_length`` is automatically set to
75. 75.
``FileField`` ``FileField``
@ -400,7 +404,7 @@ Like a ``PositiveIntegerField``, but only allows values under a certain
containing only letters, numbers, underscores or hyphens. They're generally containing only letters, numbers, underscores or hyphens. They're generally
used in URLs. used in URLs.
Like a CharField, you can specify ``maxlength``. If ``maxlength`` is Like a CharField, you can specify ``max_length``. If ``max_length`` is
not specified, Django will use a default length of 50. not specified, Django will use a default length of 50.
Implies ``db_index=True``. Implies ``db_index=True``.
@ -447,9 +451,9 @@ and doesn't give a 404 response).
The admin represents this as an ``<input type="text">`` (a single-line input). The admin represents this as an ``<input type="text">`` (a single-line input).
``URLField`` takes an optional argument, ``maxlength``, the maximum length (in ``URLField`` takes an optional argument, ``max_length``, the maximum length (in
characters) of the field. The maxlength is enforced at the database level and characters) of the field. The maximum length is enforced at the database level and
in Django's validation. If you don't specify ``maxlength``, a default of 200 in Django's validation. If you don't specify ``max_length``, a default of 200
is used. is used.
``USStateField`` ``USStateField``
@ -536,7 +540,7 @@ The choices list can be defined either as part of your model class::
('M', 'Male'), ('M', 'Male'),
('F', 'Female'), ('F', 'Female'),
) )
gender = models.CharField(maxlength=1, choices=GENDER_CHOICES) gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
or outside your model class altogether:: or outside your model class altogether::
@ -545,7 +549,7 @@ or outside your model class altogether::
('F', 'Female'), ('F', 'Female'),
) )
class Foo(models.Model): class Foo(models.Model):
gender = models.CharField(maxlength=1, choices=GENDER_CHOICES) gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
For each model field that has ``choices`` set, Django will add a method to For each model field that has ``choices`` set, Django will add a method to
retrieve the human-readable name for the field's current value. See retrieve the human-readable name for the field's current value. See
@ -698,11 +702,11 @@ it using the field's attribute name, converting underscores to spaces.
In this example, the verbose name is ``"Person's first name"``:: In this example, the verbose name is ``"Person's first name"``::
first_name = models.CharField("Person's first name", maxlength=30) first_name = models.CharField("Person's first name", max_length=30)
In this example, the verbose name is ``"first name"``:: In this example, the verbose name is ``"first name"``::
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
``ForeignKey``, ``ManyToManyField`` and ``OneToOneField`` require the first ``ForeignKey``, ``ManyToManyField`` and ``OneToOneField`` require the first
argument to be a model class, so use the ``verbose_name`` keyword argument:: argument to be a model class, so use the ``verbose_name`` keyword argument::
@ -1027,8 +1031,8 @@ Once you have ``MytypeField``, you can use it in any model, just like any other
``Field`` type:: ``Field`` type::
class Person(models.Model): class Person(models.Model):
name = models.CharField(maxlength=80) name = models.CharField(max_length=80)
gender = models.CharField(maxlength=1) gender = models.CharField(max_length=1)
something_else = MytypeField() something_else = MytypeField()
If you aim to build a database-agnostic application, you should account for If you aim to build a database-agnostic application, you should account for
@ -1074,12 +1078,12 @@ time -- i.e., when the class is instantiated. To do that, just implement
# This is a much more flexible example. # This is a much more flexible example.
class BetterCharField(models.Field): class BetterCharField(models.Field):
def __init__(self, maxlength, *args, **kwargs): def __init__(self, max_length, *args, **kwargs):
self.maxlength = maxlength self.max_length = max_length
super(BetterCharField, self).__init__(*args, **kwargs) super(BetterCharField, self).__init__(*args, **kwargs)
def db_type(self): def db_type(self):
return 'char(%s)' % self.maxlength return 'char(%s)' % self.max_length
# In the model: # In the model:
class MyModel(models.Model): class MyModel(models.Model):
@ -1096,7 +1100,7 @@ Meta options
Give your model metadata by using an inner ``class Meta``, like so:: Give your model metadata by using an inner ``class Meta``, like so::
class Foo(models.Model): class Foo(models.Model):
bar = models.CharField(maxlength=30) bar = models.CharField(max_length=30)
class Meta: class Meta:
# ... # ...
@ -1270,8 +1274,8 @@ If you want your model to be visible to Django's admin site, give your model an
inner ``"class Admin"``, like so:: inner ``"class Admin"``, like so::
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
class Admin: class Admin:
# Admin options go here # Admin options go here
@ -1430,7 +1434,7 @@ A few special cases to note about ``list_display``:
Here's a full example model:: Here's a full example model::
class Person(models.Model): class Person(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
birthday = models.DateField() birthday = models.DateField()
class Admin: class Admin:
@ -1447,9 +1451,9 @@ A few special cases to note about ``list_display``:
Here's a full example model:: Here's a full example model::
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=50) first_name = models.CharField(max_length=50)
last_name = models.CharField(maxlength=50) last_name = models.CharField(max_length=50)
color_code = models.CharField(maxlength=6) color_code = models.CharField(max_length=6)
class Admin: class Admin:
list_display = ('first_name', 'last_name', 'colored_name') list_display = ('first_name', 'last_name', 'colored_name')
@ -1465,7 +1469,7 @@ A few special cases to note about ``list_display``:
Here's a full example model:: Here's a full example model::
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=50) first_name = models.CharField(max_length=50)
birthday = models.DateField() birthday = models.DateField()
class Admin: class Admin:
@ -1493,8 +1497,8 @@ A few special cases to note about ``list_display``:
For example:: For example::
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=50) first_name = models.CharField(max_length=50)
color_code = models.CharField(maxlength=6) color_code = models.CharField(max_length=6)
class Admin: class Admin:
list_display = ('first_name', 'colored_first_name') list_display = ('first_name', 'colored_first_name')
@ -1744,13 +1748,13 @@ returns a list of all ``OpinionPoll`` objects, each with an extra
return result_list return result_list
class OpinionPoll(models.Model): class OpinionPoll(models.Model):
question = models.CharField(maxlength=200) question = models.CharField(max_length=200)
poll_date = models.DateField() poll_date = models.DateField()
objects = PollManager() objects = PollManager()
class Response(models.Model): class Response(models.Model):
poll = models.ForeignKey(Poll) poll = models.ForeignKey(Poll)
person_name = models.CharField(maxlength=50) person_name = models.CharField(max_length=50)
response = models.TextField() response = models.TextField()
With this example, you'd use ``OpinionPoll.objects.with_counts()`` to return With this example, you'd use ``OpinionPoll.objects.with_counts()`` to return
@ -1766,8 +1770,8 @@ A ``Manager``'s base ``QuerySet`` returns all objects in the system. For
example, using this model:: example, using this model::
class Book(models.Model): class Book(models.Model):
title = models.CharField(maxlength=100) title = models.CharField(max_length=100)
author = models.CharField(maxlength=50) author = models.CharField(max_length=50)
...the statement ``Book.objects.all()`` will return all books in the database. ...the statement ``Book.objects.all()`` will return all books in the database.
@ -1785,8 +1789,8 @@ all objects, and one that returns only the books by Roald Dahl::
# Then hook it into the Book model explicitly. # Then hook it into the Book model explicitly.
class Book(models.Model): class Book(models.Model):
title = models.CharField(maxlength=100) title = models.CharField(max_length=100)
author = models.CharField(maxlength=50) author = models.CharField(max_length=50)
objects = models.Manager() # The default manager. objects = models.Manager() # The default manager.
dahl_objects = DahlBookManager() # The Dahl-specific manager. dahl_objects = DahlBookManager() # The Dahl-specific manager.
@ -1819,9 +1823,9 @@ For example::
return super(FemaleManager, self).get_query_set().filter(sex='F') return super(FemaleManager, self).get_query_set().filter(sex='F')
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=50) first_name = models.CharField(max_length=50)
last_name = models.CharField(maxlength=50) last_name = models.CharField(max_length=50)
sex = models.CharField(maxlength=1, choices=(('M', 'Male'), ('F', 'Female'))) sex = models.CharField(max_length=1, choices=(('M', 'Male'), ('F', 'Female')))
people = models.Manager() people = models.Manager()
men = MaleManager() men = MaleManager()
women = FemaleManager() women = FemaleManager()
@ -1851,11 +1855,11 @@ model.
For example, this model has a few custom methods:: For example, this model has a few custom methods::
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=50) first_name = models.CharField(max_length=50)
last_name = models.CharField(maxlength=50) last_name = models.CharField(max_length=50)
birth_date = models.DateField() birth_date = models.DateField()
address = models.CharField(maxlength=100) address = models.CharField(max_length=100)
city = models.CharField(maxlength=50) city = models.CharField(max_length=50)
state = models.USStateField() # Yes, this is America-centric... state = models.USStateField() # Yes, this is America-centric...
def baby_boomer_status(self): def baby_boomer_status(self):
@ -1897,8 +1901,8 @@ Although this isn't required, it's strongly encouraged (see the description of
For example:: For example::
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=50) first_name = models.CharField(max_length=50)
last_name = models.CharField(maxlength=50) last_name = models.CharField(max_length=50)
def __str__(self): def __str__(self):
# Note use of django.utils.encoding.smart_str() here because # Note use of django.utils.encoding.smart_str() here because
@ -1915,8 +1919,8 @@ method for your model. The example in the previous section could be written
more simply as:: more simply as::
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=50) first_name = models.CharField(max_length=50)
last_name = models.CharField(maxlength=50) last_name = models.CharField(max_length=50)
def __unicode__(self): def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name) return u'%s %s' % (self.first_name, self.last_name)
@ -2058,7 +2062,7 @@ A classic use-case for overriding the built-in methods is if you want something
to happen whenever you save an object. For example:: to happen whenever you save an object. For example::
class Blog(models.Model): class Blog(models.Model):
name = models.CharField(maxlength=100) name = models.CharField(max_length=100)
tagline = models.TextField() tagline = models.TextField()
def save(self): def save(self):
@ -2069,7 +2073,7 @@ to happen whenever you save an object. For example::
You can also prevent saving:: You can also prevent saving::
class Blog(models.Model): class Blog(models.Model):
name = models.CharField(maxlength=100) name = models.CharField(max_length=100)
tagline = models.TextField() tagline = models.TextField()
def save(self): def save(self):

View File

@ -1372,7 +1372,7 @@ the full list of conversions:
``AutoField`` Not represented in the form ``AutoField`` Not represented in the form
``BooleanField`` ``BooleanField`` ``BooleanField`` ``BooleanField``
``CharField`` ``CharField`` with ``max_length`` set to ``CharField`` ``CharField`` with ``max_length`` set to
the model field's ``maxlength`` the model field's ``max_length``
``CommaSeparatedIntegerField`` ``CharField`` ``CommaSeparatedIntegerField`` ``CharField``
``DateField`` ``DateField`` ``DateField`` ``DateField``
``DateTimeField`` ``DateTimeField`` ``DateTimeField`` ``DateTimeField``
@ -1452,15 +1452,15 @@ Consider this set of models::
) )
class Author(models.Model): class Author(models.Model):
name = models.CharField(maxlength=100) name = models.CharField(max_length=100)
title = models.CharField(maxlength=3, choices=TITLE_CHOICES) title = models.CharField(max_length=3, choices=TITLE_CHOICES)
birth_date = models.DateField(blank=True, null=True) birth_date = models.DateField(blank=True, null=True)
def __unicode__(self): def __unicode__(self):
return self.name return self.name
class Book(models.Model): class Book(models.Model):
name = models.CharField(maxlength=100) name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author) authors = models.ManyToManyField(Author)
With these models, a call to ``form_for_model(Author)`` would return a ``Form`` With these models, a call to ``form_for_model(Author)`` would return a ``Form``

View File

@ -25,14 +25,14 @@ far, it's been solving two years' worth of database-schema problems. Here's a
quick example:: quick example::
class Reporter(models.Model): class Reporter(models.Model):
full_name = models.CharField(maxlength=70) full_name = models.CharField(max_length=70)
def __unicode__(self): def __unicode__(self):
return self.full_name return self.full_name
class Article(models.Model): class Article(models.Model):
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
headline = models.CharField(maxlength=200) headline = models.CharField(max_length=200)
article = models.TextField() article = models.TextField()
reporter = models.ForeignKey(Reporter) reporter = models.ForeignKey(Reporter)
@ -134,7 +134,7 @@ your model classes::
class Article(models.Model): class Article(models.Model):
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
headline = models.CharField(maxlength=200) headline = models.CharField(max_length=200)
article = models.TextField() article = models.TextField()
reporter = models.ForeignKey(Reporter) reporter = models.ForeignKey(Reporter)
class Admin: pass class Admin: pass

View File

@ -46,7 +46,7 @@ that's represented by a ``ManyToManyField`` in the ``Article`` model::
from django.contrib.sites.models import Site from django.contrib.sites.models import Site
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=200) headline = models.CharField(max_length=200)
# ... # ...
sites = models.ManyToManyField(Site) sites = models.ManyToManyField(Site)
@ -87,7 +87,7 @@ like this::
from django.contrib.sites.models import Site from django.contrib.sites.models import Site
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=200) headline = models.CharField(max_length=200)
# ... # ...
site = models.ForeignKey(Site) site = models.ForeignKey(Site)
@ -229,7 +229,7 @@ Use ``CurrentSiteManager`` by adding it to your model explicitly. For example::
class Photo(models.Model): class Photo(models.Model):
photo = models.FileField(upload_to='/home/photos') photo = models.FileField(upload_to='/home/photos')
photographer_name = models.CharField(maxlength=100) photographer_name = models.CharField(max_length=100)
pub_date = models.DateField() pub_date = models.DateField()
site = models.ForeignKey(Site) site = models.ForeignKey(Site)
objects = models.Manager() objects = models.Manager()
@ -257,7 +257,7 @@ this::
class Photo(models.Model): class Photo(models.Model):
photo = models.FileField(upload_to='/home/photos') photo = models.FileField(upload_to='/home/photos')
photographer_name = models.CharField(maxlength=100) photographer_name = models.CharField(max_length=100)
pub_date = models.DateField() pub_date = models.DateField()
publish_on = models.ForeignKey(Site) publish_on = models.ForeignKey(Site)
objects = models.Manager() objects = models.Manager()

View File

@ -79,8 +79,8 @@ For example::
'The cat says "meow"' 'The cat says "meow"'
""" """
name = models.CharField(maxlength=20) name = models.CharField(max_length=20)
sound = models.CharField(maxlength=20) sound = models.CharField(max_length=20)
def speak(self): def speak(self):
return 'The %s says "%s"' % (self.name, self.sound) return 'The %s says "%s"' % (self.name, self.sound)

View File

@ -251,12 +251,12 @@ These concepts are represented by simple Python classes. Edit the
from django.db import models from django.db import models
class Poll(models.Model): class Poll(models.Model):
question = models.CharField(maxlength=200) question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published') pub_date = models.DateTimeField('date published')
class Choice(models.Model): class Choice(models.Model):
poll = models.ForeignKey(Poll) poll = models.ForeignKey(Poll)
choice = models.CharField(maxlength=200) choice = models.CharField(max_length=200)
votes = models.IntegerField() votes = models.IntegerField()
The code is straightforward. Each model is represented by a class that The code is straightforward. Each model is represented by a class that
@ -279,7 +279,7 @@ name for ``Poll.pub_date``. For all other fields in this model, the field's
machine-readable name will suffice as its human-readable name. machine-readable name will suffice as its human-readable name.
Some ``Field`` classes have required elements. ``CharField``, for example, Some ``Field`` classes have required elements. ``CharField``, for example,
requires that you give it a ``maxlength``. That's used not only in the database requires that you give it a ``max_length``. That's used not only in the database
schema, but in validation, as we'll soon see. schema, but in validation, as we'll soon see.
Finally, note a relationship is defined, using ``models.ForeignKey``. That tells Finally, note a relationship is defined, using ``models.ForeignKey``. That tells

View File

@ -240,7 +240,7 @@ default, provide enough fields for 3 Choices."
Then change the other fields in ``Choice`` to give them ``core=True``:: Then change the other fields in ``Choice`` to give them ``core=True``::
choice = models.CharField(maxlength=200, core=True) choice = models.CharField(max_length=200, core=True)
votes = models.IntegerField(core=True) votes = models.IntegerField(core=True)
This tells Django: "When you edit a Choice on the Poll admin page, the 'choice' This tells Django: "When you edit a Choice on the Poll admin page, the 'choice'

View File

@ -8,7 +8,7 @@ This is a basic model with only two non-primary-key fields.
from django.db import models from django.db import models
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=100, default='Default headline') headline = models.CharField(max_length=100, default='Default headline')
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
class Meta: class Meta:

View File

@ -17,8 +17,8 @@ GENDER_CHOICES = (
) )
class Person(models.Model): class Person(models.Model):
name = models.CharField(maxlength=20) name = models.CharField(max_length=20)
gender = models.CharField(maxlength=1, choices=GENDER_CHOICES) gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
def __unicode__(self): def __unicode__(self):
return self.name return self.name

View File

@ -18,8 +18,8 @@ ManyToMany field. This has no effect on the API for querying the database.
from django.db import models from django.db import models
class Author(models.Model): class Author(models.Model):
first_name = models.CharField(maxlength=30, db_column='firstname') first_name = models.CharField(max_length=30, db_column='firstname')
last_name = models.CharField(maxlength=30, db_column='last') last_name = models.CharField(max_length=30, db_column='last')
def __unicode__(self): def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name) return u'%s %s' % (self.first_name, self.last_name)
@ -29,7 +29,7 @@ class Author(models.Model):
ordering = ('last_name','first_name') ordering = ('last_name','first_name')
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=100) headline = models.CharField(max_length=100)
authors = models.ManyToManyField(Author, db_table='my_m2m_table') authors = models.ManyToManyField(Author, db_table='my_m2m_table')
def __unicode__(self): def __unicode__(self):

View File

@ -18,8 +18,8 @@ class PersonManager(models.Manager):
return self.filter(fun=True) return self.filter(fun=True)
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
fun = models.BooleanField() fun = models.BooleanField()
objects = PersonManager() objects = PersonManager()
@ -33,8 +33,8 @@ class PublishedBookManager(models.Manager):
return super(PublishedBookManager, self).get_query_set().filter(is_published=True) return super(PublishedBookManager, self).get_query_set().filter(is_published=True)
class Book(models.Model): class Book(models.Model):
title = models.CharField(maxlength=50) title = models.CharField(max_length=50)
author = models.CharField(maxlength=30) author = models.CharField(max_length=30)
is_published = models.BooleanField() is_published = models.BooleanField()
published_objects = PublishedBookManager() published_objects = PublishedBookManager()
authors = models.ManyToManyField(Person, related_name='books') authors = models.ManyToManyField(Person, related_name='books')
@ -49,7 +49,7 @@ class FastCarManager(models.Manager):
return super(FastCarManager, self).get_query_set().filter(top_speed__gt=150) return super(FastCarManager, self).get_query_set().filter(top_speed__gt=150)
class Car(models.Model): class Car(models.Model):
name = models.CharField(maxlength=10) name = models.CharField(max_length=10)
mileage = models.IntegerField() mileage = models.IntegerField()
top_speed = models.IntegerField(help_text="In miles per hour.") top_speed = models.IntegerField(help_text="In miles per hour.")
cars = models.Manager() cars = models.Manager()

View File

@ -8,7 +8,7 @@ from django.db import models
import datetime import datetime
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=100) headline = models.CharField(max_length=100)
pub_date = models.DateField() pub_date = models.DateField()
def __unicode__(self): def __unicode__(self):

View File

@ -8,10 +8,10 @@ this behavior by explicitly adding ``primary_key=True`` to a field.
from django.db import models from django.db import models
class Employee(models.Model): class Employee(models.Model):
employee_code = models.CharField(maxlength=10, primary_key=True, employee_code = models.CharField(max_length=10, primary_key=True,
db_column = 'code') db_column = 'code')
first_name = models.CharField(maxlength=20) first_name = models.CharField(max_length=20)
last_name = models.CharField(maxlength=20) last_name = models.CharField(max_length=20)
class Meta: class Meta:
ordering = ('last_name', 'first_name') ordering = ('last_name', 'first_name')
@ -19,7 +19,7 @@ class Employee(models.Model):
return u"%s %s" % (self.first_name, self.last_name) return u"%s %s" % (self.first_name, self.last_name)
class Business(models.Model): class Business(models.Model):
name = models.CharField(maxlength=20, primary_key=True) name = models.CharField(max_length=20, primary_key=True)
employees = models.ManyToManyField(Employee) employees = models.ManyToManyField(Employee)
class Meta: class Meta:
verbose_name_plural = 'businesses' verbose_name_plural = 'businesses'

View File

@ -13,7 +13,7 @@ from django.db import models
from datetime import datetime from datetime import datetime
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=100, default='Default headline') headline = models.CharField(max_length=100, default='Default headline')
pub_date = models.DateTimeField(default=datetime.now) pub_date = models.DateTimeField(default=datetime.now)
def __unicode__(self): def __unicode__(self):

View File

@ -11,7 +11,7 @@ FIXTURE_DIRS setting.
from django.db import models from django.db import models
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=100, default='Default headline') headline = models.CharField(max_length=100, default='Default headline')
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
def __unicode__(self): def __unicode__(self):

View File

@ -28,8 +28,8 @@ class TaggedItem(models.Model):
return self.tag return self.tag
class Animal(models.Model): class Animal(models.Model):
common_name = models.CharField(maxlength=150) common_name = models.CharField(max_length=150)
latin_name = models.CharField(maxlength=150) latin_name = models.CharField(max_length=150)
tags = generic.GenericRelation(TaggedItem) tags = generic.GenericRelation(TaggedItem)
@ -37,7 +37,7 @@ class Animal(models.Model):
return self.common_name return self.common_name
class Vegetable(models.Model): class Vegetable(models.Model):
name = models.CharField(maxlength=150) name = models.CharField(max_length=150)
is_yucky = models.BooleanField(default=True) is_yucky = models.BooleanField(default=True)
tags = generic.GenericRelation(TaggedItem) tags = generic.GenericRelation(TaggedItem)
@ -46,7 +46,7 @@ class Vegetable(models.Model):
return self.name return self.name
class Mineral(models.Model): class Mineral(models.Model):
name = models.CharField(maxlength=150) name = models.CharField(max_length=150)
hardness = models.PositiveSmallIntegerField() hardness = models.PositiveSmallIntegerField()
# note the lack of an explicit GenericRelation here... # note the lack of an explicit GenericRelation here...

View File

@ -11,7 +11,7 @@ into the future."
from django.db import models from django.db import models
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=100) headline = models.CharField(max_length=100)
pub_date = models.DateField() pub_date = models.DateField()
expire_date = models.DateField() expire_date = models.DateField()
class Meta: class Meta:
@ -21,7 +21,7 @@ class Article(models.Model):
return self.headline return self.headline
class Person(models.Model): class Person(models.Model):
name = models.CharField(maxlength=30) name = models.CharField(max_length=30)
birthday = models.DateField() birthday = models.DateField()
# Note that this model doesn't have "get_latest_by" set. # Note that this model doesn't have "get_latest_by" set.

View File

@ -15,7 +15,7 @@ from django.http import Http404
from django.shortcuts import get_object_or_404, get_list_or_404 from django.shortcuts import get_object_or_404, get_list_or_404
class Author(models.Model): class Author(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
def __unicode__(self): def __unicode__(self):
return self.name return self.name
@ -26,7 +26,7 @@ class ArticleManager(models.Manager):
class Article(models.Model): class Article(models.Model):
authors = models.ManyToManyField(Author) authors = models.ManyToManyField(Author)
title = models.CharField(maxlength=50) title = models.CharField(max_length=50)
objects = models.Manager() objects = models.Manager()
by_a_sir = ArticleManager() by_a_sir = ArticleManager()

View File

@ -8,8 +8,8 @@ parameters. If an object isn't found, it creates one with the given parameters.
from django.db import models from django.db import models
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=100) first_name = models.CharField(max_length=100)
last_name = models.CharField(maxlength=100) last_name = models.CharField(max_length=100)
birthday = models.DateField() birthday = models.DateField()
def __unicode__(self): def __unicode__(self):

View File

@ -10,26 +10,26 @@ class FieldErrors(models.Model):
charfield = models.CharField() charfield = models.CharField()
decimalfield = models.DecimalField() decimalfield = models.DecimalField()
filefield = models.FileField() filefield = models.FileField()
prepopulate = models.CharField(maxlength=10, prepopulate_from='bad') prepopulate = models.CharField(max_length=10, prepopulate_from='bad')
choices = models.CharField(maxlength=10, choices='bad') choices = models.CharField(max_length=10, choices='bad')
choices2 = models.CharField(maxlength=10, choices=[(1,2,3),(1,2,3)]) choices2 = models.CharField(max_length=10, choices=[(1,2,3),(1,2,3)])
index = models.CharField(maxlength=10, db_index='bad') index = models.CharField(max_length=10, db_index='bad')
class Target(models.Model): class Target(models.Model):
tgt_safe = models.CharField(maxlength=10) tgt_safe = models.CharField(max_length=10)
clash1 = models.CharField(maxlength=10) clash1 = models.CharField(max_length=10)
clash2 = models.CharField(maxlength=10) clash2 = models.CharField(max_length=10)
clash1_set = models.CharField(maxlength=10) clash1_set = models.CharField(max_length=10)
class Clash1(models.Model): class Clash1(models.Model):
src_safe = models.CharField(maxlength=10, core=True) src_safe = models.CharField(max_length=10, core=True)
foreign = models.ForeignKey(Target) foreign = models.ForeignKey(Target)
m2m = models.ManyToManyField(Target) m2m = models.ManyToManyField(Target)
class Clash2(models.Model): class Clash2(models.Model):
src_safe = models.CharField(maxlength=10, core=True) src_safe = models.CharField(max_length=10, core=True)
foreign_1 = models.ForeignKey(Target, related_name='id') foreign_1 = models.ForeignKey(Target, related_name='id')
foreign_2 = models.ForeignKey(Target, related_name='src_safe') foreign_2 = models.ForeignKey(Target, related_name='src_safe')
@ -38,7 +38,7 @@ class Clash2(models.Model):
m2m_2 = models.ManyToManyField(Target, related_name='src_safe') m2m_2 = models.ManyToManyField(Target, related_name='src_safe')
class Target2(models.Model): class Target2(models.Model):
clash3 = models.CharField(maxlength=10) clash3 = models.CharField(max_length=10)
foreign_tgt = models.ForeignKey(Target) foreign_tgt = models.ForeignKey(Target)
clashforeign_set = models.ForeignKey(Target) clashforeign_set = models.ForeignKey(Target)
@ -46,7 +46,7 @@ class Target2(models.Model):
clashm2m_set = models.ManyToManyField(Target) clashm2m_set = models.ManyToManyField(Target)
class Clash3(models.Model): class Clash3(models.Model):
src_safe = models.CharField(maxlength=10, core=True) src_safe = models.CharField(max_length=10, core=True)
foreign_1 = models.ForeignKey(Target2, related_name='foreign_tgt') foreign_1 = models.ForeignKey(Target2, related_name='foreign_tgt')
foreign_2 = models.ForeignKey(Target2, related_name='m2m_tgt') foreign_2 = models.ForeignKey(Target2, related_name='m2m_tgt')
@ -61,16 +61,16 @@ class ClashM2M(models.Model):
m2m = models.ManyToManyField(Target2) m2m = models.ManyToManyField(Target2)
class SelfClashForeign(models.Model): class SelfClashForeign(models.Model):
src_safe = models.CharField(maxlength=10, core=True) src_safe = models.CharField(max_length=10, core=True)
selfclashforeign = models.CharField(maxlength=10) selfclashforeign = models.CharField(max_length=10)
selfclashforeign_set = models.ForeignKey("SelfClashForeign") selfclashforeign_set = models.ForeignKey("SelfClashForeign")
foreign_1 = models.ForeignKey("SelfClashForeign", related_name='id') foreign_1 = models.ForeignKey("SelfClashForeign", related_name='id')
foreign_2 = models.ForeignKey("SelfClashForeign", related_name='src_safe') foreign_2 = models.ForeignKey("SelfClashForeign", related_name='src_safe')
class ValidM2M(models.Model): class ValidM2M(models.Model):
src_safe = models.CharField(maxlength=10) src_safe = models.CharField(max_length=10)
validm2m = models.CharField(maxlength=10) validm2m = models.CharField(max_length=10)
# M2M fields are symmetrical by default. Symmetrical M2M fields # M2M fields are symmetrical by default. Symmetrical M2M fields
# on self don't require a related accessor, so many potential # on self don't require a related accessor, so many potential
@ -84,8 +84,8 @@ class ValidM2M(models.Model):
m2m_4 = models.ManyToManyField('self') m2m_4 = models.ManyToManyField('self')
class SelfClashM2M(models.Model): class SelfClashM2M(models.Model):
src_safe = models.CharField(maxlength=10) src_safe = models.CharField(max_length=10)
selfclashm2m = models.CharField(maxlength=10) selfclashm2m = models.CharField(max_length=10)
# Non-symmetrical M2M fields _do_ have related accessors, so # Non-symmetrical M2M fields _do_ have related accessors, so
# there is potential for clashes. # there is potential for clashes.
@ -100,14 +100,14 @@ class SelfClashM2M(models.Model):
class Model(models.Model): class Model(models.Model):
"But it's valid to call a model Model." "But it's valid to call a model Model."
year = models.PositiveIntegerField() #1960 year = models.PositiveIntegerField() #1960
make = models.CharField(maxlength=10) #Aston Martin make = models.CharField(max_length=10) #Aston Martin
name = models.CharField(maxlength=10) #DB 4 GT name = models.CharField(max_length=10) #DB 4 GT
class Car(models.Model): class Car(models.Model):
colour = models.CharField(maxlength=5) colour = models.CharField(max_length=5)
model = models.ForeignKey(Model) model = models.ForeignKey(Model)
model_errors = """invalid_models.fielderrors: "charfield": CharFields require a "maxlength" attribute. model_errors = """invalid_models.fielderrors: "charfield": CharFields require a "max_length" attribute.
invalid_models.fielderrors: "decimalfield": DecimalFields require a "decimal_places" attribute. invalid_models.fielderrors: "decimalfield": DecimalFields require a "decimal_places" attribute.
invalid_models.fielderrors: "decimalfield": DecimalFields require a "max_digits" attribute. invalid_models.fielderrors: "decimalfield": DecimalFields require a "max_digits" attribute.
invalid_models.fielderrors: "filefield": FileFields require an "upload_to" attribute. invalid_models.fielderrors: "filefield": FileFields require an "upload_to" attribute.

View File

@ -8,7 +8,7 @@ from django.db import models
from django.conf import settings from django.conf import settings
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=100) headline = models.CharField(max_length=100)
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
class Meta: class Meta:
ordering = ('-pub_date', 'headline') ordering = ('-pub_date', 'headline')

View File

@ -7,7 +7,7 @@ Make sure to set ``related_name`` if you use relationships to the same table.
from django.db import models from django.db import models
class User(models.Model): class User(models.Model):
username = models.CharField(maxlength=20) username = models.CharField(max_length=20)
class Issue(models.Model): class Issue(models.Model):
num = models.IntegerField() num = models.IntegerField()

View File

@ -13,14 +13,14 @@ writer").
from django.db import models from django.db import models
class Reporter(models.Model): class Reporter(models.Model):
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
def __unicode__(self): def __unicode__(self):
return u"%s %s" % (self.first_name, self.last_name) return u"%s %s" % (self.first_name, self.last_name)
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=100) headline = models.CharField(max_length=100)
pub_date = models.DateField() pub_date = models.DateField()
def __unicode__(self): def __unicode__(self):
@ -29,7 +29,7 @@ class Article(models.Model):
class Writer(models.Model): class Writer(models.Model):
reporter = models.ForeignKey(Reporter) reporter = models.ForeignKey(Reporter)
article = models.ForeignKey(Article) article = models.ForeignKey(Article)
position = models.CharField(maxlength=100) position = models.CharField(max_length=100)
def __unicode__(self): def __unicode__(self):
return u'%s (%s)' % (self.reporter, self.position) return u'%s (%s)' % (self.reporter, self.position)

View File

@ -10,7 +10,7 @@ Set ``related_name`` to designate what the reverse relationship is called.
from django.db import models from django.db import models
class Category(models.Model): class Category(models.Model):
name = models.CharField(maxlength=20) name = models.CharField(max_length=20)
class Meta: class Meta:
ordering = ('name',) ordering = ('name',)
@ -18,7 +18,7 @@ class Category(models.Model):
return self.name return self.name
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=50) headline = models.CharField(max_length=50)
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
primary_categories = models.ManyToManyField(Category, related_name='primary_article_set') primary_categories = models.ManyToManyField(Category, related_name='primary_article_set')
secondary_categories = models.ManyToManyField(Category, related_name='secondary_article_set') secondary_categories = models.ManyToManyField(Category, related_name='secondary_article_set')

View File

@ -15,7 +15,7 @@ there will be a clash, and tests that symmetry is preserved where appropriate.
from django.db import models from django.db import models
class Person(models.Model): class Person(models.Model):
name = models.CharField(maxlength=20) name = models.CharField(max_length=20)
friends = models.ManyToManyField('self') friends = models.ManyToManyField('self')
idols = models.ManyToManyField('self', symmetrical=False, related_name='stalkers') idols = models.ManyToManyField('self', symmetrical=False, related_name='stalkers')

View File

@ -13,7 +13,7 @@ Set ``related_name`` to designate what the reverse relationship is called.
from django.db import models from django.db import models
class Category(models.Model): class Category(models.Model):
name = models.CharField(maxlength=20) name = models.CharField(max_length=20)
parent = models.ForeignKey('self', null=True, related_name='child_set') parent = models.ForeignKey('self', null=True, related_name='child_set')
def __unicode__(self): def __unicode__(self):

View File

@ -10,7 +10,7 @@ Set ``related_name`` to designate what the reverse relationship is called.
from django.db import models from django.db import models
class Person(models.Model): class Person(models.Model):
full_name = models.CharField(maxlength=20) full_name = models.CharField(max_length=20)
mother = models.ForeignKey('self', null=True, related_name='mothers_child_set') mother = models.ForeignKey('self', null=True, related_name='mothers_child_set')
father = models.ForeignKey('self', null=True, related_name='fathers_child_set') father = models.ForeignKey('self', null=True, related_name='fathers_child_set')

View File

@ -7,14 +7,14 @@ Each model gets an AddManipulator and ChangeManipulator by default.
from django.db import models from django.db import models
class Musician(models.Model): class Musician(models.Model):
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
def __unicode__(self): def __unicode__(self):
return u"%s %s" % (self.first_name, self.last_name) return u"%s %s" % (self.first_name, self.last_name)
class Album(models.Model): class Album(models.Model):
name = models.CharField(maxlength=100) name = models.CharField(max_length=100)
musician = models.ForeignKey(Musician) musician = models.ForeignKey(Musician)
release_date = models.DateField(blank=True, null=True) release_date = models.DateField(blank=True, null=True)

View File

@ -10,7 +10,7 @@ and a publication has multiple articles.
from django.db import models from django.db import models
class Publication(models.Model): class Publication(models.Model):
title = models.CharField(maxlength=30) title = models.CharField(max_length=30)
def __unicode__(self): def __unicode__(self):
return self.title return self.title
@ -19,7 +19,7 @@ class Publication(models.Model):
ordering = ('title',) ordering = ('title',)
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=100) headline = models.CharField(max_length=100)
publications = models.ManyToManyField(Publication) publications = models.ManyToManyField(Publication)
def __unicode__(self): def __unicode__(self):

View File

@ -7,15 +7,15 @@ To define a many-to-one relationship, use ``ForeignKey()`` .
from django.db import models from django.db import models
class Reporter(models.Model): class Reporter(models.Model):
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
email = models.EmailField() email = models.EmailField()
def __unicode__(self): def __unicode__(self):
return u"%s %s" % (self.first_name, self.last_name) return u"%s %s" % (self.first_name, self.last_name)
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=100) headline = models.CharField(max_length=100)
pub_date = models.DateField() pub_date = models.DateField()
reporter = models.ForeignKey(Reporter) reporter = models.ForeignKey(Reporter)

View File

@ -8,13 +8,13 @@ To define a many-to-one relationship that can have a null foreign key, use
from django.db import models from django.db import models
class Reporter(models.Model): class Reporter(models.Model):
name = models.CharField(maxlength=30) name = models.CharField(max_length=30)
def __unicode__(self): def __unicode__(self):
return self.name return self.name
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=100) headline = models.CharField(max_length=100)
reporter = models.ForeignKey(Reporter, null=True) reporter = models.ForeignKey(Reporter, null=True)
class Meta: class Meta:

View File

@ -31,20 +31,20 @@ ARTICLE_STATUS = (
) )
class Category(models.Model): class Category(models.Model):
name = models.CharField(maxlength=20) name = models.CharField(max_length=20)
url = models.CharField('The URL', maxlength=40) url = models.CharField('The URL', max_length=40)
def __unicode__(self): def __unicode__(self):
return self.name return self.name
class Writer(models.Model): class Writer(models.Model):
name = models.CharField(maxlength=50, help_text='Use both first and last names.') name = models.CharField(max_length=50, help_text='Use both first and last names.')
def __unicode__(self): def __unicode__(self):
return self.name return self.name
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=50) headline = models.CharField(max_length=50)
pub_date = models.DateField() pub_date = models.DateField()
created = models.DateField(editable=False) created = models.DateField(editable=False)
writer = models.ForeignKey(Writer) writer = models.ForeignKey(Writer)
@ -63,7 +63,7 @@ class Article(models.Model):
class PhoneNumber(models.Model): class PhoneNumber(models.Model):
phone = models.PhoneNumberField() phone = models.PhoneNumberField()
description = models.CharField(maxlength=20) description = models.CharField(max_length=20)
def __unicode__(self): def __unicode__(self):
return self.phone return self.phone

View File

@ -7,8 +7,8 @@ Model inheritance isn't yet supported.
from django.db import models from django.db import models
class Place(models.Model): class Place(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
address = models.CharField(maxlength=80) address = models.CharField(max_length=80)
def __unicode__(self): def __unicode__(self):
return u"%s the place" % self.name return u"%s the place" % self.name

View File

@ -7,11 +7,11 @@ To define a many-to-one relationship, use ``ForeignKey()`` .
from django.db.models import * from django.db.models import *
class Parent(Model): class Parent(Model):
name = CharField(maxlength=100, core=True) name = CharField(max_length=100, core=True)
bestchild = ForeignKey("Child", null=True, related_name="favoured_by") bestchild = ForeignKey("Child", null=True, related_name="favoured_by")
class Child(Model): class Child(Model):
name = CharField(maxlength=100) name = CharField(max_length=100)
parent = ForeignKey(Parent) parent = ForeignKey(Parent)
__test__ = {'API_TESTS':""" __test__ = {'API_TESTS':"""

View File

@ -9,8 +9,8 @@ In this example, a ``Place`` optionally can be a ``Restaurant``.
from django.db import models from django.db import models
class Place(models.Model): class Place(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
address = models.CharField(maxlength=80) address = models.CharField(max_length=80)
def __unicode__(self): def __unicode__(self):
return u"%s the place" % self.name return u"%s the place" % self.name
@ -25,18 +25,18 @@ class Restaurant(models.Model):
class Waiter(models.Model): class Waiter(models.Model):
restaurant = models.ForeignKey(Restaurant) restaurant = models.ForeignKey(Restaurant)
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
def __unicode__(self): def __unicode__(self):
return u"%s the waiter at %s" % (self.name, self.restaurant) return u"%s the waiter at %s" % (self.name, self.restaurant)
class ManualPrimaryKey(models.Model): class ManualPrimaryKey(models.Model):
primary_key = models.CharField(maxlength=10, primary_key=True) primary_key = models.CharField(max_length=10, primary_key=True)
name = models.CharField(maxlength = 50) name = models.CharField(max_length = 50)
class RelatedModel(models.Model): class RelatedModel(models.Model):
link = models.OneToOneField(ManualPrimaryKey) link = models.OneToOneField(ManualPrimaryKey)
name = models.CharField(maxlength = 50) name = models.CharField(max_length = 50)
__test__ = {'API_TESTS':""" __test__ = {'API_TESTS':"""
# Create a couple of Places. # Create a couple of Places.

View File

@ -14,7 +14,7 @@ a get_sql method).
from django.db import models from django.db import models
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=50) headline = models.CharField(max_length=50)
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
class Meta: class Meta:

View File

@ -16,7 +16,7 @@ undefined -- not random, just undefined.
from django.db import models from django.db import models
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=100) headline = models.CharField(max_length=100)
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
class Meta: class Meta:
ordering = ('-pub_date', 'headline') ordering = ('-pub_date', 'headline')

View File

@ -9,7 +9,7 @@ objects into easily readable pages.
from django.db import models from django.db import models
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=100, default='Default headline') headline = models.CharField(max_length=100, default='Default headline')
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
def __unicode__(self): def __unicode__(self):

View File

@ -7,8 +7,8 @@ Use properties on models just like on any other Python object.
from django.db import models from django.db import models
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
def _get_full_name(self): def _get_full_name(self):
return "%s %s" % (self.first_name, self.last_name) return "%s %s" % (self.first_name, self.last_name)

View File

@ -10,14 +10,14 @@ reserved-name usage.
from django.db import models from django.db import models
class Thing(models.Model): class Thing(models.Model):
when = models.CharField(maxlength=1, primary_key=True) when = models.CharField(max_length=1, primary_key=True)
join = models.CharField(maxlength=1) join = models.CharField(max_length=1)
like = models.CharField(maxlength=1) like = models.CharField(max_length=1)
drop = models.CharField(maxlength=1) drop = models.CharField(max_length=1)
alter = models.CharField(maxlength=1) alter = models.CharField(max_length=1)
having = models.CharField(maxlength=1) having = models.CharField(max_length=1)
where = models.DateField(maxlength=1) where = models.DateField(max_length=1)
has_hyphen = models.CharField(maxlength=1, db_column='has-hyphen') has_hyphen = models.CharField(max_length=1, db_column='has-hyphen')
class Meta: class Meta:
db_table = 'select' db_table = 'select'

View File

@ -7,20 +7,20 @@ This demonstrates the reverse lookup features of the database API.
from django.db import models from django.db import models
class User(models.Model): class User(models.Model):
name = models.CharField(maxlength=200) name = models.CharField(max_length=200)
def __unicode__(self): def __unicode__(self):
return self.name return self.name
class Poll(models.Model): class Poll(models.Model):
question = models.CharField(maxlength=200) question = models.CharField(max_length=200)
creator = models.ForeignKey(User) creator = models.ForeignKey(User)
def __unicode__(self): def __unicode__(self):
return self.question return self.question
class Choice(models.Model): class Choice(models.Model):
name = models.CharField(maxlength=100) name = models.CharField(max_length=100)
poll = models.ForeignKey(Poll, related_name="poll_choice") poll = models.ForeignKey(Poll, related_name="poll_choice")
related_poll = models.ForeignKey(Poll, related_name="related_choice") related_poll = models.ForeignKey(Poll, related_name="related_choice")

View File

@ -8,8 +8,8 @@ the methods.
from django.db import models from django.db import models
class Person(models.Model): class Person(models.Model):
first_name = models.CharField(maxlength=20) first_name = models.CharField(max_length=20)
last_name = models.CharField(maxlength=20) last_name = models.CharField(max_length=20)
def __unicode__(self): def __unicode__(self):
return u"%s %s" % (self.first_name, self.last_name) return u"%s %s" % (self.first_name, self.last_name)

View File

@ -12,48 +12,48 @@ from django.db import models
# Who remembers high school biology? # Who remembers high school biology?
class Domain(models.Model): class Domain(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
def __unicode__(self): def __unicode__(self):
return self.name return self.name
class Kingdom(models.Model): class Kingdom(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
domain = models.ForeignKey(Domain) domain = models.ForeignKey(Domain)
def __unicode__(self): def __unicode__(self):
return self.name return self.name
class Phylum(models.Model): class Phylum(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
kingdom = models.ForeignKey(Kingdom) kingdom = models.ForeignKey(Kingdom)
def __unicode__(self): def __unicode__(self):
return self.name return self.name
class Klass(models.Model): class Klass(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
phylum = models.ForeignKey(Phylum) phylum = models.ForeignKey(Phylum)
def __unicode__(self): def __unicode__(self):
return self.name return self.name
class Order(models.Model): class Order(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
klass = models.ForeignKey(Klass) klass = models.ForeignKey(Klass)
def __unicode__(self): def __unicode__(self):
return self.name return self.name
class Family(models.Model): class Family(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
order = models.ForeignKey(Order) order = models.ForeignKey(Order)
def __unicode__(self): def __unicode__(self):
return self.name return self.name
class Genus(models.Model): class Genus(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
family = models.ForeignKey(Family) family = models.ForeignKey(Family)
def __unicode__(self): def __unicode__(self):
return self.name return self.name
class Species(models.Model): class Species(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
genus = models.ForeignKey(Genus) genus = models.ForeignKey(Genus)
def __unicode__(self): def __unicode__(self):
return self.name return self.name

View File

@ -8,7 +8,7 @@ to and from "flat" data (i.e. strings).
from django.db import models from django.db import models
class Category(models.Model): class Category(models.Model):
name = models.CharField(maxlength=20) name = models.CharField(max_length=20)
class Meta: class Meta:
ordering = ('name',) ordering = ('name',)
@ -17,7 +17,7 @@ class Category(models.Model):
return self.name return self.name
class Author(models.Model): class Author(models.Model):
name = models.CharField(maxlength=20) name = models.CharField(max_length=20)
class Meta: class Meta:
ordering = ('name',) ordering = ('name',)
@ -27,7 +27,7 @@ class Author(models.Model):
class Article(models.Model): class Article(models.Model):
author = models.ForeignKey(Author) author = models.ForeignKey(Author)
headline = models.CharField(maxlength=50) headline = models.CharField(max_length=50)
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
categories = models.ManyToManyField(Category) categories = models.ManyToManyField(Category)

View File

@ -17,7 +17,7 @@ if you prefer. You must be careful to encode the results correctly, though.
from django.db import models from django.db import models
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=100) headline = models.CharField(max_length=100)
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
def __str__(self): def __str__(self):
@ -26,7 +26,7 @@ class Article(models.Model):
return self.headline return self.headline
class InternationalArticle(models.Model): class InternationalArticle(models.Model):
headline = models.CharField(maxlength=100) headline = models.CharField(max_length=100)
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
def __unicode__(self): def __unicode__(self):

View File

@ -10,8 +10,8 @@ manually.
from django.db import models from django.db import models
class Reporter(models.Model): class Reporter(models.Model):
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
email = models.EmailField() email = models.EmailField()
def __unicode__(self): def __unicode__(self):

View File

@ -12,7 +12,7 @@ from django.db import models
class Person(models.Model): class Person(models.Model):
is_child = models.BooleanField() is_child = models.BooleanField()
name = models.CharField(maxlength=20) name = models.CharField(max_length=20)
birthdate = models.DateField() birthdate = models.DateField()
favorite_moment = models.DateTimeField() favorite_moment = models.DateTimeField()
email = models.EmailField() email = models.EmailField()

View File

@ -2,7 +2,7 @@ import tempfile
from django.db import models from django.db import models
class Photo(models.Model): class Photo(models.Model):
title = models.CharField(maxlength=30) title = models.CharField(max_length=30)
image = models.FileField(upload_to=tempfile.gettempdir()) image = models.FileField(upload_to=tempfile.gettempdir())
# Support code for the tests; this keeps track of how many times save() gets # Support code for the tests; this keeps track of how many times save() gets

View File

@ -7,7 +7,7 @@ from django.db import models
from django.conf import settings from django.conf import settings
class Donut(models.Model): class Donut(models.Model):
name = models.CharField(maxlength=100) name = models.CharField(max_length=100)
is_frosted = models.BooleanField(default=False) is_frosted = models.BooleanField(default=False)
has_sprinkles = models.NullBooleanField() has_sprinkles = models.NullBooleanField()
baked_date = models.DateField(null=True) baked_date = models.DateField(null=True)

View File

@ -2,21 +2,21 @@ from django.db import models
from django.contrib.auth.models import User from django.contrib.auth.models import User
class Animal(models.Model): class Animal(models.Model):
name = models.CharField(maxlength=150) name = models.CharField(max_length=150)
latin_name = models.CharField(maxlength=150) latin_name = models.CharField(max_length=150)
def __unicode__(self): def __unicode__(self):
return self.common_name return self.common_name
class Plant(models.Model): class Plant(models.Model):
name = models.CharField(maxlength=150) name = models.CharField(max_length=150)
class Meta: class Meta:
# For testing when upper case letter in app name; regression for #4057 # For testing when upper case letter in app name; regression for #4057
db_table = "Fixtures_regress_plant" db_table = "Fixtures_regress_plant"
class Stuff(models.Model): class Stuff(models.Model):
name = models.CharField(maxlength=20, null=True) name = models.CharField(max_length=20, null=True)
owner = models.ForeignKey(User, null=True) owner = models.ForeignKey(User, null=True)
def __unicode__(self): def __unicode__(self):

View File

@ -5,7 +5,7 @@ Regression tests for initial SQL insertion.
from django.db import models from django.db import models
class Simple(models.Model): class Simple(models.Model):
name = models.CharField(maxlength = 50) name = models.CharField(max_length = 50)
__test__ = {'API_TESTS':""} __test__ = {'API_TESTS':""}

View File

@ -12,7 +12,7 @@ model_errors = ""
##This should fail gracefully but is causing a metaclass error ##This should fail gracefully but is causing a metaclass error
#class BadAdminOption(models.Model): #class BadAdminOption(models.Model):
# "Test nonexistent admin option" # "Test nonexistent admin option"
# name = models.CharField(maxlength=30) # name = models.CharField(max_length=30)
# #
# class Admin: # class Admin:
# nonexistent = 'option' # nonexistent = 'option'
@ -22,7 +22,7 @@ model_errors = ""
class ListDisplayBadOne(models.Model): class ListDisplayBadOne(models.Model):
"Test list_display, list_display must be a list or tuple" "Test list_display, list_display must be a list or tuple"
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
class Admin: class Admin:
list_display = 'first_name' list_display = 'first_name'
@ -32,7 +32,7 @@ model_errors += """invalid_admin_options.listdisplaybadone: "admin.list_display"
class ListDisplayBadTwo(models.Model): class ListDisplayBadTwo(models.Model):
"Test list_display, list_display items must be attributes, methods or properties." "Test list_display, list_display items must be attributes, methods or properties."
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
class Admin: class Admin:
list_display = ['first_name','nonexistent'] list_display = ['first_name','nonexistent']
@ -41,7 +41,7 @@ model_errors += """invalid_admin_options.listdisplaybadtwo: "admin.list_display"
""" """
class ListDisplayBadThree(models.Model): class ListDisplayBadThree(models.Model):
"Test list_display, list_display items can not be a ManyToManyField." "Test list_display, list_display items can not be a ManyToManyField."
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
nick_names = models.ManyToManyField('ListDisplayGood') nick_names = models.ManyToManyField('ListDisplayGood')
class Admin: class Admin:
@ -52,7 +52,7 @@ model_errors += """invalid_admin_options.listdisplaybadthree: "admin.list_displa
class ListDisplayGood(models.Model): class ListDisplayGood(models.Model):
"Test list_display, Admin list_display can be a attribute, method or property." "Test list_display, Admin list_display can be a attribute, method or property."
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
def _last_name(self): def _last_name(self):
return self.first_name return self.first_name
@ -66,8 +66,8 @@ class ListDisplayGood(models.Model):
class ListDisplayLinksBadOne(models.Model): class ListDisplayLinksBadOne(models.Model):
"Test list_display_links, item must be included in list_display." "Test list_display_links, item must be included in list_display."
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
class Admin: class Admin:
list_display = ['last_name'] list_display = ['last_name']
@ -78,8 +78,8 @@ model_errors += """invalid_admin_options.listdisplaylinksbadone: "admin.list_dis
class ListDisplayLinksBadTwo(models.Model): class ListDisplayLinksBadTwo(models.Model):
"Test list_display_links, must be a list or tuple." "Test list_display_links, must be a list or tuple."
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
class Admin: class Admin:
list_display = ['first_name','last_name'] list_display = ['first_name','last_name']
@ -92,8 +92,8 @@ model_errors += """invalid_admin_options.listdisplaylinksbadtwo: "admin.list_dis
## This is failing but the validation which should fail is not. ## This is failing but the validation which should fail is not.
#class ListDisplayLinksBadThree(models.Model): #class ListDisplayLinksBadThree(models.Model):
# "Test list_display_links, must define list_display to use list_display_links." # "Test list_display_links, must define list_display to use list_display_links."
# first_name = models.CharField(maxlength=30) # first_name = models.CharField(max_length=30)
# last_name = models.CharField(maxlength=30) # last_name = models.CharField(max_length=30)
# #
# class Admin: # class Admin:
# list_display_links = ('first_name',) # list_display_links = ('first_name',)
@ -103,7 +103,7 @@ model_errors += """invalid_admin_options.listdisplaylinksbadtwo: "admin.list_dis
class ListDisplayLinksGood(models.Model): class ListDisplayLinksGood(models.Model):
"Test list_display_links, Admin list_display_list can be a attribute, method or property." "Test list_display_links, Admin list_display_list can be a attribute, method or property."
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
def _last_name(self): def _last_name(self):
return self.first_name return self.first_name
@ -118,7 +118,7 @@ class ListDisplayLinksGood(models.Model):
class ListFilterBadOne(models.Model): class ListFilterBadOne(models.Model):
"Test list_filter, must be a list or tuple." "Test list_filter, must be a list or tuple."
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
class Admin: class Admin:
list_filter = 'first_name' list_filter = 'first_name'
@ -128,7 +128,7 @@ model_errors += """invalid_admin_options.listfilterbadone: "admin.list_filter",
class ListFilterBadTwo(models.Model): class ListFilterBadTwo(models.Model):
"Test list_filter, must be a field not a property or method." "Test list_filter, must be a field not a property or method."
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
def _last_name(self): def _last_name(self):
return self.first_name return self.first_name
@ -146,7 +146,7 @@ invalid_admin_options.listfilterbadtwo: "admin.list_filter" refers to 'full_name
class DateHierarchyBadOne(models.Model): class DateHierarchyBadOne(models.Model):
"Test date_hierarchy, must be a date or datetime field." "Test date_hierarchy, must be a date or datetime field."
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
birth_day = models.DateField() birth_day = models.DateField()
class Admin: class Admin:
@ -158,7 +158,7 @@ class DateHierarchyBadOne(models.Model):
class DateHierarchyBadTwo(models.Model): class DateHierarchyBadTwo(models.Model):
"Test date_hieracrhy, must be a field." "Test date_hieracrhy, must be a field."
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
birth_day = models.DateField() birth_day = models.DateField()
class Admin: class Admin:
@ -169,7 +169,7 @@ model_errors += """invalid_admin_options.datehierarchybadtwo: "admin.date_hierar
class DateHierarchyGood(models.Model): class DateHierarchyGood(models.Model):
"Test date_hieracrhy, must be a field." "Test date_hieracrhy, must be a field."
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
birth_day = models.DateField() birth_day = models.DateField()
class Admin: class Admin:
@ -177,7 +177,7 @@ class DateHierarchyGood(models.Model):
class SearchFieldsBadOne(models.Model): class SearchFieldsBadOne(models.Model):
"Test search_fields, must be a list or tuple." "Test search_fields, must be a list or tuple."
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
class Admin: class Admin:
search_fields = ('nonexistent') search_fields = ('nonexistent')
@ -188,7 +188,7 @@ class SearchFieldsBadOne(models.Model):
class SearchFieldsBadTwo(models.Model): class SearchFieldsBadTwo(models.Model):
"Test search_fields, must be a field." "Test search_fields, must be a field."
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
def _last_name(self): def _last_name(self):
return self.first_name return self.first_name
@ -203,8 +203,8 @@ class SearchFieldsBadTwo(models.Model):
class SearchFieldsGood(models.Model): class SearchFieldsGood(models.Model):
"Test search_fields, must be a list or tuple." "Test search_fields, must be a list or tuple."
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
class Admin: class Admin:
search_fields = ['first_name','last_name'] search_fields = ['first_name','last_name']
@ -212,7 +212,7 @@ class SearchFieldsGood(models.Model):
class JsBadOne(models.Model): class JsBadOne(models.Model):
"Test js, must be a list or tuple" "Test js, must be a list or tuple"
name = models.CharField(maxlength=30) name = models.CharField(max_length=30)
class Admin: class Admin:
js = 'test.js' js = 'test.js'
@ -223,7 +223,7 @@ class JsBadOne(models.Model):
class SaveAsBad(models.Model): class SaveAsBad(models.Model):
"Test save_as, should be True or False" "Test save_as, should be True or False"
name = models.CharField(maxlength=30) name = models.CharField(max_length=30)
class Admin: class Admin:
save_as = 'not True or False' save_as = 'not True or False'
@ -234,7 +234,7 @@ class SaveAsBad(models.Model):
class SaveOnTopBad(models.Model): class SaveOnTopBad(models.Model):
"Test save_on_top, should be True or False" "Test save_on_top, should be True or False"
name = models.CharField(maxlength=30) name = models.CharField(max_length=30)
class Admin: class Admin:
save_on_top = 'not True or False' save_on_top = 'not True or False'
@ -245,7 +245,7 @@ class SaveOnTopBad(models.Model):
class ListSelectRelatedBad(models.Model): class ListSelectRelatedBad(models.Model):
"Test list_select_related, should be True or False" "Test list_select_related, should be True or False"
name = models.CharField(maxlength=30) name = models.CharField(max_length=30)
class Admin: class Admin:
list_select_related = 'not True or False' list_select_related = 'not True or False'
@ -256,7 +256,7 @@ class ListSelectRelatedBad(models.Model):
class ListPerPageBad(models.Model): class ListPerPageBad(models.Model):
"Test list_per_page, should be a positive integer value." "Test list_per_page, should be a positive integer value."
name = models.CharField(maxlength=30) name = models.CharField(max_length=30)
class Admin: class Admin:
list_per_page = 89.3 list_per_page = 89.3
@ -267,8 +267,8 @@ class ListPerPageBad(models.Model):
class FieldsBadOne(models.Model): class FieldsBadOne(models.Model):
"Test fields, should be a tuple" "Test fields, should be a tuple"
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
class Admin: class Admin:
fields = 'not a tuple' fields = 'not a tuple'
@ -279,8 +279,8 @@ class FieldsBadOne(models.Model):
class FieldsBadTwo(models.Model): class FieldsBadTwo(models.Model):
"""Test fields, 'fields' dict option is required.""" """Test fields, 'fields' dict option is required."""
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
class Admin: class Admin:
fields = ('Name', {'description': 'this fieldset needs fields'}) fields = ('Name', {'description': 'this fieldset needs fields'})
@ -291,8 +291,8 @@ class FieldsBadTwo(models.Model):
class FieldsBadThree(models.Model): class FieldsBadThree(models.Model):
"""Test fields, 'classes' and 'description' are the only allowable extra dict options.""" """Test fields, 'classes' and 'description' are the only allowable extra dict options."""
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
class Admin: class Admin:
fields = ('Name', {'fields': ('first_name','last_name'),'badoption': 'verybadoption'}) fields = ('Name', {'fields': ('first_name','last_name'),'badoption': 'verybadoption'})
@ -303,8 +303,8 @@ class FieldsBadThree(models.Model):
class FieldsGood(models.Model): class FieldsGood(models.Model):
"Test fields, working example" "Test fields, working example"
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
birth_day = models.DateField() birth_day = models.DateField()
class Admin: class Admin:
@ -315,8 +315,8 @@ class FieldsGood(models.Model):
class OrderingBad(models.Model): class OrderingBad(models.Model):
"Test ordering, must be a field." "Test ordering, must be a field."
first_name = models.CharField(maxlength=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(maxlength=30) last_name = models.CharField(max_length=30)
class Admin: class Admin:
ordering = 'nonexistent' ordering = 'nonexistent'
@ -328,7 +328,7 @@ class OrderingBad(models.Model):
## TODO: Add a manager validator, this should fail gracefully. ## TODO: Add a manager validator, this should fail gracefully.
#class ManagerBad(models.Model): #class ManagerBad(models.Model):
# "Test manager, must be a manager object." # "Test manager, must be a manager object."
# first_name = models.CharField(maxlength=30) # first_name = models.CharField(max_length=30)
# #
# class Admin: # class Admin:
# manager = 'nonexistent' # manager = 'nonexistent'

View File

@ -12,15 +12,15 @@ class Second(models.Model):
# Protect against repetition of #1839, #2415 and #2536. # Protect against repetition of #1839, #2415 and #2536.
class Third(models.Model): class Third(models.Model):
name = models.CharField(maxlength=20) name = models.CharField(max_length=20)
third = models.ForeignKey('self', null=True, related_name='child_set') third = models.ForeignKey('self', null=True, related_name='child_set')
class Parent(models.Model): class Parent(models.Model):
name = models.CharField(maxlength=20) name = models.CharField(max_length=20)
bestchild = models.ForeignKey('Child', null=True, related_name='favored_by') bestchild = models.ForeignKey('Child', null=True, related_name='favored_by')
class Child(models.Model): class Child(models.Model):
name = models.CharField(maxlength=20) name = models.CharField(max_length=20)
parent = models.ForeignKey(Parent) parent = models.ForeignKey(Parent)

View File

@ -0,0 +1,160 @@
# Test access to max_length while still providing full backwards compatibility
# with legacy maxlength attribute.
"""
Don't print out the deprecation warnings during testing.
>>> from warnings import filterwarnings
>>> filterwarnings("ignore")
# legacy_maxlength function
>>> from django.utils.maxlength import legacy_maxlength
>>> legacy_maxlength(None, None)
>>> legacy_maxlength(10, None)
10
>>> legacy_maxlength(None, 10)
10
>>> legacy_maxlength(10, 12)
Traceback (most recent call last):
...
TypeError: field can not take both the max_length argument and the legacy maxlength argument.
>>> legacy_maxlength(0, 10)
Traceback (most recent call last):
...
TypeError: field can not take both the max_length argument and the legacy maxlength argument.
>>> legacy_maxlength(0, None)
0
>>> legacy_maxlength(None, 0)
0
#===============================================================================
# Fields
#===============================================================================
# Set up fields
>>> from django.db.models import fields
>>> new = fields.Field(max_length=15)
>>> old = fields.Field(maxlength=10)
# Ensure both max_length and legacy maxlength are not able to both be specified
>>> fields.Field(maxlength=10, max_length=15)
Traceback (most recent call last):
...
TypeError: field can not take both the max_length argument and the legacy maxlength argument.
# Test max_length
>>> new.max_length
15
>>> old.max_length
10
# Test accessing maxlength
>>> new.maxlength
15
>>> old.maxlength
10
# Test setting maxlength
>>> new.maxlength += 1
>>> old.maxlength += 1
>>> new.max_length
16
>>> old.max_length
11
# SlugField __init__ passes through max_length so test that too
>>> fields.SlugField('new', max_length=15).max_length
15
>>> fields.SlugField('empty').max_length
50
>>> fields.SlugField('old', maxlength=10).max_length
10
#===============================================================================
# (old)forms
#===============================================================================
>>> from django import oldforms
# Test max_length attribute
>>> oldforms.TextField('new', max_length=15).render('')
u'<input type="text" id="id_new" class="vTextField" name="new" size="30" value="" maxlength="15" />'
>>> oldforms.IntegerField('new', max_length=15).render('')
u'<input type="text" id="id_new" class="vIntegerField" name="new" size="10" value="" maxlength="15" />'
>>> oldforms.SmallIntegerField('new', max_length=15).render('')
u'<input type="text" id="id_new" class="vSmallIntegerField" name="new" size="5" value="" maxlength="15" />'
>>> oldforms.PositiveIntegerField('new', max_length=15).render('')
u'<input type="text" id="id_new" class="vPositiveIntegerField" name="new" size="10" value="" maxlength="15" />'
>>> oldforms.PositiveSmallIntegerField('new', max_length=15).render('')
u'<input type="text" id="id_new" class="vPositiveSmallIntegerField" name="new" size="5" value="" maxlength="15" />'
>>> oldforms.DatetimeField('new', max_length=15).render('')
u'<input type="text" id="id_new" class="vDatetimeField" name="new" size="30" value="" maxlength="15" />'
>>> oldforms.EmailField('new', max_length=15).render('')
u'<input type="text" id="id_new" class="vEmailField" name="new" size="50" value="" maxlength="15" />'
>>> oldforms.EmailField('new').render('')
u'<input type="text" id="id_new" class="vEmailField" name="new" size="50" value="" maxlength="75" />'
>>> oldforms.URLField('new', max_length=15).render('')
u'<input type="text" id="id_new" class="vURLField" name="new" size="50" value="" maxlength="15" />'
>>> oldforms.URLField('new').render('')
u'<input type="text" id="id_new" class="vURLField" name="new" size="50" value="" maxlength="200" />'
>>> oldforms.IPAddressField('new', max_length=15).render('')
u'<input type="text" id="id_new" class="vIPAddressField" name="new" size="15" value="" maxlength="15" />'
>>> oldforms.IPAddressField('new').render('')
u'<input type="text" id="id_new" class="vIPAddressField" name="new" size="15" value="" maxlength="15" />'
>>> oldforms.CommaSeparatedIntegerField('new', max_length=15).render('')
u'<input type="text" id="id_new" class="vCommaSeparatedIntegerField" name="new" size="20" value="" maxlength="15" />'
# Test legacy maxlength attribute
>>> oldforms.TextField('old', maxlength=10).render('')
u'<input type="text" id="id_old" class="vTextField" name="old" size="30" value="" maxlength="10" />'
>>> oldforms.IntegerField('old', maxlength=10).render('')
u'<input type="text" id="id_old" class="vIntegerField" name="old" size="10" value="" maxlength="10" />'
>>> oldforms.SmallIntegerField('old', maxlength=10).render('')
u'<input type="text" id="id_old" class="vSmallIntegerField" name="old" size="5" value="" maxlength="10" />'
>>> oldforms.PositiveIntegerField('old', maxlength=10).render('')
u'<input type="text" id="id_old" class="vPositiveIntegerField" name="old" size="10" value="" maxlength="10" />'
>>> oldforms.PositiveSmallIntegerField('old', maxlength=10).render('')
u'<input type="text" id="id_old" class="vPositiveSmallIntegerField" name="old" size="5" value="" maxlength="10" />'
>>> oldforms.DatetimeField('old', maxlength=10).render('')
u'<input type="text" id="id_old" class="vDatetimeField" name="old" size="30" value="" maxlength="10" />'
>>> oldforms.EmailField('old', maxlength=10).render('')
u'<input type="text" id="id_old" class="vEmailField" name="old" size="50" value="" maxlength="10" />'
>>> oldforms.URLField('old', maxlength=10).render('')
u'<input type="text" id="id_old" class="vURLField" name="old" size="50" value="" maxlength="10" />'
>>> oldforms.IPAddressField('old', maxlength=10).render('')
u'<input type="text" id="id_old" class="vIPAddressField" name="old" size="15" value="" maxlength="10" />'
>>> oldforms.CommaSeparatedIntegerField('old', maxlength=10).render('')
u'<input type="text" id="id_old" class="vCommaSeparatedIntegerField" name="old" size="20" value="" maxlength="10" />'
"""
if __name__ == "__main__":
import doctest
doctest.testmod()

View File

@ -7,7 +7,7 @@ CHOICES = (
) )
class Article(models.Model): class Article(models.Model):
headline = models.CharField(maxlength=100, default='Default headline') headline = models.CharField(max_length=100, default='Default headline')
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
status = models.IntegerField(blank=True, null=True, choices=CHOICES) status = models.IntegerField(blank=True, null=True, choices=CHOICES)

View File

@ -1,14 +1,14 @@
from django.db import models from django.db import models
class Poll(models.Model): class Poll(models.Model):
question = models.CharField(maxlength=200) question = models.CharField(max_length=200)
def __unicode__(self): def __unicode__(self):
return u"Q: %s " % self.question return u"Q: %s " % self.question
class Choice(models.Model): class Choice(models.Model):
poll = models.ForeignKey(Poll) poll = models.ForeignKey(Poll)
choice = models.CharField(maxlength=200) choice = models.CharField(max_length=200)
def __unicode__(self): def __unicode__(self):
return u"Choice: %s in poll %s" % (self.choice, self.poll) return u"Choice: %s in poll %s" % (self.choice, self.poll)

View File

@ -1,8 +1,8 @@
from django.db import models from django.db import models
class Place(models.Model): class Place(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
address = models.CharField(maxlength=80) address = models.CharField(max_length=80)
def __unicode__(self): def __unicode__(self):
return u"%s the place" % self.name return u"%s the place" % self.name
@ -16,7 +16,7 @@ class Restaurant(models.Model):
return u"%s the restaurant" % self.place.name return u"%s the restaurant" % self.place.name
class Favorites(models.Model): class Favorites(models.Model):
name = models.CharField(maxlength = 50) name = models.CharField(max_length = 50)
restaurants = models.ManyToManyField(Restaurant) restaurants = models.ManyToManyField(Restaurant)
def __unicode__(self): def __unicode__(self):

View File

@ -16,7 +16,7 @@ class BooleanData(models.Model):
data = models.BooleanField(null=True) data = models.BooleanField(null=True)
class CharData(models.Model): class CharData(models.Model):
data = models.CharField(maxlength=30, null=True) data = models.CharField(max_length=30, null=True)
class DateData(models.Model): class DateData(models.Model):
data = models.DateField(null=True) data = models.DateField(null=True)
@ -90,7 +90,7 @@ class Tag(models.Model):
ordering = ["data"] ordering = ["data"]
class GenericData(models.Model): class GenericData(models.Model):
data = models.CharField(maxlength=30) data = models.CharField(max_length=30)
tags = generic.GenericRelation(Tag) tags = generic.GenericRelation(Tag)
@ -102,13 +102,13 @@ class Anchor(models.Model):
"""This is a model that can be used as """This is a model that can be used as
something for other models to point at""" something for other models to point at"""
data = models.CharField(maxlength=30) data = models.CharField(max_length=30)
class UniqueAnchor(models.Model): class UniqueAnchor(models.Model):
"""This is a model that can be used as """This is a model that can be used as
something for other models to point at""" something for other models to point at"""
data = models.CharField(unique=True, maxlength=30) data = models.CharField(unique=True, max_length=30)
class FKData(models.Model): class FKData(models.Model):
data = models.ForeignKey(Anchor, null=True) data = models.ForeignKey(Anchor, null=True)
@ -144,7 +144,7 @@ class BooleanPKData(models.Model):
data = models.BooleanField(primary_key=True) data = models.BooleanField(primary_key=True)
class CharPKData(models.Model): class CharPKData(models.Model):
data = models.CharField(maxlength=30, primary_key=True) data = models.CharField(max_length=30, primary_key=True)
# class DatePKData(models.Model): # class DatePKData(models.Model):
# data = models.DateField(primary_key=True) # data = models.DateField(primary_key=True)
@ -208,9 +208,9 @@ class USStatePKData(models.Model):
# data = models.XMLField(primary_key=True) # data = models.XMLField(primary_key=True)
class ComplexModel(models.Model): class ComplexModel(models.Model):
field1 = models.CharField(maxlength=10) field1 = models.CharField(max_length=10)
field2 = models.CharField(maxlength=10) field2 = models.CharField(max_length=10)
field3 = models.CharField(maxlength=10) field3 = models.CharField(max_length=10)
# Tests for handling fields with pre_save functions, or # Tests for handling fields with pre_save functions, or
# models with save functions that modify data # models with save functions that modify data

View File

@ -2,14 +2,14 @@
from django.db import models from django.db import models
class Foo(models.Model): class Foo(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
friend = models.CharField(maxlength=50, blank=True) friend = models.CharField(max_length=50, blank=True)
def __unicode__(self): def __unicode__(self):
return "Foo %s" % self.name return "Foo %s" % self.name
class Bar(models.Model): class Bar(models.Model):
name = models.CharField(maxlength=50) name = models.CharField(max_length=50)
normal = models.ForeignKey(Foo, related_name='normal_foo') normal = models.ForeignKey(Foo, related_name='normal_foo')
fwd = models.ForeignKey("Whiz") fwd = models.ForeignKey("Whiz")
back = models.ForeignKey("Foo") back = models.ForeignKey("Foo")
@ -18,20 +18,20 @@ class Bar(models.Model):
return "Bar %s" % self.place.name return "Bar %s" % self.place.name
class Whiz(models.Model): class Whiz(models.Model):
name = models.CharField(maxlength = 50) name = models.CharField(max_length = 50)
def __unicode__(self): def __unicode__(self):
return "Whiz %s" % self.name return "Whiz %s" % self.name
class Child(models.Model): class Child(models.Model):
parent = models.OneToOneField('Base') parent = models.OneToOneField('Base')
name = models.CharField(maxlength = 50) name = models.CharField(max_length = 50)
def __unicode__(self): def __unicode__(self):
return "Child %s" % self.name return "Child %s" % self.name
class Base(models.Model): class Base(models.Model):
name = models.CharField(maxlength = 50) name = models.CharField(max_length = 50)
def __unicode__(self): def __unicode__(self):
return "Base %s" % self.name return "Base %s" % self.name