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
|
|
|
"""
|
|
|
|
|
2012-06-08 00:08:47 +08:00
|
|
|
from __future__ import absolute_import, unicode_literals
|
2011-10-18 00:56:18 +08:00
|
|
|
|
2011-03-28 10:11:19 +08:00
|
|
|
import copy
|
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
|
2013-03-19 13:04:59 +08:00
|
|
|
import sys
|
2012-07-20 21:36:52 +08:00
|
|
|
try:
|
|
|
|
from urllib.parse import urlsplit, urlunsplit
|
|
|
|
except ImportError: # Python 2
|
|
|
|
from urlparse import urlsplit, urlunsplit
|
2009-12-18 06:06:41 +08:00
|
|
|
from decimal import Decimal, DecimalException
|
2012-05-06 01:47:03 +08:00
|
|
|
from io import BytesIO
|
2008-07-01 23:10:51 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
from django.core import validators
|
2011-10-18 00:56:18 +08:00
|
|
|
from django.core.exceptions import ValidationError
|
2011-11-18 21:01:06 +08:00
|
|
|
from django.forms.util import ErrorList, from_current_timezone, to_current_timezone
|
2013-01-28 21:12:56 +08:00
|
|
|
from django.forms.widgets import (
|
2013-02-23 16:45:56 +08:00
|
|
|
TextInput, NumberInput, EmailInput, URLInput, HiddenInput,
|
2011-10-18 00:56:18 +08:00
|
|
|
MultipleHiddenInput, ClearableFileInput, CheckboxInput, Select,
|
|
|
|
NullBooleanSelect, SelectMultiple, DateInput, DateTimeInput, TimeInput,
|
2013-01-28 21:12:56 +08:00
|
|
|
SplitDateTimeWidget, SplitHiddenDateTimeWidget, FILE_INPUT_CONTRADICTION
|
|
|
|
)
|
2010-03-01 18:19:24 +08:00
|
|
|
from django.utils import formats
|
2013-01-27 03:49:02 +08:00
|
|
|
from django.utils.encoding import smart_text, force_str, force_text
|
2011-06-11 21:48:24 +08:00
|
|
|
from django.utils.ipv6 import clean_ipv6_address
|
2012-07-20 20:22:00 +08:00
|
|
|
from django.utils import six
|
2013-01-31 04:29:39 +08:00
|
|
|
from django.utils.translation import ugettext_lazy as _, ungettext_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
|
|
|
|
|
2007-07-13 17:09:59 +08:00
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
__all__ = (
|
|
|
|
'Field', 'CharField', 'IntegerField',
|
2011-04-22 20:27:58 +08:00
|
|
|
'DateField', 'TimeField', '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',
|
2011-06-11 21:48:24 +08:00
|
|
|
'SplitDateTimeField', 'IPAddressField', 'GenericIPAddressField', 'FilePathField',
|
|
|
|
'SlugField', 'TypedChoiceField', 'TypedMultipleChoiceField'
|
2006-10-29 04:34:37 +08:00
|
|
|
)
|
|
|
|
|
2009-12-23 01:58:49 +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
|
2013-03-14 23:19:59 +08:00
|
|
|
# Add an 'invalid' entry to default_error_message if you want a specific
|
|
|
|
# field error message not raised by the field validators.
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'required': _('This field is required.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
2013-03-07 16:21:59 +08:00
|
|
|
empty_values = list(validators.EMPTY_VALUES)
|
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,
|
2013-03-26 04:25:53 +08:00
|
|
|
help_text='', 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-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
|
2013-03-26 04:25:53 +08:00
|
|
|
self.help_text = 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
|
2013-03-19 05:22:26 +08:00
|
|
|
super(Field, self).__init__()
|
2010-01-05 11:56:19 +08:00
|
|
|
|
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):
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values and self.required:
|
2010-01-05 11:56:19 +08:00
|
|
|
raise ValidationError(self.error_messages['required'])
|
|
|
|
|
|
|
|
def run_validators(self, value):
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2010-01-05 11:56:19 +08:00
|
|
|
return
|
|
|
|
errors = []
|
|
|
|
for v in self.validators:
|
|
|
|
try:
|
|
|
|
v(value)
|
2012-04-29 00:09:37 +08:00
|
|
|
except ValidationError as e:
|
2010-01-05 11:56:19 +08:00
|
|
|
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 {}
|
|
|
|
|
2013-01-26 03:50:46 +08:00
|
|
|
def _has_changed(self, initial, data):
|
|
|
|
"""
|
|
|
|
Return True if data differs from initial.
|
|
|
|
"""
|
|
|
|
# For purposes of seeing whether something has changed, None is
|
|
|
|
# the same as an empty string, if the data or inital value we get
|
|
|
|
# is None, replace it w/ ''.
|
2013-01-27 00:05:47 +08:00
|
|
|
initial_value = initial if initial is not None else ''
|
|
|
|
try:
|
|
|
|
data = self.to_python(data)
|
|
|
|
except ValidationError:
|
2013-01-26 03:50:46 +08:00
|
|
|
return True
|
2013-01-27 00:05:47 +08:00
|
|
|
data_value = data if data is not None else ''
|
|
|
|
return initial_value != data_value
|
2013-01-26 03:50:46 +08:00
|
|
|
|
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)
|
2011-10-28 22:38:41 +08:00
|
|
|
result.validators = self.validators[:]
|
2007-09-14 11:29:39 +08:00
|
|
|
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."
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2012-06-08 00:08:47 +08:00
|
|
|
return ''
|
2012-07-21 16:00:10 +08:00
|
|
|
return smart_text(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-12-09 02:54:53 +08:00
|
|
|
def widget_attrs(self, widget):
|
2011-11-15 17:36:08 +08:00
|
|
|
attrs = super(CharField, self).widget_attrs(widget)
|
2012-09-11 01:21:29 +08:00
|
|
|
if self.max_length is not None and isinstance(widget, TextInput):
|
2007-08-05 13:14:46 +08:00
|
|
|
# The HTML attribute is maxlength, not max_length.
|
2011-11-15 17:36:08 +08:00
|
|
|
attrs.update({'maxlength': str(self.max_length)})
|
|
|
|
return attrs
|
2006-12-09 02:54:53 +08:00
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
class IntegerField(Field):
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('Enter a whole number.'),
|
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):
|
2011-01-14 00:41:46 +08:00
|
|
|
self.max_value, self.min_value = max_value, min_value
|
2013-02-23 16:45:56 +08:00
|
|
|
kwargs.setdefault('widget', NumberInput if not kwargs.get('localize') else self.widget)
|
2007-01-29 06:10:04 +08:00
|
|
|
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)
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.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
|
|
|
|
2013-02-23 16:45:56 +08:00
|
|
|
def widget_attrs(self, widget):
|
|
|
|
attrs = super(IntegerField, self).widget_attrs(widget)
|
|
|
|
if isinstance(widget, NumberInput):
|
|
|
|
if self.min_value is not None:
|
|
|
|
attrs['min'] = self.min_value
|
|
|
|
if self.max_value is not None:
|
|
|
|
attrs['max'] = self.max_value
|
|
|
|
return attrs
|
|
|
|
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
class FloatField(IntegerField):
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('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)
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.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
|
|
|
|
|
2013-02-23 16:45:56 +08:00
|
|
|
def widget_attrs(self, widget):
|
|
|
|
attrs = super(FloatField, self).widget_attrs(widget)
|
|
|
|
if isinstance(widget, NumberInput):
|
|
|
|
attrs.setdefault('step', 'any')
|
|
|
|
return attrs
|
|
|
|
|
|
|
|
|
|
|
|
class DecimalField(IntegerField):
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('Enter a number.'),
|
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
|
2013-02-23 16:45:56 +08:00
|
|
|
super(DecimalField, self).__init__(max_value, min_value, *args, **kwargs)
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
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.
|
|
|
|
"""
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.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)
|
2012-07-21 16:00:10 +08:00
|
|
|
value = smart_text(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)
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2010-01-05 11:56:19 +08:00
|
|
|
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
|
|
|
|
|
2013-02-23 16:45:56 +08:00
|
|
|
def widget_attrs(self, widget):
|
|
|
|
attrs = super(DecimalField, self).widget_attrs(widget)
|
|
|
|
if isinstance(widget, NumberInput):
|
|
|
|
if self.max_digits is not None:
|
|
|
|
max_length = self.max_digits + 1 # for the sign
|
|
|
|
if self.decimal_places is None or self.decimal_places > 0:
|
|
|
|
max_length += 1 # for the dot
|
|
|
|
attrs['maxlength'] = max_length
|
|
|
|
if self.decimal_places:
|
|
|
|
attrs['step'] = '0.%s1' % ('0' * (self.decimal_places-1))
|
|
|
|
return attrs
|
|
|
|
|
|
|
|
|
2011-05-02 00:14:57 +08:00
|
|
|
class BaseTemporalField(Field):
|
|
|
|
|
|
|
|
def __init__(self, input_formats=None, *args, **kwargs):
|
|
|
|
super(BaseTemporalField, self).__init__(*args, **kwargs)
|
|
|
|
if input_formats is not None:
|
|
|
|
self.input_formats = input_formats
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
# Try to coerce the value to unicode.
|
2012-07-21 16:00:10 +08:00
|
|
|
unicode_value = force_text(value, strings_only=True)
|
2012-07-20 20:48:51 +08:00
|
|
|
if isinstance(unicode_value, six.text_type):
|
2011-05-02 00:14:57 +08:00
|
|
|
value = unicode_value.strip()
|
|
|
|
# If unicode, try to strptime against each input format.
|
2012-07-20 20:48:51 +08:00
|
|
|
if isinstance(value, six.text_type):
|
2011-05-02 00:14:57 +08:00
|
|
|
for format in self.input_formats:
|
|
|
|
try:
|
|
|
|
return self.strptime(value, format)
|
2012-09-23 19:25:47 +08:00
|
|
|
except (ValueError, TypeError):
|
2012-04-05 22:49:02 +08:00
|
|
|
continue
|
2011-05-02 00:14:57 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'])
|
|
|
|
|
|
|
|
def strptime(self, value, format):
|
|
|
|
raise NotImplementedError('Subclasses must define this method.')
|
|
|
|
|
2013-01-26 03:50:46 +08:00
|
|
|
|
2011-05-02 00:14:57 +08:00
|
|
|
class DateField(BaseTemporalField):
|
2009-04-16 22:24:27 +08:00
|
|
|
widget = DateInput
|
2011-05-02 00:14:57 +08:00
|
|
|
input_formats = formats.get_format_lazy('DATE_INPUT_FORMATS')
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('Enter a valid date.'),
|
2007-10-28 13:40:26 +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.
|
|
|
|
"""
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.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
|
2011-05-02 00:14:57 +08:00
|
|
|
return super(DateField, self).to_python(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2011-05-02 00:14:57 +08:00
|
|
|
def strptime(self, value, format):
|
2013-01-27 03:49:02 +08:00
|
|
|
return datetime.datetime.strptime(force_str(value), format).date()
|
2011-05-02 00:14:57 +08:00
|
|
|
|
2013-01-26 03:50:46 +08:00
|
|
|
|
2011-05-02 00:14:57 +08:00
|
|
|
class TimeField(BaseTemporalField):
|
2008-08-24 01:36:42 +08:00
|
|
|
widget = TimeInput
|
2011-05-02 00:14:57 +08:00
|
|
|
input_formats = formats.get_format_lazy('TIME_INPUT_FORMATS')
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('Enter a valid time.')
|
2007-10-28 13:40:26 +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.
|
|
|
|
"""
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2006-12-15 04:35:32 +08:00
|
|
|
return None
|
|
|
|
if isinstance(value, datetime.time):
|
|
|
|
return value
|
2011-05-02 00:14:57 +08:00
|
|
|
return super(TimeField, self).to_python(value)
|
|
|
|
|
|
|
|
def strptime(self, value, format):
|
2013-01-27 03:49:02 +08:00
|
|
|
return datetime.datetime.strptime(force_str(value), format).time()
|
2006-12-15 04:35:32 +08:00
|
|
|
|
2011-05-02 00:14:57 +08:00
|
|
|
class DateTimeField(BaseTemporalField):
|
2007-10-21 22:50:47 +08:00
|
|
|
widget = DateTimeInput
|
2011-05-02 00:14:57 +08:00
|
|
|
input_formats = formats.get_format_lazy('DATETIME_INPUT_FORMATS')
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('Enter a valid date/time.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
2007-10-21 22:50:47 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def prepare_value(self, value):
|
|
|
|
if isinstance(value, datetime.datetime):
|
|
|
|
value = to_current_timezone(value)
|
|
|
|
return value
|
|
|
|
|
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.
|
|
|
|
"""
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2006-10-29 04:34:37 +08:00
|
|
|
return None
|
|
|
|
if isinstance(value, datetime.datetime):
|
2011-11-18 21:01:06 +08:00
|
|
|
return from_current_timezone(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
if isinstance(value, datetime.date):
|
2011-11-18 21:01:06 +08:00
|
|
|
result = datetime.datetime(value.year, value.month, value.day)
|
|
|
|
return from_current_timezone(result)
|
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'])
|
2013-03-07 16:21:59 +08:00
|
|
|
if value[0] in self.empty_values and value[1] in self.empty_values:
|
2010-09-12 05:26:19 +08:00
|
|
|
return None
|
2007-10-21 22:50:20 +08:00
|
|
|
value = '%s %s' % tuple(value)
|
2011-11-18 21:01:06 +08:00
|
|
|
result = super(DateTimeField, self).to_python(value)
|
|
|
|
return from_current_timezone(result)
|
2011-05-02 00:14:57 +08:00
|
|
|
|
|
|
|
def strptime(self, value, format):
|
2013-01-27 03:49:02 +08:00
|
|
|
return datetime.datetime.strptime(force_str(value), format)
|
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)
|
2011-11-07 15:41:24 +08:00
|
|
|
self._set_regex(regex)
|
|
|
|
|
|
|
|
def _get_regex(self):
|
|
|
|
return self._regex
|
|
|
|
|
|
|
|
def _set_regex(self, regex):
|
2012-07-20 20:22:00 +08:00
|
|
|
if isinstance(regex, six.string_types):
|
2012-06-01 02:45:35 +08:00
|
|
|
regex = re.compile(regex, re.UNICODE)
|
2011-11-07 15:41:24 +08:00
|
|
|
self._regex = regex
|
|
|
|
if hasattr(self, '_regex_validator') and self._regex_validator in self.validators:
|
|
|
|
self.validators.remove(self._regex_validator)
|
|
|
|
self._regex_validator = validators.RegexValidator(regex=regex)
|
|
|
|
self.validators.append(self._regex_validator)
|
|
|
|
|
|
|
|
regex = property(_get_regex, _set_regex)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
class EmailField(CharField):
|
2013-01-28 21:12:56 +08:00
|
|
|
widget = EmailInput
|
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 = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _("No file was submitted. Check the encoding type on the form."),
|
|
|
|
'missing': _("No file was submitted."),
|
|
|
|
'empty': _("The submitted file is empty."),
|
2013-01-31 04:29:39 +08:00
|
|
|
'max_length': ungettext_lazy(
|
|
|
|
'Ensure this filename has at most %(max)d character (it has %(length)d).',
|
|
|
|
'Ensure this filename has at most %(max)d characters (it has %(length)d).',
|
|
|
|
'max'),
|
2012-06-08 00:08:47 +08:00
|
|
|
'contradiction': _('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)
|
2011-04-23 05:18:27 +08:00
|
|
|
self.allow_empty_file = kwargs.pop('allow_empty_file', False)
|
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):
|
2013-03-07 16:21:59 +08:00
|
|
|
if data in self.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'])
|
2011-04-23 05:18:27 +08:00
|
|
|
if not self.allow_empty_file and 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
|
2013-03-07 16:21:59 +08:00
|
|
|
# in self.empty_value; if a False value makes it this far
|
2010-10-01 10:02:58 +08:00
|
|
|
# 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
|
|
|
|
|
2013-01-26 03:50:46 +08:00
|
|
|
def _has_changed(self, initial, data):
|
|
|
|
if data is None:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2007-08-06 21:58:56 +08:00
|
|
|
class ImageField(FileField):
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid_image': _("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'):
|
2012-05-06 01:47:03 +08:00
|
|
|
file = BytesIO(data.read())
|
2008-07-01 23:10:51 +08:00
|
|
|
else:
|
2012-05-06 01:47:03 +08:00
|
|
|
file = BytesIO(data['content'])
|
2008-07-01 23:10:51 +08:00
|
|
|
|
2007-08-06 21:58:56 +08:00
|
|
|
try:
|
2012-07-31 03:57:22 +08:00
|
|
|
# load() could spot a truncated JPEG, but it loads the entire
|
|
|
|
# image in memory, which is a DoS vector. See #3848 and #18520.
|
|
|
|
# verify() must be called immediately after the constructor.
|
|
|
|
Image.open(file).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
|
2013-03-19 13:04:59 +08:00
|
|
|
six.reraise(ValidationError, ValidationError(self.error_messages['invalid_image']), sys.exc_info()[2])
|
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):
|
2013-01-28 21:24:48 +08:00
|
|
|
widget = URLInput
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('Enter a valid URL.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2012-03-31 21:55:03 +08:00
|
|
|
def __init__(self, max_length=None, min_length=None, *args, **kwargs):
|
|
|
|
super(URLField, self).__init__(max_length, min_length, *args, **kwargs)
|
|
|
|
self.validators.append(validators.URLValidator())
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
def to_python(self, value):
|
2011-09-10 06:57:12 +08:00
|
|
|
|
|
|
|
def split_url(url):
|
|
|
|
"""
|
|
|
|
Returns a list of url parts via ``urlparse.urlsplit`` (or raises a
|
|
|
|
``ValidationError`` exception for certain).
|
|
|
|
"""
|
|
|
|
try:
|
2012-07-20 21:36:52 +08:00
|
|
|
return list(urlsplit(url))
|
2011-09-10 06:57:12 +08:00
|
|
|
except ValueError:
|
|
|
|
# urlparse.urlsplit can raise a ValueError with some
|
|
|
|
# misformatted URLs.
|
|
|
|
raise ValidationError(self.error_messages['invalid'])
|
|
|
|
|
2011-09-10 06:32:38 +08:00
|
|
|
value = super(URLField, self).to_python(value)
|
2010-01-05 11:56:19 +08:00
|
|
|
if value:
|
2011-09-10 06:57:12 +08:00
|
|
|
url_fields = split_url(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
|
2011-01-14 00:41:46 +08:00
|
|
|
# contains the domain.
|
2010-11-21 18:08:28 +08:00
|
|
|
url_fields[1] = url_fields[2]
|
|
|
|
url_fields[2] = ''
|
|
|
|
# Rebuild the url_fields list, since the domain segment may now
|
|
|
|
# contain the path too.
|
2012-07-20 21:36:52 +08:00
|
|
|
url_fields = split_url(urlunsplit(url_fields))
|
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] = '/'
|
2012-07-20 21:36:52 +08:00
|
|
|
value = urlunsplit(url_fields)
|
2011-09-10 06:32:38 +08:00
|
|
|
return value
|
2006-11-02 07:52:43 +08:00
|
|
|
|
2013-01-26 03:50:46 +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.
|
2012-07-20 20:22:00 +08:00
|
|
|
if isinstance(value, six.string_types) and value.lower() in ('false', '0'):
|
2008-06-30 18:44:56 +08:00
|
|
|
value = False
|
|
|
|
else:
|
|
|
|
value = bool(value)
|
2013-01-26 23:39:20 +08:00
|
|
|
return super(BooleanField, self).to_python(value)
|
|
|
|
|
|
|
|
def validate(self, value):
|
2008-06-30 18:44:56 +08:00
|
|
|
if not value and self.required:
|
|
|
|
raise ValidationError(self.error_messages['required'])
|
2006-11-02 11:16:12 +08:00
|
|
|
|
2013-01-26 03:50:46 +08:00
|
|
|
def _has_changed(self, initial, data):
|
|
|
|
# Sometimes data or initial could be None or '' which should be the
|
|
|
|
# same thing as False.
|
|
|
|
if initial == 'False':
|
|
|
|
# show_hidden_initial may have transformed False to 'False'
|
|
|
|
initial = False
|
|
|
|
return bool(initial) != bool(data)
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
2013-01-26 03:50:46 +08:00
|
|
|
def _has_changed(self, initial, data):
|
|
|
|
# None (unknown) and False (No) are not the same
|
|
|
|
if initial is not None:
|
|
|
|
initial = bool(initial)
|
|
|
|
if data is not None:
|
|
|
|
data = bool(data)
|
|
|
|
return initial != data
|
|
|
|
|
|
|
|
|
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 = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid_choice': _('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,
|
2013-03-26 04:25:53 +08:00
|
|
|
initial=None, help_text='', *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
|
|
|
|
|
2011-06-17 00:34:38 +08:00
|
|
|
def __deepcopy__(self, memo):
|
|
|
|
result = super(ChoiceField, self).__deepcopy__(memo)
|
|
|
|
result._choices = copy.deepcopy(self._choices, memo)
|
|
|
|
return result
|
|
|
|
|
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."
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2012-06-08 00:08:47 +08:00
|
|
|
return ''
|
2012-07-21 16:00:10 +08:00
|
|
|
return smart_text(value)
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
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"
|
2013-03-14 21:45:41 +08:00
|
|
|
text_value = force_text(value)
|
2008-07-19 15:53:02 +08:00
|
|
|
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:
|
2013-03-14 21:45:41 +08:00
|
|
|
if value == k2 or text_value == force_text(k2):
|
2008-07-19 15:53:02 +08:00
|
|
|
return True
|
|
|
|
else:
|
2013-03-14 21:45:41 +08:00
|
|
|
if value == k or text_value == force_text(k):
|
2008-07-19 15:53:02 +08:00
|
|
|
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
|
|
|
"""
|
2010-12-05 12:47:19 +08:00
|
|
|
Validates that the value is in self.choices and can be coerced to the
|
2008-09-01 04:10:50 +08:00
|
|
|
right type.
|
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
value = super(TypedChoiceField, self).to_python(value)
|
2013-03-07 16:21:59 +08:00
|
|
|
if value == self.empty_value or value in self.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
|
|
|
|
|
2013-01-26 03:50:46 +08:00
|
|
|
|
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 = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'),
|
|
|
|
'invalid_list': _('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'])
|
2012-07-21 16:00:10 +08:00
|
|
|
return [smart_text(val) for val in value]
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
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
|
|
|
|
2013-01-26 03:50:46 +08:00
|
|
|
def _has_changed(self, initial, data):
|
|
|
|
if initial is None:
|
|
|
|
initial = []
|
|
|
|
if data is None:
|
|
|
|
data = []
|
|
|
|
if len(initial) != len(data):
|
|
|
|
return True
|
|
|
|
initial_set = set([force_text(value) for value in initial])
|
|
|
|
data_set = set([force_text(value) for value in data])
|
|
|
|
return data_set != initial_set
|
|
|
|
|
|
|
|
|
2010-12-05 12:47:19 +08:00
|
|
|
class TypedMultipleChoiceField(MultipleChoiceField):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.coerce = kwargs.pop('coerce', lambda val: val)
|
|
|
|
self.empty_value = kwargs.pop('empty_value', [])
|
|
|
|
super(TypedMultipleChoiceField, self).__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
"""
|
|
|
|
Validates that the values are in self.choices and can be coerced to the
|
|
|
|
right type.
|
|
|
|
"""
|
|
|
|
value = super(TypedMultipleChoiceField, self).to_python(value)
|
2013-03-07 16:21:59 +08:00
|
|
|
if value == self.empty_value or value in self.empty_values:
|
2010-12-05 12:47:19 +08:00
|
|
|
return self.empty_value
|
|
|
|
new_value = []
|
|
|
|
for choice in value:
|
|
|
|
try:
|
|
|
|
new_value.append(self.coerce(choice))
|
|
|
|
except (ValueError, TypeError, ValidationError):
|
|
|
|
raise ValidationError(self.error_messages['invalid_choice'] % {'value': choice})
|
|
|
|
return new_value
|
|
|
|
|
|
|
|
def validate(self, value):
|
2013-03-14 21:45:41 +08:00
|
|
|
if value != self.empty_value:
|
|
|
|
super(TypedMultipleChoiceField, self).validate(value)
|
|
|
|
elif self.required:
|
|
|
|
raise ValidationError(self.error_messages['required'])
|
|
|
|
|
2010-12-05 12:47:19 +08:00
|
|
|
|
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 = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('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)):
|
2013-03-07 16:21:59 +08:00
|
|
|
if not value or not [v for v in value if v not in self.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
|
2013-03-07 16:21:59 +08:00
|
|
|
if self.required and field_value in self.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))
|
2012-04-29 00:09:37 +08:00
|
|
|
except ValidationError as e:
|
2007-01-24 04:23:07 +08:00
|
|
|
# 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)
|
2012-02-04 20:48:12 +08:00
|
|
|
self.run_validators(out)
|
2010-01-05 11:56:19 +08:00
|
|
|
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.')
|
|
|
|
|
2013-01-26 03:50:46 +08:00
|
|
|
def _has_changed(self, initial, data):
|
|
|
|
if initial is None:
|
|
|
|
initial = ['' for x in range(0, len(data))]
|
|
|
|
else:
|
|
|
|
if not isinstance(initial, list):
|
|
|
|
initial = self.widget.decompress(initial)
|
|
|
|
for field, initial, data in zip(self.fields, initial, data):
|
|
|
|
if field._has_changed(initial, data):
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2008-03-20 06:29:11 +08:00
|
|
|
class FilePathField(ChoiceField):
|
2012-04-22 22:44:08 +08:00
|
|
|
def __init__(self, path, match=None, recursive=False, allow_files=True,
|
|
|
|
allow_folders=False, required=True, widget=None, label=None,
|
2013-03-26 04:25:53 +08:00
|
|
|
initial=None, help_text='', *args, **kwargs):
|
2008-03-20 06:29:11 +08:00
|
|
|
self.path, self.match, self.recursive = path, match, recursive
|
2012-04-22 22:44:08 +08:00
|
|
|
self.allow_files, self.allow_folders = allow_files, allow_folders
|
2008-03-20 06:29:11 +08:00
|
|
|
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:
|
2010-12-02 08:49:15 +08:00
|
|
|
for root, dirs, files in sorted(os.walk(self.path)):
|
2012-04-22 22:44:08 +08:00
|
|
|
if self.allow_files:
|
|
|
|
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)))
|
|
|
|
if self.allow_folders:
|
|
|
|
for f in dirs:
|
2012-05-16 23:56:56 +08:00
|
|
|
if f == '__pycache__':
|
|
|
|
continue
|
2012-04-22 22:44:08 +08:00
|
|
|
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)))
|
2008-03-20 06:29:11 +08:00
|
|
|
else:
|
|
|
|
try:
|
2010-12-02 08:49:15 +08:00
|
|
|
for f in sorted(os.listdir(self.path)):
|
2012-05-16 23:56:56 +08:00
|
|
|
if f == '__pycache__':
|
|
|
|
continue
|
2008-03-20 06:29:11 +08:00
|
|
|
full_file = os.path.join(self.path, f)
|
2012-04-22 22:44:08 +08:00
|
|
|
if (((self.allow_files and os.path.isfile(full_file)) or
|
|
|
|
(self.allow_folders and os.path.isdir(full_file))) and
|
|
|
|
(self.match is None or self.match_re.search(f))):
|
2008-03-20 06:29:11 +08:00
|
|
|
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 = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid_date': _('Enter a valid date.'),
|
|
|
|
'invalid_time': _('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).
|
2013-03-07 16:21:59 +08:00
|
|
|
if data_list[0] in self.empty_values:
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid_date'])
|
2013-03-07 16:21:59 +08:00
|
|
|
if data_list[1] in self.empty_values:
|
2007-10-28 13:40:26 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid_time'])
|
2011-11-18 21:01:06 +08:00
|
|
|
result = datetime.datetime.combine(*data_list)
|
|
|
|
return from_current_timezone(result)
|
2007-01-24 04:23:07 +08:00
|
|
|
return None
|
2007-09-16 19:38:32 +08:00
|
|
|
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
class IPAddressField(CharField):
|
|
|
|
default_validators = [validators.validate_ipv4_address]
|
2007-10-28 13:40:26 +08:00
|
|
|
|
2013-02-24 01:42:53 +08:00
|
|
|
def to_python(self, value):
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2013-02-24 01:42:53 +08:00
|
|
|
return ''
|
|
|
|
return value.strip()
|
2013-02-23 21:44:57 +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
|
|
|
|
2011-06-11 21:48:24 +08:00
|
|
|
class GenericIPAddressField(CharField):
|
|
|
|
def __init__(self, protocol='both', unpack_ipv4=False, *args, **kwargs):
|
|
|
|
self.unpack_ipv4 = unpack_ipv4
|
2013-03-14 23:19:59 +08:00
|
|
|
self.default_validators = validators.ip_address_validators(protocol, unpack_ipv4)[0]
|
2011-06-11 21:48:24 +08:00
|
|
|
super(GenericIPAddressField, self).__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
def to_python(self, value):
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2012-06-08 00:08:47 +08:00
|
|
|
return ''
|
2013-02-24 01:42:53 +08:00
|
|
|
value = value.strip()
|
2011-06-11 21:48:24 +08:00
|
|
|
if value and ':' in value:
|
2013-03-14 23:19:59 +08:00
|
|
|
return clean_ipv6_address(value, self.unpack_ipv4)
|
2011-06-11 21:48:24 +08:00
|
|
|
return value
|
|
|
|
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
class SlugField(CharField):
|
|
|
|
default_validators = [validators.validate_slug]
|