PageRenderTime 30ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/django/forms/fields.py

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