2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
Field classes
|
|
|
|
"""
|
|
|
|
|
2006-12-06 14:37:32 +08:00
|
|
|
from django.utils.translation import gettext
|
2006-12-06 03:55:51 +08:00
|
|
|
from util import ValidationError, smart_unicode
|
2007-01-09 13:12:25 +08:00
|
|
|
from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, CheckboxInput, Select, SelectMultiple
|
2006-10-29 04:34:37 +08:00
|
|
|
import datetime
|
|
|
|
import re
|
|
|
|
import time
|
|
|
|
|
|
|
|
__all__ = (
|
|
|
|
'Field', 'CharField', 'IntegerField',
|
|
|
|
'DEFAULT_DATE_INPUT_FORMATS', 'DateField',
|
2006-12-15 04:35:32 +08:00
|
|
|
'DEFAULT_TIME_INPUT_FORMATS', 'TimeField',
|
2006-10-29 04:34:37 +08:00
|
|
|
'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField',
|
2006-11-02 07:52:43 +08:00
|
|
|
'RegexField', 'EmailField', 'URLField', 'BooleanField',
|
2006-11-02 11:16:12 +08:00
|
|
|
'ChoiceField', 'MultipleChoiceField',
|
2006-11-05 04:49:59 +08:00
|
|
|
'ComboField',
|
2006-10-29 04:34:37 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
# These values, if given to to_python(), will trigger the self.required check.
|
|
|
|
EMPTY_VALUES = (None, '')
|
|
|
|
|
2006-11-02 11:16:12 +08:00
|
|
|
try:
|
|
|
|
set # Only available in Python 2.4+
|
|
|
|
except NameError:
|
|
|
|
from sets import Set as set # Python 2.3 fallback
|
|
|
|
|
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".
|
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
|
|
|
|
|
2006-12-28 08:01:52 +08:00
|
|
|
def __init__(self, required=True, widget=None, label=None, initial=None):
|
|
|
|
# required -- Boolean that specifies whether the field is required.
|
|
|
|
# True by default.
|
|
|
|
# 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.
|
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
|
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
|
|
|
|
|
|
|
# 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
|
|
|
|
|
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.
|
|
|
|
"""
|
|
|
|
if self.required and value in EMPTY_VALUES:
|
2006-12-06 14:37:32 +08:00
|
|
|
raise ValidationError(gettext(u'This field is required.'))
|
2006-10-29 04:34:37 +08:00
|
|
|
return value
|
|
|
|
|
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 {}
|
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
class CharField(Field):
|
2006-12-28 08:01:52 +08:00
|
|
|
def __init__(self, max_length=None, min_length=None, required=True, widget=None, label=None, initial=None):
|
2006-10-29 04:34:37 +08:00
|
|
|
self.max_length, self.min_length = max_length, min_length
|
2007-01-21 01:25:42 +08:00
|
|
|
super(CharField, self).__init__(required, widget, label, initial)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def clean(self, value):
|
2006-10-29 04:34:37 +08:00
|
|
|
"Validates max_length and min_length. Returns a Unicode object."
|
2007-01-21 01:25:42 +08:00
|
|
|
super(CharField, self).clean(value)
|
2006-12-16 07:07:41 +08:00
|
|
|
if value in EMPTY_VALUES:
|
2007-01-21 01:31:45 +08:00
|
|
|
return u''
|
2006-11-16 14:45:29 +08:00
|
|
|
value = smart_unicode(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
if self.max_length is not None and len(value) > self.max_length:
|
2006-12-06 14:37:32 +08:00
|
|
|
raise ValidationError(gettext(u'Ensure this value has at most %d characters.') % self.max_length)
|
2006-10-29 04:34:37 +08:00
|
|
|
if self.min_length is not None and len(value) < self.min_length:
|
2006-12-06 14:37:32 +08:00
|
|
|
raise ValidationError(gettext(u'Ensure this value has at least %d characters.') % self.min_length)
|
2006-10-29 04:34:37 +08:00
|
|
|
return value
|
|
|
|
|
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)):
|
|
|
|
return {'maxlength': str(self.max_length)}
|
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
class IntegerField(Field):
|
2006-12-28 08:01:52 +08:00
|
|
|
def __init__(self, max_value=None, min_value=None, required=True, widget=None, label=None, initial=None):
|
2006-12-16 07:18:47 +08:00
|
|
|
self.max_value, self.min_value = max_value, min_value
|
2007-01-21 01:25:42 +08:00
|
|
|
super(IntegerField, self).__init__(required, widget, label, initial)
|
2006-12-16 07:18:47 +08:00
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def clean(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
|
|
|
"""
|
2006-11-05 04:49:59 +08:00
|
|
|
super(IntegerField, self).clean(value)
|
2007-01-21 01:31:45 +08:00
|
|
|
if value in EMPTY_VALUES:
|
2007-01-13 13:08:07 +08:00
|
|
|
return None
|
2006-10-29 04:34:37 +08:00
|
|
|
try:
|
2006-12-16 07:18:47 +08:00
|
|
|
value = int(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
except (ValueError, TypeError):
|
2006-12-06 14:37:32 +08:00
|
|
|
raise ValidationError(gettext(u'Enter a whole number.'))
|
2006-12-16 07:18:47 +08:00
|
|
|
if self.max_value is not None and value > self.max_value:
|
|
|
|
raise ValidationError(gettext(u'Ensure this value is less than or equal to %s.') % self.max_value)
|
|
|
|
if self.min_value is not None and value < self.min_value:
|
|
|
|
raise ValidationError(gettext(u'Ensure this value is greater than or equal to %s.') % self.min_value)
|
|
|
|
return value
|
2006-10-29 04:34:37 +08:00
|
|
|
|
|
|
|
DEFAULT_DATE_INPUT_FORMATS = (
|
|
|
|
'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
|
|
|
|
'%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
|
|
|
|
'%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
|
|
|
|
'%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
|
|
|
|
'%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
|
|
|
|
)
|
|
|
|
|
|
|
|
class DateField(Field):
|
2006-12-28 08:01:52 +08:00
|
|
|
def __init__(self, input_formats=None, required=True, widget=None, label=None, initial=None):
|
2007-01-21 01:25:42 +08:00
|
|
|
super(DateField, self).__init__(required, widget, label, initial)
|
2006-10-29 04:34:37 +08:00
|
|
|
self.input_formats = input_formats or DEFAULT_DATE_INPUT_FORMATS
|
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def clean(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.
|
|
|
|
"""
|
2007-01-21 01:25:42 +08:00
|
|
|
super(DateField, self).clean(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
if value in EMPTY_VALUES:
|
|
|
|
return None
|
|
|
|
if isinstance(value, datetime.datetime):
|
|
|
|
return value.date()
|
|
|
|
if isinstance(value, datetime.date):
|
|
|
|
return value
|
|
|
|
for format in self.input_formats:
|
|
|
|
try:
|
|
|
|
return datetime.date(*time.strptime(value, format)[:3])
|
|
|
|
except ValueError:
|
|
|
|
continue
|
2006-12-06 14:37:32 +08:00
|
|
|
raise ValidationError(gettext(u'Enter a valid date.'))
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-12-15 04:35:32 +08:00
|
|
|
DEFAULT_TIME_INPUT_FORMATS = (
|
|
|
|
'%H:%M:%S', # '14:30:59'
|
|
|
|
'%H:%M', # '14:30'
|
|
|
|
)
|
|
|
|
|
|
|
|
class TimeField(Field):
|
2006-12-28 08:01:52 +08:00
|
|
|
def __init__(self, input_formats=None, required=True, widget=None, label=None, initial=None):
|
2007-01-21 01:25:42 +08:00
|
|
|
super(TimeField, self).__init__(required, widget, label, initial)
|
2006-12-15 04:35:32 +08:00
|
|
|
self.input_formats = input_formats or DEFAULT_TIME_INPUT_FORMATS
|
|
|
|
|
|
|
|
def clean(self, value):
|
|
|
|
"""
|
|
|
|
Validates that the input can be converted to a time. Returns a Python
|
|
|
|
datetime.time object.
|
|
|
|
"""
|
2007-01-21 01:25:42 +08:00
|
|
|
super(TimeField, self).clean(value)
|
2006-12-15 04:35:32 +08:00
|
|
|
if value in EMPTY_VALUES:
|
|
|
|
return None
|
|
|
|
if isinstance(value, datetime.time):
|
|
|
|
return value
|
|
|
|
for format in self.input_formats:
|
|
|
|
try:
|
|
|
|
return datetime.time(*time.strptime(value, format)[3:6])
|
|
|
|
except ValueError:
|
|
|
|
continue
|
|
|
|
raise ValidationError(gettext(u'Enter a valid time.'))
|
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
DEFAULT_DATETIME_INPUT_FORMATS = (
|
|
|
|
'%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
|
|
|
|
'%Y-%m-%d %H:%M', # '2006-10-25 14:30'
|
|
|
|
'%Y-%m-%d', # '2006-10-25'
|
|
|
|
'%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
|
|
|
|
'%m/%d/%Y %H:%M', # '10/25/2006 14:30'
|
|
|
|
'%m/%d/%Y', # '10/25/2006'
|
|
|
|
'%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
|
|
|
|
'%m/%d/%y %H:%M', # '10/25/06 14:30'
|
|
|
|
'%m/%d/%y', # '10/25/06'
|
|
|
|
)
|
|
|
|
|
|
|
|
class DateTimeField(Field):
|
2006-12-28 08:01:52 +08:00
|
|
|
def __init__(self, input_formats=None, required=True, widget=None, label=None, initial=None):
|
2007-01-21 01:25:42 +08:00
|
|
|
super(DateTimeField, self).__init__(required, widget, label, initial)
|
2006-10-29 04:34:37 +08:00
|
|
|
self.input_formats = input_formats or DEFAULT_DATETIME_INPUT_FORMATS
|
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def clean(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.
|
|
|
|
"""
|
2007-01-21 01:25:42 +08:00
|
|
|
super(DateTimeField, self).clean(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
if value in EMPTY_VALUES:
|
|
|
|
return None
|
|
|
|
if isinstance(value, datetime.datetime):
|
|
|
|
return value
|
|
|
|
if isinstance(value, datetime.date):
|
|
|
|
return datetime.datetime(value.year, value.month, value.day)
|
|
|
|
for format in self.input_formats:
|
|
|
|
try:
|
|
|
|
return datetime.datetime(*time.strptime(value, format)[:6])
|
|
|
|
except ValueError:
|
|
|
|
continue
|
2006-12-06 14:37:32 +08:00
|
|
|
raise ValidationError(gettext(u'Enter a valid date/time.'))
|
2006-10-29 04:34:37 +08:00
|
|
|
|
|
|
|
class RegexField(Field):
|
2006-12-27 07:46:10 +08:00
|
|
|
def __init__(self, regex, max_length=None, min_length=None, error_message=None,
|
2006-12-28 08:01:52 +08:00
|
|
|
required=True, widget=None, label=None, initial=None):
|
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-01-21 01:25:42 +08:00
|
|
|
super(RegexField, self).__init__(required, widget, label, initial)
|
2006-10-29 04:34:37 +08:00
|
|
|
if isinstance(regex, basestring):
|
|
|
|
regex = re.compile(regex)
|
|
|
|
self.regex = regex
|
2006-12-27 07:46:10 +08:00
|
|
|
self.max_length, self.min_length = max_length, min_length
|
2006-12-06 14:37:32 +08:00
|
|
|
self.error_message = error_message or gettext(u'Enter a valid value.')
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def clean(self, value):
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
Validates that the input matches the regular expression. Returns a
|
|
|
|
Unicode object.
|
|
|
|
"""
|
2007-01-21 01:25:42 +08:00
|
|
|
super(RegexField, self).clean(value)
|
2007-01-21 01:31:45 +08:00
|
|
|
if value in EMPTY_VALUES:
|
|
|
|
value = u''
|
2006-11-16 14:45:29 +08:00
|
|
|
value = smart_unicode(value)
|
2007-01-21 01:31:45 +08:00
|
|
|
if value == u'':
|
2006-11-27 08:49:26 +08:00
|
|
|
return value
|
2006-12-27 07:46:10 +08:00
|
|
|
if self.max_length is not None and len(value) > self.max_length:
|
|
|
|
raise ValidationError(gettext(u'Ensure this value has at most %d characters.') % self.max_length)
|
|
|
|
if self.min_length is not None and len(value) < self.min_length:
|
|
|
|
raise ValidationError(gettext(u'Ensure this value has at least %d characters.') % self.min_length)
|
2006-11-27 08:49:26 +08:00
|
|
|
if not self.regex.search(value):
|
2006-10-29 04:34:37 +08:00
|
|
|
raise ValidationError(self.error_message)
|
|
|
|
return value
|
|
|
|
|
|
|
|
email_re = re.compile(
|
|
|
|
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom
|
|
|
|
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string
|
|
|
|
r')@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}$', re.IGNORECASE) # domain
|
|
|
|
|
|
|
|
class EmailField(RegexField):
|
2006-12-28 08:01:52 +08:00
|
|
|
def __init__(self, max_length=None, min_length=None, required=True, widget=None, label=None, initial=None):
|
|
|
|
RegexField.__init__(self, email_re, max_length, min_length, gettext(u'Enter a valid e-mail address.'), required, widget, label, initial)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-11-02 07:52:43 +08:00
|
|
|
url_re = re.compile(
|
|
|
|
r'^https?://' # http:// or https://
|
|
|
|
r'(?:[A-Z0-9-]+\.)+[A-Z]{2,6}' # domain
|
|
|
|
r'(?::\d+)?' # optional port
|
|
|
|
r'(?:/?|/\S+)$', re.IGNORECASE)
|
|
|
|
|
2006-11-07 10:32:33 +08:00
|
|
|
try:
|
|
|
|
from django.conf import settings
|
|
|
|
URL_VALIDATOR_USER_AGENT = settings.URL_VALIDATOR_USER_AGENT
|
|
|
|
except ImportError:
|
|
|
|
# It's OK if Django settings aren't configured.
|
|
|
|
URL_VALIDATOR_USER_AGENT = 'Django (http://www.djangoproject.com/)'
|
|
|
|
|
2006-11-02 07:52:43 +08:00
|
|
|
class URLField(RegexField):
|
2006-12-27 07:46:10 +08:00
|
|
|
def __init__(self, max_length=None, min_length=None, required=True, verify_exists=False, widget=None, label=None,
|
2006-12-28 08:01:52 +08:00
|
|
|
initial=None, validator_user_agent=URL_VALIDATOR_USER_AGENT):
|
2007-01-21 01:25:42 +08:00
|
|
|
super(URLField, self).__init__(url_re, max_length, min_length, gettext(u'Enter a valid URL.'), required, widget, label, initial)
|
2006-11-02 07:52:43 +08:00
|
|
|
self.verify_exists = verify_exists
|
2006-11-07 10:32:33 +08:00
|
|
|
self.user_agent = validator_user_agent
|
2006-11-02 07:52:43 +08:00
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def clean(self, value):
|
2007-01-21 01:25:42 +08:00
|
|
|
value = super(URLField, self).clean(value)
|
2007-01-21 01:31:45 +08:00
|
|
|
if value == u'':
|
2007-01-13 13:19:15 +08:00
|
|
|
return value
|
2006-11-02 07:52:43 +08:00
|
|
|
if self.verify_exists:
|
|
|
|
import urllib2
|
2006-11-07 10:32:33 +08:00
|
|
|
from django.conf import settings
|
|
|
|
headers = {
|
|
|
|
"Accept": "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
|
|
|
|
"Accept-Language": "en-us,en;q=0.5",
|
|
|
|
"Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
|
|
|
|
"Connection": "close",
|
|
|
|
"User-Agent": self.user_agent,
|
|
|
|
}
|
2006-11-02 07:52:43 +08:00
|
|
|
try:
|
2006-11-10 11:39:00 +08:00
|
|
|
req = urllib2.Request(value, None, headers)
|
2006-11-07 10:32:33 +08:00
|
|
|
u = urllib2.urlopen(req)
|
2006-11-02 07:52:43 +08:00
|
|
|
except ValueError:
|
2006-12-06 14:37:32 +08:00
|
|
|
raise ValidationError(gettext(u'Enter a valid URL.'))
|
2006-11-02 07:52:43 +08:00
|
|
|
except: # urllib2.URLError, httplib.InvalidURL, etc.
|
2006-12-06 14:37:32 +08:00
|
|
|
raise ValidationError(gettext(u'This URL appears to be a broken link.'))
|
2006-11-02 07:52:43 +08:00
|
|
|
return value
|
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
class BooleanField(Field):
|
|
|
|
widget = CheckboxInput
|
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def clean(self, value):
|
2006-10-29 04:34:37 +08:00
|
|
|
"Returns a Python boolean object."
|
2007-01-21 01:25:42 +08:00
|
|
|
super(BooleanField, self).clean(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
return bool(value)
|
2006-11-02 11:16:12 +08:00
|
|
|
|
|
|
|
class ChoiceField(Field):
|
2006-12-28 08:01:52 +08:00
|
|
|
def __init__(self, choices=(), required=True, widget=Select, label=None, initial=None):
|
2006-11-02 11:16:12 +08:00
|
|
|
if isinstance(widget, type):
|
2007-01-21 09:10:55 +08:00
|
|
|
widget = widget()
|
|
|
|
widget.choices = choices
|
2007-01-21 01:25:42 +08:00
|
|
|
super(ChoiceField, self).__init__(required, widget, label, initial)
|
2006-11-02 11:16:12 +08:00
|
|
|
self.choices = choices
|
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def clean(self, value):
|
2006-11-02 11:16:12 +08:00
|
|
|
"""
|
|
|
|
Validates that the input is in self.choices.
|
|
|
|
"""
|
2007-01-21 01:25:42 +08:00
|
|
|
value = super(ChoiceField, self).clean(value)
|
2007-01-21 01:31:45 +08:00
|
|
|
if value in EMPTY_VALUES:
|
|
|
|
value = u''
|
2006-11-16 14:45:29 +08:00
|
|
|
value = smart_unicode(value)
|
2007-01-21 01:31:45 +08:00
|
|
|
if value == u'':
|
2006-11-27 08:49:26 +08:00
|
|
|
return value
|
2006-11-02 11:16:12 +08:00
|
|
|
valid_values = set([str(k) for k, v in self.choices])
|
|
|
|
if value not in valid_values:
|
2006-12-06 14:37:32 +08:00
|
|
|
raise ValidationError(gettext(u'Select a valid choice. %s is not one of the available choices.') % value)
|
2006-11-02 11:16:12 +08:00
|
|
|
return value
|
|
|
|
|
|
|
|
class MultipleChoiceField(ChoiceField):
|
2007-01-09 13:12:25 +08:00
|
|
|
hidden_widget = MultipleHiddenInput
|
|
|
|
|
2006-12-28 08:01:52 +08:00
|
|
|
def __init__(self, choices=(), required=True, widget=SelectMultiple, label=None, initial=None):
|
2007-01-21 01:25:42 +08:00
|
|
|
super(MultipleChoiceField, self).__init__(choices, required, widget, label, initial)
|
2006-11-02 11:16:12 +08:00
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def clean(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:
|
2006-12-06 14:37:32 +08:00
|
|
|
raise ValidationError(gettext(u'This field is required.'))
|
2006-11-27 08:49:26 +08:00
|
|
|
elif not self.required and not value:
|
|
|
|
return []
|
|
|
|
if not isinstance(value, (list, tuple)):
|
2006-12-06 14:37:32 +08:00
|
|
|
raise ValidationError(gettext(u'Enter a list of values.'))
|
2006-11-02 11:16:12 +08:00
|
|
|
new_value = []
|
|
|
|
for val in value:
|
2006-11-16 14:45:29 +08:00
|
|
|
val = smart_unicode(val)
|
|
|
|
new_value.append(val)
|
2006-11-02 11:16:12 +08:00
|
|
|
# Validate that each value in the value list is in self.choices.
|
2006-12-08 13:54:14 +08:00
|
|
|
valid_values = set([smart_unicode(k) for k, v in self.choices])
|
2006-11-02 11:16:12 +08:00
|
|
|
for val in new_value:
|
|
|
|
if val not in valid_values:
|
2006-12-06 14:37:32 +08:00
|
|
|
raise ValidationError(gettext(u'Select a valid choice. %s is not one of the available choices.') % val)
|
2006-11-02 11:16:12 +08:00
|
|
|
return new_value
|
2006-11-05 04:49:59 +08:00
|
|
|
|
|
|
|
class ComboField(Field):
|
2006-12-28 08:01:52 +08:00
|
|
|
def __init__(self, fields=(), required=True, widget=None, label=None, initial=None):
|
2007-01-21 01:25:42 +08:00
|
|
|
super(ComboField, self).__init__(required, widget, label, initial)
|
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
|