2006-10-29 04:34:37 +08:00
|
|
|
"""
|
2007-10-28 11:38:08 +08:00
|
|
|
Field classes.
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
|
2007-05-17 05:20:35 +08:00
|
|
|
import datetime
|
2008-03-20 06:29:11 +08:00
|
|
|
import os
|
2007-05-17 05:20:35 +08:00
|
|
|
import re
|
|
|
|
import time
|
2008-07-26 13:18:39 +08:00
|
|
|
import urlparse
|
2009-12-23 01:58:49 +08:00
|
|
|
import warnings
|
2009-12-18 06:06:41 +08:00
|
|
|
from decimal import Decimal, DecimalException
|
2008-07-01 23:10:51 +08:00
|
|
|
try:
|
|
|
|
from cStringIO import StringIO
|
|
|
|
except ImportError:
|
|
|
|
from StringIO import StringIO
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
from django.core.exceptions import ValidationError
|
|
|
|
from django.core import validators
|
2009-12-18 06:06:41 +08:00
|
|
|
import django.utils.copycompat as copy
|
2010-03-01 18:19:24 +08:00
|
|
|
from django.utils import formats
|
2007-11-04 10:08:02 +08:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2008-07-22 11:24:09 +08:00
|
|
|
from django.utils.encoding import smart_unicode, smart_str
|
2010-01-05 10:39:02 +08:00
|
|
|
from django.utils.functional import lazy
|
2007-05-17 05:20:35 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
# Provide this import for backwards compatibility.
|
|
|
|
from django.core.validators import EMPTY_VALUES
|
|
|
|
|
|
|
|
from util import ErrorList
|
|
|
|
from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, \
|
2010-10-01 10:02:58 +08:00
|
|
|
ClearableFileInput, CheckboxInput, Select, NullBooleanSelect, SelectMultiple, \
|
|
|
|
DateInput, DateTimeInput, TimeInput, SplitDateTimeWidget, SplitHiddenDateTimeWidget, \
|
|
|
|
FILE_INPUT_CONTRADICTION
|
2007-07-13 17:09:59 +08:00
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
__all__ = (
|
|
|
|
'Field', 'CharField', 'IntegerField',
|
|
|
|
'DEFAULT_DATE_INPUT_FORMATS', 'DateField',
|
2006-12-15 04:35:32 +08:00
|
|
|
'DEFAULT_TIME_INPUT_FORMATS', 'TimeField',
|
2008-08-24 01:33:09 +08:00
|
|
|
'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField', 'TimeField',
|
2007-10-28 11:38:08 +08:00
|
|
|
'RegexField', 'EmailField', 'FileField', 'ImageField', 'URLField',
|
|
|
|
'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField',
|
2007-05-21 09:29:58 +08:00
|
|
|
'ComboField', 'MultiValueField', 'FloatField', 'DecimalField',
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
'SplitDateTimeField', 'IPAddressField', 'FilePathField', 'SlugField',
|
2008-09-01 04:10:50 +08:00
|
|
|
'TypedChoiceField'
|
2006-10-29 04:34:37 +08:00
|
|
|
)
|
|
|
|
|
2009-12-23 01:58:49 +08:00
|
|
|
def en_format(name):
|
|
|
|
"""
|
|
|
|
Helper function to stay backward compatible.
|
|
|
|
"""
|
|
|
|
from django.conf.locale.en import formats
|
|
|
|
warnings.warn(
|
|
|
|
"`django.forms.fields.DEFAULT_%s` is deprecated; use `django.utils.formats.get_format('%s')` instead." % (name, name),
|
2010-10-11 20:20:07 +08:00
|
|
|
DeprecationWarning
|
2009-12-23 01:58:49 +08:00
|
|
|
)
|
|
|
|
return getattr(formats, name)
|
|
|
|
|
2010-01-05 10:39:02 +08:00
|
|
|
DEFAULT_DATE_INPUT_FORMATS = lazy(lambda: en_format('DATE_INPUT_FORMATS'), tuple, list)()
|
|
|
|
DEFAULT_TIME_INPUT_FORMATS = lazy(lambda: en_format('TIME_INPUT_FORMATS'), tuple, list)()
|
|
|
|
DEFAULT_DATETIME_INPUT_FORMATS = lazy(lambda: en_format('DATETIME_INPUT_FORMATS'), tuple, list)()
|
2007-05-21 09:29:58 +08:00
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
class Field(object):
|
|
|
|
widget = TextInput # Default widget to use when rendering this type of Field.
|
2007-01-09 13:12:25 +08:00
|
|
|
hidden_widget = HiddenInput # Default widget to use when rendering this as "hidden".
|
2010-01-05 11:56:19 +08:00
|
|
|
default_validators = [] # Default set of validators
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2007-11-04 10:08:02 +08:00
|
|
|
'required': _(u'This field is required.'),
|
|
|
|
'invalid': _(u'Enter a valid value.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-11-24 01:40:33 +08:00
|
|
|
# Tracks each time a Field instance is created. Used to retain order.
|
|
|
|
creation_counter = 0
|
|
|
|
|
2007-10-28 13:40:26 +08:00
|
|
|
def __init__(self, required=True, widget=None, label=None, initial=None,
|
2010-01-05 11:56:19 +08:00
|
|
|
help_text=None, error_messages=None, show_hidden_initial=False,
|
2010-03-28 00:43:27 +08:00
|
|
|
validators=[], localize=False):
|
2006-12-28 08:01:52 +08:00
|
|
|
# required -- Boolean that specifies whether the field is required.
|
|
|
|
# True by default.
|
2007-04-01 13:05:59 +08:00
|
|
|
# widget -- A Widget class, or instance of a Widget class, that should
|
|
|
|
# be used for this Field when displaying it. Each Field has a
|
|
|
|
# default Widget that it'll use if you don't specify this. In
|
|
|
|
# most cases, the default widget is TextInput.
|
|
|
|
# label -- A verbose name for this field, for use in displaying this
|
|
|
|
# field in a form. By default, Django will use a "pretty"
|
|
|
|
# version of the form field name, if the Field is part of a
|
|
|
|
# Form.
|
|
|
|
# initial -- A value to use in this Field's initial display. This value
|
|
|
|
# is *not* used as a fallback if data isn't given.
|
2007-01-29 06:10:04 +08:00
|
|
|
# help_text -- An optional string to use as "help text" for this Field.
|
2010-03-28 00:43:27 +08:00
|
|
|
# error_messages -- An optional dictionary to override the default
|
|
|
|
# messages that the field will raise.
|
2008-09-02 05:28:32 +08:00
|
|
|
# show_hidden_initial -- Boolean that specifies if it is needed to render a
|
|
|
|
# hidden widget with initial value after widget.
|
2010-01-05 11:56:19 +08:00
|
|
|
# validators -- List of addtional validators to use
|
2010-03-28 00:43:27 +08:00
|
|
|
# localize -- Boolean that specifies if the field should be localized.
|
2006-12-18 03:04:03 +08:00
|
|
|
if label is not None:
|
|
|
|
label = smart_unicode(label)
|
2006-12-28 08:01:52 +08:00
|
|
|
self.required, self.label, self.initial = required, label, initial
|
2008-09-02 05:28:32 +08:00
|
|
|
self.show_hidden_initial = show_hidden_initial
|
2008-07-30 13:50:24 +08:00
|
|
|
if help_text is None:
|
|
|
|
self.help_text = u''
|
|
|
|
else:
|
|
|
|
self.help_text = smart_unicode(help_text)
|
2006-10-29 04:34:37 +08:00
|
|
|
widget = widget or self.widget
|
|
|
|
if isinstance(widget, type):
|
|
|
|
widget = widget()
|
2006-12-09 02:54:53 +08:00
|
|
|
|
2010-03-28 00:43:27 +08:00
|
|
|
# Trigger the localization machinery if needed.
|
|
|
|
self.localize = localize
|
2010-05-21 22:07:54 +08:00
|
|
|
if self.localize:
|
|
|
|
widget.is_localized = True
|
2010-03-28 00:43:27 +08:00
|
|
|
|
2010-10-01 10:02:58 +08:00
|
|
|
# Let the widget know whether it should display as required.
|
|
|
|
widget.is_required = self.required
|
|
|
|
|
2006-12-09 02:54:53 +08:00
|
|
|
# Hook into self.widget_attrs() for any Field-specific HTML attributes.
|
|
|
|
extra_attrs = self.widget_attrs(widget)
|
|
|
|
if extra_attrs:
|
|
|
|
widget.attrs.update(extra_attrs)
|
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
self.widget = widget
|
|
|
|
|
2006-11-24 01:40:33 +08:00
|
|
|
# Increase the creation counter, and save our local copy.
|
|
|
|
self.creation_counter = Field.creation_counter
|
|
|
|
Field.creation_counter += 1
|
|
|
|
|
2007-12-02 00:50:48 +08:00
|
|
|
messages = {}
|
2010-01-05 11:56:19 +08:00
|
|
|
for c in reversed(self.__class__.__mro__):
|
|
|
|
messages.update(getattr(c, 'default_error_messages', {}))
|
2007-12-02 00:50:48 +08:00
|
|
|
messages.update(error_messages or {})
|
|
|
|
self.error_messages = messages
|
2007-10-28 13:40:26 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
self.validators = self.default_validators + validators
|
|
|
|
|
2010-08-14 20:05:41 +08:00
|
|
|
def prepare_value(self, value):
|
|
|
|
return value
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
return value
|
|
|
|
|
|
|
|
def validate(self, value):
|
|
|
|
if value in validators.EMPTY_VALUES and self.required:
|
|
|
|
raise ValidationError(self.error_messages['required'])
|
|
|
|
|
|
|
|
def run_validators(self, value):
|
|
|
|
if value in validators.EMPTY_VALUES:
|
|
|
|
return
|
|
|
|
errors = []
|
|
|
|
for v in self.validators:
|
|
|
|
try:
|
|
|
|
v(value)
|
|
|
|
except ValidationError, e:
|
|
|
|
if hasattr(e, 'code') and e.code in self.error_messages:
|
|
|
|
message = self.error_messages[e.code]
|
|
|
|
if e.params:
|
|
|
|
message = message % e.params
|
|
|
|
errors.append(message)
|
|
|
|
else:
|
|
|
|
errors.extend(e.messages)
|
|
|
|
if errors:
|
|
|
|
raise ValidationError(errors)
|
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def clean(self, value):
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
2006-11-05 04:49:59 +08:00
|
|
|
Validates the given value and returns its "cleaned" value as an
|
2006-10-29 04:34:37 +08:00
|
|
|
appropriate Python object.
|
|
|
|
|
|
|
|
Raises ValidationError for any errors.
|
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
value = self.to_python(value)
|
|
|
|
self.validate(value)
|
|
|
|
self.run_validators(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
return value
|
|
|
|
|
2010-10-01 10:02:58 +08:00
|
|
|
def bound_data(self, data, initial):
|
|
|
|
"""
|
|
|
|
Return the value that should be shown for this field on render of a
|
|
|
|
bound form, given the submitted POST data for the field and the initial
|
|
|
|
data, if any.
|
|
|
|
|
|
|
|
For most fields, this will simply be data; FileFields need to handle it
|
|
|
|
a bit differently.
|
|
|
|
"""
|
|
|
|
return data
|
|
|
|
|
2006-12-09 02:54:53 +08:00
|
|
|
def widget_attrs(self, widget):
|
|
|
|
"""
|
|
|
|
Given a Widget instance (*not* a Widget class), returns a dictionary of
|
|
|
|
any HTML attributes that should be added to the Widget, based on this
|
|
|
|
Field.
|
|
|
|
"""
|
|
|
|
return {}
|
|
|
|
|
2007-09-14 11:29:39 +08:00
|
|
|
def __deepcopy__(self, memo):
|
|
|
|
result = copy.copy(self)
|
|
|
|
memo[id(self)] = result
|
|
|
|
result.widget = copy.deepcopy(self.widget, memo)
|
|
|
|
return result
|
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
class CharField(Field):
|
2007-01-29 06:10:04 +08:00
|
|
|
def __init__(self, max_length=None, min_length=None, *args, **kwargs):
|
2006-10-29 04:34:37 +08:00
|
|
|
self.max_length, self.min_length = max_length, min_length
|
2007-01-29 06:10:04 +08:00
|
|
|
super(CharField, self).__init__(*args, **kwargs)
|
2010-01-05 11:56:19 +08:00
|
|
|
if min_length is not None:
|
|
|
|
self.validators.append(validators.MinLengthValidator(min_length))
|
|
|
|
if max_length is not None:
|
|
|
|
self.validators.append(validators.MaxLengthValidator(max_length))
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
"Returns a Unicode object."
|
|
|
|
if value in validators.EMPTY_VALUES:
|
2007-01-21 01:31:45 +08:00
|
|
|
return u''
|
2010-01-05 11:56:19 +08:00
|
|
|
return smart_unicode(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-12-09 02:54:53 +08:00
|
|
|
def widget_attrs(self, widget):
|
|
|
|
if self.max_length is not None and isinstance(widget, (TextInput, PasswordInput)):
|
2007-08-05 13:14:46 +08:00
|
|
|
# The HTML attribute is maxlength, not max_length.
|
2006-12-09 02:54:53 +08:00
|
|
|
return {'maxlength': str(self.max_length)}
|
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
class IntegerField(Field):
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2007-11-04 10:08:02 +08:00
|
|
|
'invalid': _(u'Enter a whole number.'),
|
2010-01-05 11:56:19 +08:00
|
|
|
'max_value': _(u'Ensure this value is less than or equal to %(limit_value)s.'),
|
|
|
|
'min_value': _(u'Ensure this value is greater than or equal to %(limit_value)s.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2007-01-29 06:10:04 +08:00
|
|
|
def __init__(self, max_value=None, min_value=None, *args, **kwargs):
|
|
|
|
super(IntegerField, self).__init__(*args, **kwargs)
|
2006-12-16 07:18:47 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
if max_value is not None:
|
|
|
|
self.validators.append(validators.MaxValueValidator(max_value))
|
|
|
|
if min_value is not None:
|
|
|
|
self.validators.append(validators.MinValueValidator(min_value))
|
|
|
|
|
|
|
|
def to_python(self, value):
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
Validates that int() can be called on the input. Returns the result
|
2007-01-13 13:08:07 +08:00
|
|
|
of int(). Returns None for empty values.
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
value = super(IntegerField, self).to_python(value)
|
|
|
|
if value in validators.EMPTY_VALUES:
|
2007-01-13 13:08:07 +08:00
|
|
|
return None
|
2010-03-28 00:43:27 +08:00
|
|
|
if self.localize:
|
|
|
|
value = formats.sanitize_separators(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
try:
|
2007-09-15 19:45:19 +08:00
|
|
|
value = int(str(value))
|
2006-10-29 04:34:37 +08:00
|
|
|
except (ValueError, TypeError):
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'])
|
2006-12-16 07:18:47 +08:00
|
|
|
return value
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
class FloatField(IntegerField):
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2007-11-04 10:08:02 +08:00
|
|
|
'invalid': _(u'Enter a number.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
2007-05-21 09:29:58 +08:00
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
Validates that float() can be called on the input. Returns the result
|
|
|
|
of float(). Returns None for empty values.
|
2007-05-21 09:29:58 +08:00
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
value = super(IntegerField, self).to_python(value)
|
|
|
|
if value in validators.EMPTY_VALUES:
|
2007-05-21 09:29:58 +08:00
|
|
|
return None
|
2010-03-28 00:43:27 +08:00
|
|
|
if self.localize:
|
|
|
|
value = formats.sanitize_separators(value)
|
2007-05-21 09:29:58 +08:00
|
|
|
try:
|
2010-03-01 18:19:24 +08:00
|
|
|
value = float(value)
|
2007-05-21 09:29:58 +08:00
|
|
|
except (ValueError, TypeError):
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'])
|
2007-05-21 09:29:58 +08:00
|
|
|
return value
|
|
|
|
|
|
|
|
class DecimalField(Field):
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2007-11-04 10:08:02 +08:00
|
|
|
'invalid': _(u'Enter a number.'),
|
2010-01-05 11:56:19 +08:00
|
|
|
'max_value': _(u'Ensure this value is less than or equal to %(limit_value)s.'),
|
|
|
|
'min_value': _(u'Ensure this value is greater than or equal to %(limit_value)s.'),
|
2007-11-04 10:08:02 +08:00
|
|
|
'max_digits': _('Ensure that there are no more than %s digits in total.'),
|
|
|
|
'max_decimal_places': _('Ensure that there are no more than %s decimal places.'),
|
|
|
|
'max_whole_digits': _('Ensure that there are no more than %s digits before the decimal point.')
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2007-05-21 09:29:58 +08:00
|
|
|
def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs):
|
|
|
|
self.max_digits, self.decimal_places = max_digits, decimal_places
|
|
|
|
Field.__init__(self, *args, **kwargs)
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
if max_value is not None:
|
|
|
|
self.validators.append(validators.MaxValueValidator(max_value))
|
|
|
|
if min_value is not None:
|
|
|
|
self.validators.append(validators.MinValueValidator(min_value))
|
|
|
|
|
|
|
|
def to_python(self, value):
|
2007-05-21 09:29:58 +08:00
|
|
|
"""
|
|
|
|
Validates that the input is a decimal number. Returns a Decimal
|
|
|
|
instance. Returns None for empty values. Ensures that there are no more
|
|
|
|
than max_digits in the number, and no more than decimal_places digits
|
|
|
|
after the decimal point.
|
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
if value in validators.EMPTY_VALUES:
|
2007-05-21 09:29:58 +08:00
|
|
|
return None
|
2010-03-28 00:43:27 +08:00
|
|
|
if self.localize:
|
|
|
|
value = formats.sanitize_separators(value)
|
2007-11-30 03:30:38 +08:00
|
|
|
value = smart_str(value).strip()
|
2007-07-13 17:09:59 +08:00
|
|
|
try:
|
2010-03-01 18:19:24 +08:00
|
|
|
value = Decimal(value)
|
2007-07-13 17:09:59 +08:00
|
|
|
except DecimalException:
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'])
|
2010-01-05 11:56:19 +08:00
|
|
|
return value
|
2008-08-16 04:09:47 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def validate(self, value):
|
|
|
|
super(DecimalField, self).validate(value)
|
|
|
|
if value in validators.EMPTY_VALUES:
|
|
|
|
return
|
2010-02-22 22:38:44 +08:00
|
|
|
# Check for NaN, Inf and -Inf values. We can't compare directly for NaN,
|
|
|
|
# since it is never equal to itself. However, NaN is the only value that
|
|
|
|
# isn't equal to itself, so we can use this to identify NaN
|
|
|
|
if value != value or value == Decimal("Inf") or value == Decimal("-Inf"):
|
|
|
|
raise ValidationError(self.error_messages['invalid'])
|
2008-08-16 04:09:47 +08:00
|
|
|
sign, digittuple, exponent = value.as_tuple()
|
|
|
|
decimals = abs(exponent)
|
|
|
|
# digittuple doesn't include any leading zeros.
|
|
|
|
digits = len(digittuple)
|
2008-11-11 03:52:53 +08:00
|
|
|
if decimals > digits:
|
2008-08-16 04:09:47 +08:00
|
|
|
# We have leading zeros up to or past the decimal point. Count
|
2009-04-16 22:24:27 +08:00
|
|
|
# everything past the decimal point as a digit. We do not count
|
|
|
|
# 0 before the decimal point as a digit since that would mean
|
2008-11-11 03:52:53 +08:00
|
|
|
# we would not allow max_digits = decimal_places.
|
|
|
|
digits = decimals
|
2008-08-16 04:09:47 +08:00
|
|
|
whole_digits = digits - decimals
|
|
|
|
|
|
|
|
if self.max_digits is not None and digits > self.max_digits:
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['max_digits'] % self.max_digits)
|
2007-05-21 09:29:58 +08:00
|
|
|
if self.decimal_places is not None and decimals > self.decimal_places:
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['max_decimal_places'] % self.decimal_places)
|
2008-08-16 04:09:47 +08:00
|
|
|
if self.max_digits is not None and self.decimal_places is not None and whole_digits > (self.max_digits - self.decimal_places):
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['max_whole_digits'] % (self.max_digits - self.decimal_places))
|
2007-05-21 09:29:58 +08:00
|
|
|
return value
|
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
class DateField(Field):
|
2009-04-16 22:24:27 +08:00
|
|
|
widget = DateInput
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2007-11-04 10:08:02 +08:00
|
|
|
'invalid': _(u'Enter a valid date.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2007-01-29 06:10:04 +08:00
|
|
|
def __init__(self, input_formats=None, *args, **kwargs):
|
|
|
|
super(DateField, self).__init__(*args, **kwargs)
|
2009-12-23 01:58:49 +08:00
|
|
|
self.input_formats = input_formats
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
Validates that the input can be converted to a date. Returns a Python
|
|
|
|
datetime.date object.
|
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
if value in validators.EMPTY_VALUES:
|
2006-10-29 04:34:37 +08:00
|
|
|
return None
|
|
|
|
if isinstance(value, datetime.datetime):
|
|
|
|
return value.date()
|
|
|
|
if isinstance(value, datetime.date):
|
|
|
|
return value
|
2010-03-01 18:19:24 +08:00
|
|
|
for format in self.input_formats or formats.get_format('DATE_INPUT_FORMATS'):
|
2006-10-29 04:34:37 +08:00
|
|
|
try:
|
|
|
|
return datetime.date(*time.strptime(value, format)[:3])
|
|
|
|
except ValueError:
|
|
|
|
continue
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'])
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-12-15 04:35:32 +08:00
|
|
|
class TimeField(Field):
|
2008-08-24 01:36:42 +08:00
|
|
|
widget = TimeInput
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2007-11-04 10:08:02 +08:00
|
|
|
'invalid': _(u'Enter a valid time.')
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2007-01-29 06:10:04 +08:00
|
|
|
def __init__(self, input_formats=None, *args, **kwargs):
|
|
|
|
super(TimeField, self).__init__(*args, **kwargs)
|
2009-12-23 01:58:49 +08:00
|
|
|
self.input_formats = input_formats
|
2006-12-15 04:35:32 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
2006-12-15 04:35:32 +08:00
|
|
|
"""
|
|
|
|
Validates that the input can be converted to a time. Returns a Python
|
|
|
|
datetime.time object.
|
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
if value in validators.EMPTY_VALUES:
|
2006-12-15 04:35:32 +08:00
|
|
|
return None
|
|
|
|
if isinstance(value, datetime.time):
|
|
|
|
return value
|
2010-03-01 18:19:24 +08:00
|
|
|
for format in self.input_formats or formats.get_format('TIME_INPUT_FORMATS'):
|
2006-12-15 04:35:32 +08:00
|
|
|
try:
|
|
|
|
return datetime.time(*time.strptime(value, format)[3:6])
|
|
|
|
except ValueError:
|
|
|
|
continue
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'])
|
2006-12-15 04:35:32 +08:00
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
class DateTimeField(Field):
|
2007-10-21 22:50:47 +08:00
|
|
|
widget = DateTimeInput
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2007-11-04 10:08:02 +08:00
|
|
|
'invalid': _(u'Enter a valid date/time.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
2007-10-21 22:50:47 +08:00
|
|
|
|
2007-01-29 06:10:04 +08:00
|
|
|
def __init__(self, input_formats=None, *args, **kwargs):
|
|
|
|
super(DateTimeField, self).__init__(*args, **kwargs)
|
2009-12-23 01:58:49 +08:00
|
|
|
self.input_formats = input_formats
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
Validates that the input can be converted to a datetime. Returns a
|
|
|
|
Python datetime.datetime object.
|
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
if value in validators.EMPTY_VALUES:
|
2006-10-29 04:34:37 +08:00
|
|
|
return None
|
|
|
|
if isinstance(value, datetime.datetime):
|
|
|
|
return value
|
|
|
|
if isinstance(value, datetime.date):
|
|
|
|
return datetime.datetime(value.year, value.month, value.day)
|
2007-10-21 22:50:20 +08:00
|
|
|
if isinstance(value, list):
|
|
|
|
# Input comes from a SplitDateTimeWidget, for example. So, it's two
|
|
|
|
# components: date and time.
|
|
|
|
if len(value) != 2:
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'])
|
2010-09-12 05:26:19 +08:00
|
|
|
if value[0] in validators.EMPTY_VALUES and value[1] in validators.EMPTY_VALUES:
|
|
|
|
return None
|
2007-10-21 22:50:20 +08:00
|
|
|
value = '%s %s' % tuple(value)
|
2010-03-01 18:19:24 +08:00
|
|
|
for format in self.input_formats or formats.get_format('DATETIME_INPUT_FORMATS'):
|
2006-10-29 04:34:37 +08:00
|
|
|
try:
|
|
|
|
return datetime.datetime(*time.strptime(value, format)[:6])
|
|
|
|
except ValueError:
|
|
|
|
continue
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'])
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2007-07-13 20:03:20 +08:00
|
|
|
class RegexField(CharField):
|
2007-01-29 06:10:04 +08:00
|
|
|
def __init__(self, regex, max_length=None, min_length=None, error_message=None, *args, **kwargs):
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
regex can be either a string or a compiled regular expression object.
|
|
|
|
error_message is an optional error message to use, if
|
|
|
|
'Enter a valid value' is too generic for you.
|
|
|
|
"""
|
2007-10-28 13:40:26 +08:00
|
|
|
# error_message is just kept for backwards compatibility:
|
|
|
|
if error_message:
|
|
|
|
error_messages = kwargs.get('error_messages') or {}
|
|
|
|
error_messages['invalid'] = error_message
|
|
|
|
kwargs['error_messages'] = error_messages
|
2007-07-13 20:03:20 +08:00
|
|
|
super(RegexField, self).__init__(max_length, min_length, *args, **kwargs)
|
2006-10-29 04:34:37 +08:00
|
|
|
if isinstance(regex, basestring):
|
|
|
|
regex = re.compile(regex)
|
|
|
|
self.regex = regex
|
2010-01-05 11:56:19 +08:00
|
|
|
self.validators.append(validators.RegexValidator(regex=regex))
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
class EmailField(CharField):
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2007-11-04 10:08:02 +08:00
|
|
|
'invalid': _(u'Enter a valid e-mail address.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
2010-01-05 11:56:19 +08:00
|
|
|
default_validators = [validators.validate_email]
|
2007-08-06 21:58:56 +08:00
|
|
|
|
2010-10-07 23:50:36 +08:00
|
|
|
def clean(self, value):
|
|
|
|
value = self.to_python(value).strip()
|
|
|
|
return super(EmailField, self).clean(value)
|
|
|
|
|
2007-08-06 21:58:56 +08:00
|
|
|
class FileField(Field):
|
2010-10-01 10:02:58 +08:00
|
|
|
widget = ClearableFileInput
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2007-11-04 10:08:02 +08:00
|
|
|
'invalid': _(u"No file was submitted. Check the encoding type on the form."),
|
|
|
|
'missing': _(u"No file was submitted."),
|
|
|
|
'empty': _(u"The submitted file is empty."),
|
2009-03-31 06:52:16 +08:00
|
|
|
'max_length': _(u'Ensure this filename has at most %(max)d characters (it has %(length)d).'),
|
2010-10-01 10:02:58 +08:00
|
|
|
'contradiction': _(u'Please either submit a file or check the clear checkbox, not both.')
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2007-08-06 21:58:56 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
2009-03-31 06:52:16 +08:00
|
|
|
self.max_length = kwargs.pop('max_length', None)
|
2007-08-06 21:58:56 +08:00
|
|
|
super(FileField, self).__init__(*args, **kwargs)
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, data):
|
|
|
|
if data in validators.EMPTY_VALUES:
|
2007-08-06 21:58:56 +08:00
|
|
|
return None
|
2008-07-01 23:10:51 +08:00
|
|
|
|
Fixed #7830 -- Removed all of the remaining, deprecated, non-oldforms features:
* Support for representing files as strings was removed. Use `django.core.files.base.ContentFile` instead.
* Support for representing uploaded files as dictionaries was removed. Use `django.core.files.uploadedfile.SimpleUploadedFile` instead.
* The `filename`, `file_name`, `file_size`, and `chuck` properties of `UploadedFile` were removed. Use the `name`, `name`, `size`, and `chunks` properties instead, respectively.
* The `get_FIELD_filename`, `get_FIELD_url`, `get_FIELD_size`, and `save_FIELD_file` methods for Models with `FileField` fields were removed. Instead, use the `path`, `url`, and `size` attributes and `save` method on the field itself, respectively.
* The `get_FIELD_width` and `get_FIELD_height` methods for Models with `ImageField` fields were removed. Use the `width` and `height` attributes on the field itself instead.
* The dispatcher `connect`, `disconnect`, `send`, and `sendExact` functions were removed. Use the signal object's own `connect`, `disconnect`, `send`, and `send` methods instead, respectively.
* The `form_for_model` and `form_for_instance` functions were removed. Use a `ModelForm` subclass instead.
* Support for importing `django.newforms` was removed. Use `django.forms` instead.
* Support for importing `django.utils.images` was removed. Use `django.core.files.images` instead.
* Support for the `follow` argument in the `create_object` and `update_object` generic views was removed. Use the `django.forms` package and the new `form_class` argument instead.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8291 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-11 05:10:47 +08:00
|
|
|
# UploadedFile objects should have name and size attributes.
|
2007-08-06 21:58:56 +08:00
|
|
|
try:
|
2008-07-08 07:16:00 +08:00
|
|
|
file_name = data.name
|
|
|
|
file_size = data.size
|
2008-07-01 23:10:51 +08:00
|
|
|
except AttributeError:
|
2008-07-08 07:16:00 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'])
|
2008-07-01 23:10:51 +08:00
|
|
|
|
2009-03-31 06:52:16 +08:00
|
|
|
if self.max_length is not None and len(file_name) > self.max_length:
|
|
|
|
error_values = {'max': self.max_length, 'length': len(file_name)}
|
|
|
|
raise ValidationError(self.error_messages['max_length'] % error_values)
|
2008-07-01 23:10:51 +08:00
|
|
|
if not file_name:
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'])
|
2008-07-01 23:10:51 +08:00
|
|
|
if not file_size:
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['empty'])
|
2008-07-01 23:10:51 +08:00
|
|
|
|
2008-07-08 07:16:00 +08:00
|
|
|
return data
|
2007-08-06 21:58:56 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def clean(self, data, initial=None):
|
2010-10-01 10:02:58 +08:00
|
|
|
# If the widget got contradictory inputs, we raise a validation error
|
|
|
|
if data is FILE_INPUT_CONTRADICTION:
|
|
|
|
raise ValidationError(self.error_messages['contradiction'])
|
|
|
|
# False means the field value should be cleared; further validation is
|
|
|
|
# not needed.
|
|
|
|
if data is False:
|
|
|
|
if not self.required:
|
|
|
|
return False
|
|
|
|
# If the field is required, clearing is not possible (the widget
|
|
|
|
# shouldn't return False data in that case anyway). False is not
|
|
|
|
# in validators.EMPTY_VALUES; if a False value makes it this far
|
|
|
|
# it should be validated from here on out as None (so it will be
|
|
|
|
# caught by the required check).
|
|
|
|
data = None
|
2010-01-05 11:56:19 +08:00
|
|
|
if not data and initial:
|
|
|
|
return initial
|
|
|
|
return super(FileField, self).clean(data)
|
|
|
|
|
2010-10-01 10:02:58 +08:00
|
|
|
def bound_data(self, data, initial):
|
|
|
|
if data in (None, FILE_INPUT_CONTRADICTION):
|
|
|
|
return initial
|
|
|
|
return data
|
|
|
|
|
2007-08-06 21:58:56 +08:00
|
|
|
class ImageField(FileField):
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2007-11-04 10:08:02 +08:00
|
|
|
'invalid_image': _(u"Upload a valid image. The file you uploaded was either not an image or a corrupted image."),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, data):
|
2007-08-06 21:58:56 +08:00
|
|
|
"""
|
|
|
|
Checks that the file-upload field data contains a valid image (GIF, JPG,
|
|
|
|
PNG, possibly others -- whatever the Python Imaging Library supports).
|
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
f = super(ImageField, self).to_python(data)
|
2007-08-06 21:58:56 +08:00
|
|
|
if f is None:
|
|
|
|
return None
|
2010-02-22 22:38:44 +08:00
|
|
|
|
2010-02-15 02:28:28 +08:00
|
|
|
# Try to import PIL in either of the two ways it can end up installed.
|
|
|
|
try:
|
|
|
|
from PIL import Image
|
|
|
|
except ImportError:
|
|
|
|
import Image
|
2008-07-01 23:10:51 +08:00
|
|
|
|
|
|
|
# We need to get a file object for PIL. We might have a path or we might
|
|
|
|
# have to read the data into memory.
|
|
|
|
if hasattr(data, 'temporary_file_path'):
|
|
|
|
file = data.temporary_file_path()
|
|
|
|
else:
|
|
|
|
if hasattr(data, 'read'):
|
|
|
|
file = StringIO(data.read())
|
|
|
|
else:
|
|
|
|
file = StringIO(data['content'])
|
|
|
|
|
2007-08-06 21:58:56 +08:00
|
|
|
try:
|
2007-09-14 15:18:27 +08:00
|
|
|
# load() is the only method that can spot a truncated JPEG,
|
|
|
|
# but it cannot be called sanely after verify()
|
2008-07-01 23:10:51 +08:00
|
|
|
trial_image = Image.open(file)
|
2007-09-14 15:18:27 +08:00
|
|
|
trial_image.load()
|
2008-07-01 23:10:51 +08:00
|
|
|
|
|
|
|
# Since we're about to use the file again we have to reset the
|
|
|
|
# file object if possible.
|
|
|
|
if hasattr(file, 'reset'):
|
|
|
|
file.reset()
|
|
|
|
|
2007-09-14 15:18:27 +08:00
|
|
|
# verify() is the only method that can spot a corrupt PNG,
|
|
|
|
# but it must be called immediately after the constructor
|
2008-07-01 23:10:51 +08:00
|
|
|
trial_image = Image.open(file)
|
2007-09-14 15:18:27 +08:00
|
|
|
trial_image.verify()
|
Fixed #7830 -- Removed all of the remaining, deprecated, non-oldforms features:
* Support for representing files as strings was removed. Use `django.core.files.base.ContentFile` instead.
* Support for representing uploaded files as dictionaries was removed. Use `django.core.files.uploadedfile.SimpleUploadedFile` instead.
* The `filename`, `file_name`, `file_size`, and `chuck` properties of `UploadedFile` were removed. Use the `name`, `name`, `size`, and `chunks` properties instead, respectively.
* The `get_FIELD_filename`, `get_FIELD_url`, `get_FIELD_size`, and `save_FIELD_file` methods for Models with `FileField` fields were removed. Instead, use the `path`, `url`, and `size` attributes and `save` method on the field itself, respectively.
* The `get_FIELD_width` and `get_FIELD_height` methods for Models with `ImageField` fields were removed. Use the `width` and `height` attributes on the field itself instead.
* The dispatcher `connect`, `disconnect`, `send`, and `sendExact` functions were removed. Use the signal object's own `connect`, `disconnect`, `send`, and `send` methods instead, respectively.
* The `form_for_model` and `form_for_instance` functions were removed. Use a `ModelForm` subclass instead.
* Support for importing `django.newforms` was removed. Use `django.forms` instead.
* Support for importing `django.utils.images` was removed. Use `django.core.files.images` instead.
* Support for the `follow` argument in the `create_object` and `update_object` generic views was removed. Use the `django.forms` package and the new `form_class` argument instead.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8291 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-11 05:10:47 +08:00
|
|
|
except ImportError:
|
2008-07-21 19:52:11 +08:00
|
|
|
# Under PyPy, it is possible to import PIL. However, the underlying
|
Fixed #7830 -- Removed all of the remaining, deprecated, non-oldforms features:
* Support for representing files as strings was removed. Use `django.core.files.base.ContentFile` instead.
* Support for representing uploaded files as dictionaries was removed. Use `django.core.files.uploadedfile.SimpleUploadedFile` instead.
* The `filename`, `file_name`, `file_size`, and `chuck` properties of `UploadedFile` were removed. Use the `name`, `name`, `size`, and `chunks` properties instead, respectively.
* The `get_FIELD_filename`, `get_FIELD_url`, `get_FIELD_size`, and `save_FIELD_file` methods for Models with `FileField` fields were removed. Instead, use the `path`, `url`, and `size` attributes and `save` method on the field itself, respectively.
* The `get_FIELD_width` and `get_FIELD_height` methods for Models with `ImageField` fields were removed. Use the `width` and `height` attributes on the field itself instead.
* The dispatcher `connect`, `disconnect`, `send`, and `sendExact` functions were removed. Use the signal object's own `connect`, `disconnect`, `send`, and `send` methods instead, respectively.
* The `form_for_model` and `form_for_instance` functions were removed. Use a `ModelForm` subclass instead.
* Support for importing `django.newforms` was removed. Use `django.forms` instead.
* Support for importing `django.utils.images` was removed. Use `django.core.files.images` instead.
* Support for the `follow` argument in the `create_object` and `update_object` generic views was removed. Use the `django.forms` package and the new `form_class` argument instead.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8291 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-11 05:10:47 +08:00
|
|
|
# _imaging C module isn't available, so an ImportError will be
|
|
|
|
# raised. Catch and re-raise.
|
2008-07-21 19:52:11 +08:00
|
|
|
raise
|
2007-09-14 15:18:27 +08:00
|
|
|
except Exception: # Python Imaging Library doesn't recognize it as an image
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid_image'])
|
2008-07-13 04:43:38 +08:00
|
|
|
if hasattr(f, 'seek') and callable(f.seek):
|
|
|
|
f.seek(0)
|
2007-08-06 21:58:56 +08:00
|
|
|
return f
|
2007-09-09 03:26:15 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
class URLField(CharField):
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2007-11-04 10:08:02 +08:00
|
|
|
'invalid': _(u'Enter a valid URL.'),
|
|
|
|
'invalid_link': _(u'This URL appears to be a broken link.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2007-01-29 06:10:04 +08:00
|
|
|
def __init__(self, max_length=None, min_length=None, verify_exists=False,
|
2010-01-05 11:56:19 +08:00
|
|
|
validator_user_agent=validators.URL_VALIDATOR_USER_AGENT, *args, **kwargs):
|
|
|
|
super(URLField, self).__init__(max_length, min_length, *args,
|
2007-10-28 13:40:26 +08:00
|
|
|
**kwargs)
|
2010-01-05 11:56:19 +08:00
|
|
|
self.validators.append(validators.URLValidator(verify_exists=verify_exists, validator_user_agent=validator_user_agent))
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
if value:
|
|
|
|
url_fields = list(urlparse.urlsplit(value))
|
2010-11-21 18:08:28 +08:00
|
|
|
if not url_fields[0]:
|
|
|
|
# If no URL scheme given, assume http://
|
|
|
|
url_fields[0] = 'http'
|
|
|
|
if not url_fields[1]:
|
|
|
|
# Assume that if no domain is provided, that the path segment
|
|
|
|
# contains the domain.
|
|
|
|
url_fields[1] = url_fields[2]
|
|
|
|
url_fields[2] = ''
|
|
|
|
# Rebuild the url_fields list, since the domain segment may now
|
|
|
|
# contain the path too.
|
|
|
|
value = urlparse.urlunsplit(url_fields)
|
|
|
|
url_fields = list(urlparse.urlsplit(value))
|
2010-01-05 11:56:19 +08:00
|
|
|
if not url_fields[2]:
|
|
|
|
# the path portion may need to be added before query params
|
|
|
|
url_fields[2] = '/'
|
2010-11-21 18:08:28 +08:00
|
|
|
value = urlparse.urlunsplit(url_fields)
|
2010-01-05 11:56:19 +08:00
|
|
|
return super(URLField, self).to_python(value)
|
2006-11-02 07:52:43 +08:00
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
class BooleanField(Field):
|
|
|
|
widget = CheckboxInput
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
2007-11-30 03:22:03 +08:00
|
|
|
"""Returns a Python boolean object."""
|
|
|
|
# Explicitly check for the string 'False', which is what a hidden field
|
2009-05-02 22:52:34 +08:00
|
|
|
# will submit for False. Also check for '0', since this is what
|
|
|
|
# RadioSelect will provide. Because bool("True") == bool('1') == True,
|
|
|
|
# we don't need to handle that explicitly.
|
|
|
|
if value in ('False', '0'):
|
2008-06-30 18:44:56 +08:00
|
|
|
value = False
|
|
|
|
else:
|
|
|
|
value = bool(value)
|
2010-01-05 11:56:19 +08:00
|
|
|
value = super(BooleanField, self).to_python(value)
|
2008-06-30 18:44:56 +08:00
|
|
|
if not value and self.required:
|
|
|
|
raise ValidationError(self.error_messages['required'])
|
|
|
|
return value
|
2006-11-02 11:16:12 +08:00
|
|
|
|
2007-01-24 13:23:19 +08:00
|
|
|
class NullBooleanField(BooleanField):
|
|
|
|
"""
|
|
|
|
A field whose valid values are None, True and False. Invalid values are
|
|
|
|
cleaned to None.
|
|
|
|
"""
|
|
|
|
widget = NullBooleanSelect
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
2008-08-28 23:06:18 +08:00
|
|
|
"""
|
|
|
|
Explicitly checks for the string 'True' and 'False', which is what a
|
2009-05-02 22:52:34 +08:00
|
|
|
hidden field will submit for True and False, and for '1' and '0', which
|
|
|
|
is what a RadioField will submit. Unlike the Booleanfield we need to
|
|
|
|
explicitly check for True, because we are not using the bool() function
|
2008-08-28 23:06:18 +08:00
|
|
|
"""
|
2009-05-02 22:52:34 +08:00
|
|
|
if value in (True, 'True', '1'):
|
2008-08-28 23:06:18 +08:00
|
|
|
return True
|
2009-05-02 22:52:34 +08:00
|
|
|
elif value in (False, 'False', '0'):
|
2008-08-28 23:06:18 +08:00
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return None
|
2007-01-24 13:23:19 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def validate(self, value):
|
|
|
|
pass
|
|
|
|
|
2006-11-02 11:16:12 +08:00
|
|
|
class ChoiceField(Field):
|
2007-04-21 13:43:32 +08:00
|
|
|
widget = Select
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2008-07-19 15:53:02 +08:00
|
|
|
'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
def __init__(self, choices=(), required=True, widget=None, label=None,
|
|
|
|
initial=None, help_text=None, *args, **kwargs):
|
2010-02-22 22:38:44 +08:00
|
|
|
super(ChoiceField, self).__init__(required=required, widget=widget, label=label,
|
2010-01-05 11:56:19 +08:00
|
|
|
initial=initial, help_text=help_text, *args, **kwargs)
|
2006-11-02 11:16:12 +08:00
|
|
|
self.choices = choices
|
|
|
|
|
2007-01-21 09:29:01 +08:00
|
|
|
def _get_choices(self):
|
|
|
|
return self._choices
|
|
|
|
|
|
|
|
def _set_choices(self, value):
|
|
|
|
# Setting choices also sets the choices on the widget.
|
2007-02-20 11:05:09 +08:00
|
|
|
# choices can be any iterable, but we call list() on it because
|
|
|
|
# it will be consumed more than once.
|
|
|
|
self._choices = self.widget.choices = list(value)
|
2007-01-21 09:29:01 +08:00
|
|
|
|
|
|
|
choices = property(_get_choices, _set_choices)
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
"Returns a Unicode object."
|
|
|
|
if value in validators.EMPTY_VALUES:
|
|
|
|
return u''
|
|
|
|
return smart_unicode(value)
|
|
|
|
|
|
|
|
def validate(self, value):
|
2006-11-02 11:16:12 +08:00
|
|
|
"""
|
|
|
|
Validates that the input is in self.choices.
|
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
super(ChoiceField, self).validate(value)
|
|
|
|
if value and not self.valid_value(value):
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid_choice'] % {'value': value})
|
2006-11-02 11:16:12 +08:00
|
|
|
|
2008-07-19 15:53:02 +08:00
|
|
|
def valid_value(self, value):
|
|
|
|
"Check to see if the provided value is a valid choice"
|
|
|
|
for k, v in self.choices:
|
2010-02-24 02:27:51 +08:00
|
|
|
if isinstance(v, (list, tuple)):
|
2008-07-19 15:53:02 +08:00
|
|
|
# This is an optgroup, so look inside the group for options
|
|
|
|
for k2, v2 in v:
|
|
|
|
if value == smart_unicode(k2):
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
if value == smart_unicode(k):
|
|
|
|
return True
|
|
|
|
return False
|
Fixed #7830 -- Removed all of the remaining, deprecated, non-oldforms features:
* Support for representing files as strings was removed. Use `django.core.files.base.ContentFile` instead.
* Support for representing uploaded files as dictionaries was removed. Use `django.core.files.uploadedfile.SimpleUploadedFile` instead.
* The `filename`, `file_name`, `file_size`, and `chuck` properties of `UploadedFile` were removed. Use the `name`, `name`, `size`, and `chunks` properties instead, respectively.
* The `get_FIELD_filename`, `get_FIELD_url`, `get_FIELD_size`, and `save_FIELD_file` methods for Models with `FileField` fields were removed. Instead, use the `path`, `url`, and `size` attributes and `save` method on the field itself, respectively.
* The `get_FIELD_width` and `get_FIELD_height` methods for Models with `ImageField` fields were removed. Use the `width` and `height` attributes on the field itself instead.
* The dispatcher `connect`, `disconnect`, `send`, and `sendExact` functions were removed. Use the signal object's own `connect`, `disconnect`, `send`, and `send` methods instead, respectively.
* The `form_for_model` and `form_for_instance` functions were removed. Use a `ModelForm` subclass instead.
* Support for importing `django.newforms` was removed. Use `django.forms` instead.
* Support for importing `django.utils.images` was removed. Use `django.core.files.images` instead.
* Support for the `follow` argument in the `create_object` and `update_object` generic views was removed. Use the `django.forms` package and the new `form_class` argument instead.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8291 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-11 05:10:47 +08:00
|
|
|
|
2008-09-01 04:10:50 +08:00
|
|
|
class TypedChoiceField(ChoiceField):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.coerce = kwargs.pop('coerce', lambda val: val)
|
|
|
|
self.empty_value = kwargs.pop('empty_value', '')
|
|
|
|
super(TypedChoiceField, self).__init__(*args, **kwargs)
|
2008-10-24 15:14:30 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
2008-09-01 04:10:50 +08:00
|
|
|
"""
|
|
|
|
Validate that the value is in self.choices and can be coerced to the
|
|
|
|
right type.
|
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
value = super(TypedChoiceField, self).to_python(value)
|
|
|
|
super(TypedChoiceField, self).validate(value)
|
|
|
|
if value == self.empty_value or value in validators.EMPTY_VALUES:
|
2008-09-01 04:10:50 +08:00
|
|
|
return self.empty_value
|
|
|
|
try:
|
|
|
|
value = self.coerce(value)
|
2010-01-05 11:56:19 +08:00
|
|
|
except (ValueError, TypeError, ValidationError):
|
2008-09-01 04:10:50 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid_choice'] % {'value': value})
|
|
|
|
return value
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def validate(self, value):
|
|
|
|
pass
|
|
|
|
|
2006-11-02 11:16:12 +08:00
|
|
|
class MultipleChoiceField(ChoiceField):
|
2007-01-09 13:12:25 +08:00
|
|
|
hidden_widget = MultipleHiddenInput
|
2007-04-21 13:43:32 +08:00
|
|
|
widget = SelectMultiple
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2007-11-04 10:08:02 +08:00
|
|
|
'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),
|
|
|
|
'invalid_list': _(u'Enter a list of values.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
2006-11-02 11:16:12 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
if not value:
|
|
|
|
return []
|
|
|
|
elif not isinstance(value, (list, tuple)):
|
|
|
|
raise ValidationError(self.error_messages['invalid_list'])
|
|
|
|
return [smart_unicode(val) for val in value]
|
|
|
|
|
|
|
|
def validate(self, value):
|
2006-11-02 11:16:12 +08:00
|
|
|
"""
|
|
|
|
Validates that the input is a list or tuple.
|
|
|
|
"""
|
|
|
|
if self.required and not value:
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['required'])
|
2006-11-02 11:16:12 +08:00
|
|
|
# Validate that each value in the value list is in self.choices.
|
2010-01-05 11:56:19 +08:00
|
|
|
for val in value:
|
2008-07-19 15:53:02 +08:00
|
|
|
if not self.valid_value(val):
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid_choice'] % {'value': val})
|
2006-11-05 04:49:59 +08:00
|
|
|
|
|
|
|
class ComboField(Field):
|
2007-01-24 04:23:07 +08:00
|
|
|
"""
|
|
|
|
A Field whose clean() method calls multiple Field clean() methods.
|
|
|
|
"""
|
2007-01-29 06:10:04 +08:00
|
|
|
def __init__(self, fields=(), *args, **kwargs):
|
|
|
|
super(ComboField, self).__init__(*args, **kwargs)
|
2006-11-27 08:49:26 +08:00
|
|
|
# Set 'required' to False on the individual fields, because the
|
|
|
|
# required validation will be handled by ComboField, not by those
|
|
|
|
# individual fields.
|
|
|
|
for f in fields:
|
|
|
|
f.required = False
|
2006-11-05 04:49:59 +08:00
|
|
|
self.fields = fields
|
|
|
|
|
|
|
|
def clean(self, value):
|
|
|
|
"""
|
|
|
|
Validates the given value against all of self.fields, which is a
|
|
|
|
list of Field instances.
|
|
|
|
"""
|
2007-01-21 01:25:42 +08:00
|
|
|
super(ComboField, self).clean(value)
|
2006-11-05 04:49:59 +08:00
|
|
|
for field in self.fields:
|
|
|
|
value = field.clean(value)
|
|
|
|
return value
|
2007-01-24 04:23:07 +08:00
|
|
|
|
|
|
|
class MultiValueField(Field):
|
|
|
|
"""
|
2007-07-01 12:24:20 +08:00
|
|
|
A Field that aggregates the logic of multiple Fields.
|
2007-09-09 03:26:15 +08:00
|
|
|
|
2007-07-01 12:24:20 +08:00
|
|
|
Its clean() method takes a "decompressed" list of values, which are then
|
|
|
|
cleaned into a single value according to self.fields. Each value in
|
2007-01-24 04:23:07 +08:00
|
|
|
this list is cleaned by the corresponding field -- the first value is
|
|
|
|
cleaned by the first field, the second value is cleaned by the second
|
|
|
|
field, etc. Once all fields are cleaned, the list of clean values is
|
|
|
|
"compressed" into a single value.
|
|
|
|
|
2007-07-01 12:24:20 +08:00
|
|
|
Subclasses should not have to implement clean(). Instead, they must
|
|
|
|
implement compress(), which takes a list of valid values and returns a
|
|
|
|
"compressed" version of those values -- a single value.
|
2007-01-24 04:23:07 +08:00
|
|
|
|
|
|
|
You'll probably want to use this with MultiWidget.
|
|
|
|
"""
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2007-11-04 10:08:02 +08:00
|
|
|
'invalid': _(u'Enter a list of values.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2007-01-29 06:10:04 +08:00
|
|
|
def __init__(self, fields=(), *args, **kwargs):
|
|
|
|
super(MultiValueField, self).__init__(*args, **kwargs)
|
2007-01-24 04:23:07 +08:00
|
|
|
# Set 'required' to False on the individual fields, because the
|
|
|
|
# required validation will be handled by MultiValueField, not by those
|
|
|
|
# individual fields.
|
|
|
|
for f in fields:
|
|
|
|
f.required = False
|
|
|
|
self.fields = fields
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def validate(self, value):
|
|
|
|
pass
|
|
|
|
|
2007-01-24 04:23:07 +08:00
|
|
|
def clean(self, value):
|
|
|
|
"""
|
|
|
|
Validates every value in the given list. A value is validated against
|
|
|
|
the corresponding Field in self.fields.
|
|
|
|
|
|
|
|
For example, if this MultiValueField was instantiated with
|
|
|
|
fields=(DateField(), TimeField()), clean() would call
|
|
|
|
DateField.clean(value[0]) and TimeField.clean(value[1]).
|
|
|
|
"""
|
|
|
|
clean_data = []
|
|
|
|
errors = ErrorList()
|
2007-06-23 11:32:59 +08:00
|
|
|
if not value or isinstance(value, (list, tuple)):
|
2010-01-05 11:56:19 +08:00
|
|
|
if not value or not [v for v in value if v not in validators.EMPTY_VALUES]:
|
2007-06-23 11:32:59 +08:00
|
|
|
if self.required:
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['required'])
|
2007-06-23 11:32:59 +08:00
|
|
|
else:
|
|
|
|
return self.compress([])
|
|
|
|
else:
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'])
|
2007-01-24 04:23:07 +08:00
|
|
|
for i, field in enumerate(self.fields):
|
|
|
|
try:
|
|
|
|
field_value = value[i]
|
2007-04-26 20:46:04 +08:00
|
|
|
except IndexError:
|
2007-01-24 04:23:07 +08:00
|
|
|
field_value = None
|
2010-01-05 11:56:19 +08:00
|
|
|
if self.required and field_value in validators.EMPTY_VALUES:
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['required'])
|
2007-01-24 04:23:07 +08:00
|
|
|
try:
|
|
|
|
clean_data.append(field.clean(field_value))
|
|
|
|
except ValidationError, e:
|
|
|
|
# Collect all validation errors in a single list, which we'll
|
|
|
|
# raise at the end of clean(), rather than raising a single
|
|
|
|
# exception for the first error we encounter.
|
|
|
|
errors.extend(e.messages)
|
|
|
|
if errors:
|
|
|
|
raise ValidationError(errors)
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
out = self.compress(clean_data)
|
|
|
|
self.validate(out)
|
|
|
|
return out
|
2007-01-24 04:23:07 +08:00
|
|
|
|
|
|
|
def compress(self, data_list):
|
|
|
|
"""
|
|
|
|
Returns a single value for the given list of values. The values can be
|
|
|
|
assumed to be valid.
|
|
|
|
|
|
|
|
For example, if this MultiValueField was instantiated with
|
|
|
|
fields=(DateField(), TimeField()), this might return a datetime
|
|
|
|
object created by combining the date and time in data_list.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError('Subclasses must implement this method.')
|
|
|
|
|
2008-03-20 06:29:11 +08:00
|
|
|
class FilePathField(ChoiceField):
|
|
|
|
def __init__(self, path, match=None, recursive=False, required=True,
|
2008-08-24 01:26:00 +08:00
|
|
|
widget=None, label=None, initial=None, help_text=None,
|
2008-03-20 06:29:11 +08:00
|
|
|
*args, **kwargs):
|
|
|
|
self.path, self.match, self.recursive = path, match, recursive
|
|
|
|
super(FilePathField, self).__init__(choices=(), required=required,
|
|
|
|
widget=widget, label=label, initial=initial, help_text=help_text,
|
|
|
|
*args, **kwargs)
|
2009-04-16 22:24:27 +08:00
|
|
|
|
2009-04-09 02:53:55 +08:00
|
|
|
if self.required:
|
|
|
|
self.choices = []
|
|
|
|
else:
|
|
|
|
self.choices = [("", "---------")]
|
|
|
|
|
2008-03-20 06:29:11 +08:00
|
|
|
if self.match is not None:
|
|
|
|
self.match_re = re.compile(self.match)
|
2009-04-09 02:53:55 +08:00
|
|
|
|
2008-03-20 06:29:11 +08:00
|
|
|
if recursive:
|
|
|
|
for root, dirs, files in os.walk(self.path):
|
|
|
|
for f in files:
|
|
|
|
if self.match is None or self.match_re.search(f):
|
|
|
|
f = os.path.join(root, f)
|
|
|
|
self.choices.append((f, f.replace(path, "", 1)))
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
for f in os.listdir(self.path):
|
|
|
|
full_file = os.path.join(self.path, f)
|
|
|
|
if os.path.isfile(full_file) and (self.match is None or self.match_re.search(f)):
|
|
|
|
self.choices.append((full_file, f))
|
|
|
|
except OSError:
|
|
|
|
pass
|
2009-04-09 02:53:55 +08:00
|
|
|
|
2008-03-20 06:29:11 +08:00
|
|
|
self.widget.choices = self.choices
|
|
|
|
|
2007-01-24 04:23:07 +08:00
|
|
|
class SplitDateTimeField(MultiValueField):
|
2008-11-11 03:42:55 +08:00
|
|
|
widget = SplitDateTimeWidget
|
2008-09-02 05:28:32 +08:00
|
|
|
hidden_widget = SplitHiddenDateTimeWidget
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2007-11-04 10:08:02 +08:00
|
|
|
'invalid_date': _(u'Enter a valid date.'),
|
|
|
|
'invalid_time': _(u'Enter a valid time.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2009-03-23 00:13:06 +08:00
|
|
|
def __init__(self, input_date_formats=None, input_time_formats=None, *args, **kwargs):
|
2007-10-28 13:40:26 +08:00
|
|
|
errors = self.default_error_messages.copy()
|
|
|
|
if 'error_messages' in kwargs:
|
|
|
|
errors.update(kwargs['error_messages'])
|
2010-05-21 22:07:54 +08:00
|
|
|
localize = kwargs.get('localize', False)
|
2007-10-28 13:40:26 +08:00
|
|
|
fields = (
|
2010-05-21 22:07:54 +08:00
|
|
|
DateField(input_formats=input_date_formats,
|
|
|
|
error_messages={'invalid': errors['invalid_date']},
|
|
|
|
localize=localize),
|
|
|
|
TimeField(input_formats=input_time_formats,
|
|
|
|
error_messages={'invalid': errors['invalid_time']},
|
|
|
|
localize=localize),
|
2007-10-28 13:40:26 +08:00
|
|
|
)
|
2007-01-29 06:10:04 +08:00
|
|
|
super(SplitDateTimeField, self).__init__(fields, *args, **kwargs)
|
2007-01-24 04:23:07 +08:00
|
|
|
|
|
|
|
def compress(self, data_list):
|
|
|
|
if data_list:
|
2007-06-23 11:32:59 +08:00
|
|
|
# Raise a validation error if time or date is empty
|
|
|
|
# (possible if SplitDateTimeField has required=False).
|
2010-01-05 11:56:19 +08:00
|
|
|
if data_list[0] in validators.EMPTY_VALUES:
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid_date'])
|
2010-01-05 11:56:19 +08:00
|
|
|
if data_list[1] in validators.EMPTY_VALUES:
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid_time'])
|
2007-01-24 04:23:07 +08:00
|
|
|
return datetime.datetime.combine(*data_list)
|
|
|
|
return None
|
2007-09-16 19:38:32 +08:00
|
|
|
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
class IPAddressField(CharField):
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2007-11-04 10:08:02 +08:00
|
|
|
'invalid': _(u'Enter a valid IPv4 address.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
2010-01-05 11:56:19 +08:00
|
|
|
default_validators = [validators.validate_ipv4_address]
|
2007-10-28 13:40:26 +08:00
|
|
|
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
class SlugField(CharField):
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
default_error_messages = {
|
|
|
|
'invalid': _(u"Enter a valid 'slug' consisting of letters, numbers,"
|
|
|
|
u" underscores or hyphens."),
|
|
|
|
}
|
2010-01-05 11:56:19 +08:00
|
|
|
default_validators = [validators.validate_slug]
|