PageRenderTime 114ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/django/forms/fields.py

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