PageRenderTime 56ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/django/forms/fields.py

https://bitbucket.org/taxilian/racecontrol5
Python | 900 lines | 792 code | 31 blank | 77 comment | 61 complexity | 663f5da87e9a7c60fe7abfbf4066d8c1 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. Field classes.
  3. """
  4. import datetime
  5. import os
  6. import re
  7. import time
  8. import urlparse
  9. import warnings
  10. from decimal import Decimal, DecimalException
  11. try:
  12. from cStringIO import StringIO
  13. except ImportError:
  14. from StringIO import StringIO
  15. from django.core.exceptions import ValidationError
  16. from django.core import validators
  17. import django.utils.copycompat as copy
  18. from django.utils import formats
  19. from django.utils.translation import ugettext_lazy as _
  20. from django.utils.encoding import smart_unicode, smart_str
  21. from django.utils.functional import lazy
  22. # Provide this import for backwards compatibility.
  23. from django.core.validators import EMPTY_VALUES
  24. from util import ErrorList
  25. from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, \
  26. FileInput, CheckboxInput, Select, NullBooleanSelect, SelectMultiple, \
  27. DateInput, DateTimeInput, TimeInput, SplitDateTimeWidget, SplitHiddenDateTimeWidget
  28. __all__ = (
  29. 'Field', 'CharField', 'IntegerField',
  30. 'DEFAULT_DATE_INPUT_FORMATS', 'DateField',
  31. 'DEFAULT_TIME_INPUT_FORMATS', 'TimeField',
  32. 'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField', 'TimeField',
  33. 'RegexField', 'EmailField', 'FileField', 'ImageField', 'URLField',
  34. 'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField',
  35. 'ComboField', 'MultiValueField', 'FloatField', 'DecimalField',
  36. 'SplitDateTimeField', 'IPAddressField', 'FilePathField', 'SlugField',
  37. 'TypedChoiceField'
  38. )
  39. def en_format(name):
  40. """
  41. Helper function to stay backward compatible.
  42. """
  43. from django.conf.locale.en import formats
  44. warnings.warn(
  45. "`django.forms.fields.DEFAULT_%s` is deprecated; use `django.utils.formats.get_format('%s')` instead." % (name, name),
  46. PendingDeprecationWarning
  47. )
  48. return getattr(formats, name)
  49. DEFAULT_DATE_INPUT_FORMATS = lazy(lambda: en_format('DATE_INPUT_FORMATS'), tuple, list)()
  50. DEFAULT_TIME_INPUT_FORMATS = lazy(lambda: en_format('TIME_INPUT_FORMATS'), tuple, list)()
  51. DEFAULT_DATETIME_INPUT_FORMATS = lazy(lambda: en_format('DATETIME_INPUT_FORMATS'), tuple, list)()
  52. class Field(object):
  53. widget = TextInput # Default widget to use when rendering this type of Field.
  54. hidden_widget = HiddenInput # Default widget to use when rendering this as "hidden".
  55. default_validators = [] # Default set of validators
  56. default_error_messages = {
  57. 'required': _(u'This field is required.'),
  58. 'invalid': _(u'Enter a valid value.'),
  59. }
  60. # Tracks each time a Field instance is created. Used to retain order.
  61. creation_counter = 0
  62. def __init__(self, required=True, widget=None, label=None, initial=None,
  63. help_text=None, error_messages=None, show_hidden_initial=False,
  64. validators=[], localize=False):
  65. # required -- Boolean that specifies whether the field is required.
  66. # True by default.
  67. # widget -- A Widget class, or instance of a Widget class, that should
  68. # be used for this Field when displaying it. Each Field has a
  69. # default Widget that it'll use if you don't specify this. In
  70. # most cases, the default widget is TextInput.
  71. # label -- A verbose name for this field, for use in displaying this
  72. # field in a form. By default, Django will use a "pretty"
  73. # version of the form field name, if the Field is part of a
  74. # Form.
  75. # initial -- A value to use in this Field's initial display. This value
  76. # is *not* used as a fallback if data isn't given.
  77. # help_text -- An optional string to use as "help text" for this Field.
  78. # error_messages -- An optional dictionary to override the default
  79. # messages that the field will raise.
  80. # show_hidden_initial -- Boolean that specifies if it is needed to render a
  81. # hidden widget with initial value after widget.
  82. # validators -- List of addtional validators to use
  83. # localize -- Boolean that specifies if the field should be localized.
  84. if label is not None:
  85. label = smart_unicode(label)
  86. self.required, self.label, self.initial = required, label, initial
  87. self.show_hidden_initial = show_hidden_initial
  88. if help_text is None:
  89. self.help_text = u''
  90. else:
  91. self.help_text = smart_unicode(help_text)
  92. widget = widget or self.widget
  93. if isinstance(widget, type):
  94. widget = widget()
  95. # Trigger the localization machinery if needed.
  96. self.localize = localize
  97. if self.localize:
  98. widget.is_localized = True
  99. # Hook into self.widget_attrs() for any Field-specific HTML attributes.
  100. extra_attrs = self.widget_attrs(widget)
  101. if extra_attrs:
  102. widget.attrs.update(extra_attrs)
  103. self.widget = widget
  104. # Increase the creation counter, and save our local copy.
  105. self.creation_counter = Field.creation_counter
  106. Field.creation_counter += 1
  107. messages = {}
  108. for c in reversed(self.__class__.__mro__):
  109. messages.update(getattr(c, 'default_error_messages', {}))
  110. messages.update(error_messages or {})
  111. self.error_messages = messages
  112. self.validators = self.default_validators + validators
  113. def prepare_value(self, value):
  114. return value
  115. def to_python(self, value):
  116. return value
  117. def validate(self, value):
  118. if value in validators.EMPTY_VALUES and self.required:
  119. raise ValidationError(self.error_messages['required'])
  120. def run_validators(self, value):
  121. if value in validators.EMPTY_VALUES:
  122. return
  123. errors = []
  124. for v in self.validators:
  125. try:
  126. v(value)
  127. except ValidationError, e:
  128. if hasattr(e, 'code') and e.code in self.error_messages:
  129. message = self.error_messages[e.code]
  130. if e.params:
  131. message = message % e.params
  132. errors.append(message)
  133. else:
  134. errors.extend(e.messages)
  135. if errors:
  136. raise ValidationError(errors)
  137. def clean(self, value):
  138. """
  139. Validates the given value and returns its "cleaned" value as an
  140. appropriate Python object.
  141. Raises ValidationError for any errors.
  142. """
  143. value = self.to_python(value)
  144. self.validate(value)
  145. self.run_validators(value)
  146. return value
  147. def widget_attrs(self, widget):
  148. """
  149. Given a Widget instance (*not* a Widget class), returns a dictionary of
  150. any HTML attributes that should be added to the Widget, based on this
  151. Field.
  152. """
  153. return {}
  154. def __deepcopy__(self, memo):
  155. result = copy.copy(self)
  156. memo[id(self)] = result
  157. result.widget = copy.deepcopy(self.widget, memo)
  158. return result
  159. class CharField(Field):
  160. def __init__(self, max_length=None, min_length=None, *args, **kwargs):
  161. self.max_length, self.min_length = max_length, min_length
  162. super(CharField, self).__init__(*args, **kwargs)
  163. if min_length is not None:
  164. self.validators.append(validators.MinLengthValidator(min_length))
  165. if max_length is not None:
  166. self.validators.append(validators.MaxLengthValidator(max_length))
  167. def to_python(self, value):
  168. "Returns a Unicode object."
  169. if value in validators.EMPTY_VALUES:
  170. return u''
  171. return smart_unicode(value)
  172. def widget_attrs(self, widget):
  173. if self.max_length is not None and isinstance(widget, (TextInput, PasswordInput)):
  174. # The HTML attribute is maxlength, not max_length.
  175. return {'maxlength': str(self.max_length)}
  176. class IntegerField(Field):
  177. default_error_messages = {
  178. 'invalid': _(u'Enter a whole number.'),
  179. 'max_value': _(u'Ensure this value is less than or equal to %(limit_value)s.'),
  180. 'min_value': _(u'Ensure this value is greater than or equal to %(limit_value)s.'),
  181. }
  182. def __init__(self, max_value=None, min_value=None, *args, **kwargs):
  183. self.max_value, self.min_value = max_value, min_value
  184. super(IntegerField, self).__init__(*args, **kwargs)
  185. if max_value is not None:
  186. self.validators.append(validators.MaxValueValidator(max_value))
  187. if min_value is not None:
  188. self.validators.append(validators.MinValueValidator(min_value))
  189. def to_python(self, value):
  190. """
  191. Validates that int() can be called on the input. Returns the result
  192. of int(). Returns None for empty values.
  193. """
  194. value = super(IntegerField, self).to_python(value)
  195. if value in validators.EMPTY_VALUES:
  196. return None
  197. if self.localize:
  198. value = formats.sanitize_separators(value)
  199. try:
  200. value = int(str(value))
  201. except (ValueError, TypeError):
  202. raise ValidationError(self.error_messages['invalid'])
  203. return value
  204. class FloatField(IntegerField):
  205. default_error_messages = {
  206. 'invalid': _(u'Enter a number.'),
  207. }
  208. def to_python(self, value):
  209. """
  210. Validates that float() can be called on the input. Returns the result
  211. of float(). Returns None for empty values.
  212. """
  213. value = super(IntegerField, self).to_python(value)
  214. if value in validators.EMPTY_VALUES:
  215. return None
  216. if self.localize:
  217. value = formats.sanitize_separators(value)
  218. try:
  219. value = float(value)
  220. except (ValueError, TypeError):
  221. raise ValidationError(self.error_messages['invalid'])
  222. return value
  223. class DecimalField(Field):
  224. default_error_messages = {
  225. 'invalid': _(u'Enter a number.'),
  226. 'max_value': _(u'Ensure this value is less than or equal to %(limit_value)s.'),
  227. 'min_value': _(u'Ensure this value is greater than or equal to %(limit_value)s.'),
  228. 'max_digits': _('Ensure that there are no more than %s digits in total.'),
  229. 'max_decimal_places': _('Ensure that there are no more than %s decimal places.'),
  230. 'max_whole_digits': _('Ensure that there are no more than %s digits before the decimal point.')
  231. }
  232. def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs):
  233. self.max_value, self.min_value = max_value, min_value
  234. self.max_digits, self.decimal_places = max_digits, decimal_places
  235. Field.__init__(self, *args, **kwargs)
  236. if max_value is not None:
  237. self.validators.append(validators.MaxValueValidator(max_value))
  238. if min_value is not None:
  239. self.validators.append(validators.MinValueValidator(min_value))
  240. def to_python(self, value):
  241. """
  242. Validates that the input is a decimal number. Returns a Decimal
  243. instance. Returns None for empty values. Ensures that there are no more
  244. than max_digits in the number, and no more than decimal_places digits
  245. after the decimal point.
  246. """
  247. if value in validators.EMPTY_VALUES:
  248. return None
  249. if self.localize:
  250. value = formats.sanitize_separators(value)
  251. value = smart_str(value).strip()
  252. try:
  253. value = Decimal(value)
  254. except DecimalException:
  255. raise ValidationError(self.error_messages['invalid'])
  256. return value
  257. def validate(self, value):
  258. super(DecimalField, self).validate(value)
  259. if value in validators.EMPTY_VALUES:
  260. return
  261. # Check for NaN, Inf and -Inf values. We can't compare directly for NaN,
  262. # since it is never equal to itself. However, NaN is the only value that
  263. # isn't equal to itself, so we can use this to identify NaN
  264. if value != value or value == Decimal("Inf") or value == Decimal("-Inf"):
  265. raise ValidationError(self.error_messages['invalid'])
  266. sign, digittuple, exponent = value.as_tuple()
  267. decimals = abs(exponent)
  268. # digittuple doesn't include any leading zeros.
  269. digits = len(digittuple)
  270. if decimals > digits:
  271. # We have leading zeros up to or past the decimal point. Count
  272. # everything past the decimal point as a digit. We do not count
  273. # 0 before the decimal point as a digit since that would mean
  274. # we would not allow max_digits = decimal_places.
  275. digits = decimals
  276. whole_digits = digits - decimals
  277. if self.max_digits is not None and digits > self.max_digits:
  278. raise ValidationError(self.error_messages['max_digits'] % self.max_digits)
  279. if self.decimal_places is not None and decimals > self.decimal_places:
  280. raise ValidationError(self.error_messages['max_decimal_places'] % self.decimal_places)
  281. if self.max_digits is not None and self.decimal_places is not None and whole_digits > (self.max_digits - self.decimal_places):
  282. raise ValidationError(self.error_messages['max_whole_digits'] % (self.max_digits - self.decimal_places))
  283. return value
  284. class DateField(Field):
  285. widget = DateInput
  286. default_error_messages = {
  287. 'invalid': _(u'Enter a valid date.'),
  288. }
  289. def __init__(self, input_formats=None, *args, **kwargs):
  290. super(DateField, self).__init__(*args, **kwargs)
  291. self.input_formats = input_formats
  292. def to_python(self, value):
  293. """
  294. Validates that the input can be converted to a date. Returns a Python
  295. datetime.date object.
  296. """
  297. if value in validators.EMPTY_VALUES:
  298. return None
  299. if isinstance(value, datetime.datetime):
  300. return value.date()
  301. if isinstance(value, datetime.date):
  302. return value
  303. for format in self.input_formats or formats.get_format('DATE_INPUT_FORMATS'):
  304. try:
  305. return datetime.date(*time.strptime(value, format)[:3])
  306. except ValueError:
  307. continue
  308. raise ValidationError(self.error_messages['invalid'])
  309. class TimeField(Field):
  310. widget = TimeInput
  311. default_error_messages = {
  312. 'invalid': _(u'Enter a valid time.')
  313. }
  314. def __init__(self, input_formats=None, *args, **kwargs):
  315. super(TimeField, self).__init__(*args, **kwargs)
  316. self.input_formats = input_formats
  317. def to_python(self, value):
  318. """
  319. Validates that the input can be converted to a time. Returns a Python
  320. datetime.time object.
  321. """
  322. if value in validators.EMPTY_VALUES:
  323. return None
  324. if isinstance(value, datetime.time):
  325. return value
  326. for format in self.input_formats or formats.get_format('TIME_INPUT_FORMATS'):
  327. try:
  328. return datetime.time(*time.strptime(value, format)[3:6])
  329. except ValueError:
  330. continue
  331. raise ValidationError(self.error_messages['invalid'])
  332. class DateTimeField(Field):
  333. widget = DateTimeInput
  334. default_error_messages = {
  335. 'invalid': _(u'Enter a valid date/time.'),
  336. }
  337. def __init__(self, input_formats=None, *args, **kwargs):
  338. super(DateTimeField, self).__init__(*args, **kwargs)
  339. self.input_formats = input_formats
  340. def to_python(self, value):
  341. """
  342. Validates that the input can be converted to a datetime. Returns a
  343. Python datetime.datetime object.
  344. """
  345. if value in validators.EMPTY_VALUES:
  346. return None
  347. if isinstance(value, datetime.datetime):
  348. return value
  349. if isinstance(value, datetime.date):
  350. return datetime.datetime(value.year, value.month, value.day)
  351. if isinstance(value, list):
  352. # Input comes from a SplitDateTimeWidget, for example. So, it's two
  353. # components: date and time.
  354. if len(value) != 2:
  355. raise ValidationError(self.error_messages['invalid'])
  356. if value[0] in validators.EMPTY_VALUES and value[1] in validators.EMPTY_VALUES:
  357. return None
  358. value = '%s %s' % tuple(value)
  359. for format in self.input_formats or formats.get_format('DATETIME_INPUT_FORMATS'):
  360. try:
  361. return datetime.datetime(*time.strptime(value, format)[:6])
  362. except ValueError:
  363. continue
  364. raise ValidationError(self.error_messages['invalid'])
  365. class RegexField(CharField):
  366. def __init__(self, regex, max_length=None, min_length=None, error_message=None, *args, **kwargs):
  367. """
  368. regex can be either a string or a compiled regular expression object.
  369. error_message is an optional error message to use, if
  370. 'Enter a valid value' is too generic for you.
  371. """
  372. # error_message is just kept for backwards compatibility:
  373. if error_message:
  374. error_messages = kwargs.get('error_messages') or {}
  375. error_messages['invalid'] = error_message
  376. kwargs['error_messages'] = error_messages
  377. super(RegexField, self).__init__(max_length, min_length, *args, **kwargs)
  378. if isinstance(regex, basestring):
  379. regex = re.compile(regex)
  380. self.regex = regex
  381. self.validators.append(validators.RegexValidator(regex=regex))
  382. class EmailField(CharField):
  383. default_error_messages = {
  384. 'invalid': _(u'Enter a valid e-mail address.'),
  385. }
  386. default_validators = [validators.validate_email]
  387. def clean(self, value):
  388. value = self.to_python(value).strip()
  389. return super(EmailField, self).clean(value)
  390. class FileField(Field):
  391. widget = FileInput
  392. default_error_messages = {
  393. 'invalid': _(u"No file was submitted. Check the encoding type on the form."),
  394. 'missing': _(u"No file was submitted."),
  395. 'empty': _(u"The submitted file is empty."),
  396. 'max_length': _(u'Ensure this filename has at most %(max)d characters (it has %(length)d).'),
  397. }
  398. def __init__(self, *args, **kwargs):
  399. self.max_length = kwargs.pop('max_length', None)
  400. super(FileField, self).__init__(*args, **kwargs)
  401. def to_python(self, data):
  402. if data in validators.EMPTY_VALUES:
  403. return None
  404. # UploadedFile objects should have name and size attributes.
  405. try:
  406. file_name = data.name
  407. file_size = data.size
  408. except AttributeError:
  409. raise ValidationError(self.error_messages['invalid'])
  410. if self.max_length is not None and len(file_name) > self.max_length:
  411. error_values = {'max': self.max_length, 'length': len(file_name)}
  412. raise ValidationError(self.error_messages['max_length'] % error_values)
  413. if not file_name:
  414. raise ValidationError(self.error_messages['invalid'])
  415. if not file_size:
  416. raise ValidationError(self.error_messages['empty'])
  417. return data
  418. def clean(self, data, initial=None):
  419. if not data and initial:
  420. return initial
  421. return super(FileField, self).clean(data)
  422. class ImageField(FileField):
  423. default_error_messages = {
  424. 'invalid_image': _(u"Upload a valid image. The file you uploaded was either not an image or a corrupted image."),
  425. }
  426. def to_python(self, data):
  427. """
  428. Checks that the file-upload field data contains a valid image (GIF, JPG,
  429. PNG, possibly others -- whatever the Python Imaging Library supports).
  430. """
  431. f = super(ImageField, self).to_python(data)
  432. if f is None:
  433. return None
  434. # Try to import PIL in either of the two ways it can end up installed.
  435. try:
  436. from PIL import Image
  437. except ImportError:
  438. import Image
  439. # We need to get a file object for PIL. We might have a path or we might
  440. # have to read the data into memory.
  441. if hasattr(data, 'temporary_file_path'):
  442. file = data.temporary_file_path()
  443. else:
  444. if hasattr(data, 'read'):
  445. file = StringIO(data.read())
  446. else:
  447. file = StringIO(data['content'])
  448. try:
  449. # load() is the only method that can spot a truncated JPEG,
  450. # but it cannot be called sanely after verify()
  451. trial_image = Image.open(file)
  452. trial_image.load()
  453. # Since we're about to use the file again we have to reset the
  454. # file object if possible.
  455. if hasattr(file, 'reset'):
  456. file.reset()
  457. # verify() is the only method that can spot a corrupt PNG,
  458. # but it must be called immediately after the constructor
  459. trial_image = Image.open(file)
  460. trial_image.verify()
  461. except ImportError:
  462. # Under PyPy, it is possible to import PIL. However, the underlying
  463. # _imaging C module isn't available, so an ImportError will be
  464. # raised. Catch and re-raise.
  465. raise
  466. except Exception: # Python Imaging Library doesn't recognize it as an image
  467. raise ValidationError(self.error_messages['invalid_image'])
  468. if hasattr(f, 'seek') and callable(f.seek):
  469. f.seek(0)
  470. return f
  471. class URLField(CharField):
  472. default_error_messages = {
  473. 'invalid': _(u'Enter a valid URL.'),
  474. 'invalid_link': _(u'This URL appears to be a broken link.'),
  475. }
  476. def __init__(self, max_length=None, min_length=None, verify_exists=False,
  477. validator_user_agent=validators.URL_VALIDATOR_USER_AGENT, *args, **kwargs):
  478. super(URLField, self).__init__(max_length, min_length, *args,
  479. **kwargs)
  480. self.validators.append(validators.URLValidator(verify_exists=verify_exists, validator_user_agent=validator_user_agent))
  481. def to_python(self, value):
  482. if value:
  483. url_fields = list(urlparse.urlsplit(value))
  484. if not url_fields[0]:
  485. # If no URL scheme given, assume http://
  486. url_fields[0] = 'http'
  487. if not url_fields[1]:
  488. # Assume that if no domain is provided, that the path segment
  489. # contains the domain.
  490. url_fields[1] = url_fields[2]
  491. url_fields[2] = ''
  492. # Rebuild the url_fields list, since the domain segment may now
  493. # contain the path too.
  494. value = urlparse.urlunsplit(url_fields)
  495. url_fields = list(urlparse.urlsplit(value))
  496. if not url_fields[2]:
  497. # the path portion may need to be added before query params
  498. url_fields[2] = '/'
  499. value = urlparse.urlunsplit(url_fields)
  500. return super(URLField, self).to_python(value)
  501. class BooleanField(Field):
  502. widget = CheckboxInput
  503. def to_python(self, value):
  504. """Returns a Python boolean object."""
  505. # Explicitly check for the string 'False', which is what a hidden field
  506. # will submit for False. Also check for '0', since this is what
  507. # RadioSelect will provide. Because bool("True") == bool('1') == True,
  508. # we don't need to handle that explicitly.
  509. if value in ('False', '0'):
  510. value = False
  511. else:
  512. value = bool(value)
  513. value = super(BooleanField, self).to_python(value)
  514. if not value and self.required:
  515. raise ValidationError(self.error_messages['required'])
  516. return value
  517. class NullBooleanField(BooleanField):
  518. """
  519. A field whose valid values are None, True and False. Invalid values are
  520. cleaned to None.
  521. """
  522. widget = NullBooleanSelect
  523. def to_python(self, value):
  524. """
  525. Explicitly checks for the string 'True' and 'False', which is what a
  526. hidden field will submit for True and False, and for '1' and '0', which
  527. is what a RadioField will submit. Unlike the Booleanfield we need to
  528. explicitly check for True, because we are not using the bool() function
  529. """
  530. if value in (True, 'True', '1'):
  531. return True
  532. elif value in (False, 'False', '0'):
  533. return False
  534. else:
  535. return None
  536. def validate(self, value):
  537. pass
  538. class ChoiceField(Field):
  539. widget = Select
  540. default_error_messages = {
  541. 'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),
  542. }
  543. def __init__(self, choices=(), required=True, widget=None, label=None,
  544. initial=None, help_text=None, *args, **kwargs):
  545. super(ChoiceField, self).__init__(required=required, widget=widget, label=label,
  546. initial=initial, help_text=help_text, *args, **kwargs)
  547. self.choices = choices
  548. def _get_choices(self):
  549. return self._choices
  550. def _set_choices(self, value):
  551. # Setting choices also sets the choices on the widget.
  552. # choices can be any iterable, but we call list() on it because
  553. # it will be consumed more than once.
  554. self._choices = self.widget.choices = list(value)
  555. choices = property(_get_choices, _set_choices)
  556. def to_python(self, value):
  557. "Returns a Unicode object."
  558. if value in validators.EMPTY_VALUES:
  559. return u''
  560. return smart_unicode(value)
  561. def validate(self, value):
  562. """
  563. Validates that the input is in self.choices.
  564. """
  565. super(ChoiceField, self).validate(value)
  566. if value and not self.valid_value(value):
  567. raise ValidationError(self.error_messages['invalid_choice'] % {'value': value})
  568. def valid_value(self, value):
  569. "Check to see if the provided value is a valid choice"
  570. for k, v in self.choices:
  571. if isinstance(v, (list, tuple)):
  572. # This is an optgroup, so look inside the group for options
  573. for k2, v2 in v:
  574. if value == smart_unicode(k2):
  575. return True
  576. else:
  577. if value == smart_unicode(k):
  578. return True
  579. return False
  580. class TypedChoiceField(ChoiceField):
  581. def __init__(self, *args, **kwargs):
  582. self.coerce = kwargs.pop('coerce', lambda val: val)
  583. self.empty_value = kwargs.pop('empty_value', '')
  584. super(TypedChoiceField, self).__init__(*args, **kwargs)
  585. def to_python(self, value):
  586. """
  587. Validate that the value is in self.choices and can be coerced to the
  588. right type.
  589. """
  590. value = super(TypedChoiceField, self).to_python(value)
  591. super(TypedChoiceField, self).validate(value)
  592. if value == self.empty_value or value in validators.EMPTY_VALUES:
  593. return self.empty_value
  594. try:
  595. value = self.coerce(value)
  596. except (ValueError, TypeError, ValidationError):
  597. raise ValidationError(self.error_messages['invalid_choice'] % {'value': value})
  598. return value
  599. def validate(self, value):
  600. pass
  601. class MultipleChoiceField(ChoiceField):
  602. hidden_widget = MultipleHiddenInput
  603. widget = SelectMultiple
  604. default_error_messages = {
  605. 'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),
  606. 'invalid_list': _(u'Enter a list of values.'),
  607. }
  608. def to_python(self, value):
  609. if not value:
  610. return []
  611. elif not isinstance(value, (list, tuple)):
  612. raise ValidationError(self.error_messages['invalid_list'])
  613. return [smart_unicode(val) for val in value]
  614. def validate(self, value):
  615. """
  616. Validates that the input is a list or tuple.
  617. """
  618. if self.required and not value:
  619. raise ValidationError(self.error_messages['required'])
  620. # Validate that each value in the value list is in self.choices.
  621. for val in value:
  622. if not self.valid_value(val):
  623. raise ValidationError(self.error_messages['invalid_choice'] % {'value': val})
  624. class ComboField(Field):
  625. """
  626. A Field whose clean() method calls multiple Field clean() methods.
  627. """
  628. def __init__(self, fields=(), *args, **kwargs):
  629. super(ComboField, self).__init__(*args, **kwargs)
  630. # Set 'required' to False on the individual fields, because the
  631. # required validation will be handled by ComboField, not by those
  632. # individual fields.
  633. for f in fields:
  634. f.required = False
  635. self.fields = fields
  636. def clean(self, value):
  637. """
  638. Validates the given value against all of self.fields, which is a
  639. list of Field instances.
  640. """
  641. super(ComboField, self).clean(value)
  642. for field in self.fields:
  643. value = field.clean(value)
  644. return value
  645. class MultiValueField(Field):
  646. """
  647. A Field that aggregates the logic of multiple Fields.
  648. Its clean() method takes a "decompressed" list of values, which are then
  649. cleaned into a single value according to self.fields. Each value in
  650. this list is cleaned by the corresponding field -- the first value is
  651. cleaned by the first field, the second value is cleaned by the second
  652. field, etc. Once all fields are cleaned, the list of clean values is
  653. "compressed" into a single value.
  654. Subclasses should not have to implement clean(). Instead, they must
  655. implement compress(), which takes a list of valid values and returns a
  656. "compressed" version of those values -- a single value.
  657. You'll probably want to use this with MultiWidget.
  658. """
  659. default_error_messages = {
  660. 'invalid': _(u'Enter a list of values.'),
  661. }
  662. def __init__(self, fields=(), *args, **kwargs):
  663. super(MultiValueField, self).__init__(*args, **kwargs)
  664. # Set 'required' to False on the individual fields, because the
  665. # required validation will be handled by MultiValueField, not by those
  666. # individual fields.
  667. for f in fields:
  668. f.required = False
  669. self.fields = fields
  670. def validate(self, value):
  671. pass
  672. def clean(self, value):
  673. """
  674. Validates every value in the given list. A value is validated against
  675. the corresponding Field in self.fields.
  676. For example, if this MultiValueField was instantiated with
  677. fields=(DateField(), TimeField()), clean() would call
  678. DateField.clean(value[0]) and TimeField.clean(value[1]).
  679. """
  680. clean_data = []
  681. errors = ErrorList()
  682. if not value or isinstance(value, (list, tuple)):
  683. if not value or not [v for v in value if v not in validators.EMPTY_VALUES]:
  684. if self.required:
  685. raise ValidationError(self.error_messages['required'])
  686. else:
  687. return self.compress([])
  688. else:
  689. raise ValidationError(self.error_messages['invalid'])
  690. for i, field in enumerate(self.fields):
  691. try:
  692. field_value = value[i]
  693. except IndexError:
  694. field_value = None
  695. if self.required and field_value in validators.EMPTY_VALUES:
  696. raise ValidationError(self.error_messages['required'])
  697. try:
  698. clean_data.append(field.clean(field_value))
  699. except ValidationError, e:
  700. # Collect all validation errors in a single list, which we'll
  701. # raise at the end of clean(), rather than raising a single
  702. # exception for the first error we encounter.
  703. errors.extend(e.messages)
  704. if errors:
  705. raise ValidationError(errors)
  706. out = self.compress(clean_data)
  707. self.validate(out)
  708. return out
  709. def compress(self, data_list):
  710. """
  711. Returns a single value for the given list of values. The values can be
  712. assumed to be valid.
  713. For example, if this MultiValueField was instantiated with
  714. fields=(DateField(), TimeField()), this might return a datetime
  715. object created by combining the date and time in data_list.
  716. """
  717. raise NotImplementedError('Subclasses must implement this method.')
  718. class FilePathField(ChoiceField):
  719. def __init__(self, path, match=None, recursive=False, required=True,
  720. widget=None, label=None, initial=None, help_text=None,
  721. *args, **kwargs):
  722. self.path, self.match, self.recursive = path, match, recursive
  723. super(FilePathField, self).__init__(choices=(), required=required,
  724. widget=widget, label=label, initial=initial, help_text=help_text,
  725. *args, **kwargs)
  726. if self.required:
  727. self.choices = []
  728. else:
  729. self.choices = [("", "---------")]
  730. if self.match is not None:
  731. self.match_re = re.compile(self.match)
  732. if recursive:
  733. for root, dirs, files in sorted(os.walk(self.path)):
  734. for f in files:
  735. if self.match is None or self.match_re.search(f):
  736. f = os.path.join(root, f)
  737. self.choices.append((f, f.replace(path, "", 1)))
  738. else:
  739. try:
  740. for f in sorted(os.listdir(self.path)):
  741. full_file = os.path.join(self.path, f)
  742. if os.path.isfile(full_file) and (self.match is None or self.match_re.search(f)):
  743. self.choices.append((full_file, f))
  744. except OSError:
  745. pass
  746. self.widget.choices = self.choices
  747. class SplitDateTimeField(MultiValueField):
  748. widget = SplitDateTimeWidget
  749. hidden_widget = SplitHiddenDateTimeWidget
  750. default_error_messages = {
  751. 'invalid_date': _(u'Enter a valid date.'),
  752. 'invalid_time': _(u'Enter a valid time.'),
  753. }
  754. def __init__(self, input_date_formats=None, input_time_formats=None, *args, **kwargs):
  755. errors = self.default_error_messages.copy()
  756. if 'error_messages' in kwargs:
  757. errors.update(kwargs['error_messages'])
  758. localize = kwargs.get('localize', False)
  759. fields = (
  760. DateField(input_formats=input_date_formats,
  761. error_messages={'invalid': errors['invalid_date']},
  762. localize=localize),
  763. TimeField(input_formats=input_time_formats,
  764. error_messages={'invalid': errors['invalid_time']},
  765. localize=localize),
  766. )
  767. super(SplitDateTimeField, self).__init__(fields, *args, **kwargs)
  768. def compress(self, data_list):
  769. if data_list:
  770. # Raise a validation error if time or date is empty
  771. # (possible if SplitDateTimeField has required=False).
  772. if data_list[0] in validators.EMPTY_VALUES:
  773. raise ValidationError(self.error_messages['invalid_date'])
  774. if data_list[1] in validators.EMPTY_VALUES:
  775. raise ValidationError(self.error_messages['invalid_time'])
  776. return datetime.datetime.combine(*data_list)
  777. return None
  778. class IPAddressField(CharField):
  779. default_error_messages = {
  780. 'invalid': _(u'Enter a valid IPv4 address.'),
  781. }
  782. default_validators = [validators.validate_ipv4_address]
  783. class SlugField(CharField):
  784. default_error_messages = {
  785. 'invalid': _(u"Enter a valid 'slug' consisting of letters, numbers,"
  786. u" underscores or hyphens."),
  787. }
  788. default_validators = [validators.validate_slug]