PageRenderTime 232ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/django/forms/fields.py

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