PageRenderTime 35ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/django-0.96/django/newforms/fields.py

https://github.com/theosp/google_appengine
Python | 494 lines | 463 code | 11 blank | 20 comment | 11 complexity | c0e69c9b528cc352be811ea4cce5c2b5 MD5 | raw file
  1. """
  2. Field classes
  3. """
  4. from django.utils.translation import gettext
  5. from util import ErrorList, ValidationError, smart_unicode
  6. from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, CheckboxInput, Select, NullBooleanSelect, SelectMultiple
  7. import datetime
  8. import re
  9. import time
  10. __all__ = (
  11. 'Field', 'CharField', 'IntegerField',
  12. 'DEFAULT_DATE_INPUT_FORMATS', 'DateField',
  13. 'DEFAULT_TIME_INPUT_FORMATS', 'TimeField',
  14. 'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField',
  15. 'RegexField', 'EmailField', 'URLField', 'BooleanField',
  16. 'ChoiceField', 'NullBooleanField', 'MultipleChoiceField',
  17. 'ComboField', 'MultiValueField',
  18. 'SplitDateTimeField',
  19. )
  20. # These values, if given to to_python(), will trigger the self.required check.
  21. EMPTY_VALUES = (None, '')
  22. try:
  23. set # Only available in Python 2.4+
  24. except NameError:
  25. from sets import Set as set # Python 2.3 fallback
  26. class Field(object):
  27. widget = TextInput # Default widget to use when rendering this type of Field.
  28. hidden_widget = HiddenInput # Default widget to use when rendering this as "hidden".
  29. # Tracks each time a Field instance is created. Used to retain order.
  30. creation_counter = 0
  31. def __init__(self, required=True, widget=None, label=None, initial=None, help_text=None):
  32. # required -- Boolean that specifies whether the field is required.
  33. # True by default.
  34. # widget -- A Widget class, or instance of a Widget class, that should be
  35. # used for this Field when displaying it. Each Field has a default
  36. # Widget that it'll use if you don't specify this. In most cases,
  37. # the default widget is TextInput.
  38. # label -- A verbose name for this field, for use in displaying this field in
  39. # a form. By default, Django will use a "pretty" version of the form
  40. # field name, if the Field is part of a Form.
  41. # initial -- A value to use in this Field's initial display. This value is
  42. # *not* used as a fallback if data isn't given.
  43. # help_text -- An optional string to use as "help text" for this Field.
  44. if label is not None:
  45. label = smart_unicode(label)
  46. self.required, self.label, self.initial = required, label, initial
  47. self.help_text = smart_unicode(help_text or '')
  48. widget = widget or self.widget
  49. if isinstance(widget, type):
  50. widget = widget()
  51. # Hook into self.widget_attrs() for any Field-specific HTML attributes.
  52. extra_attrs = self.widget_attrs(widget)
  53. if extra_attrs:
  54. widget.attrs.update(extra_attrs)
  55. self.widget = widget
  56. # Increase the creation counter, and save our local copy.
  57. self.creation_counter = Field.creation_counter
  58. Field.creation_counter += 1
  59. def clean(self, value):
  60. """
  61. Validates the given value and returns its "cleaned" value as an
  62. appropriate Python object.
  63. Raises ValidationError for any errors.
  64. """
  65. if self.required and value in EMPTY_VALUES:
  66. raise ValidationError(gettext(u'This field is required.'))
  67. return value
  68. def widget_attrs(self, widget):
  69. """
  70. Given a Widget instance (*not* a Widget class), returns a dictionary of
  71. any HTML attributes that should be added to the Widget, based on this
  72. Field.
  73. """
  74. return {}
  75. class CharField(Field):
  76. def __init__(self, max_length=None, min_length=None, *args, **kwargs):
  77. self.max_length, self.min_length = max_length, min_length
  78. super(CharField, self).__init__(*args, **kwargs)
  79. def clean(self, value):
  80. "Validates max_length and min_length. Returns a Unicode object."
  81. super(CharField, self).clean(value)
  82. if value in EMPTY_VALUES:
  83. return u''
  84. value = smart_unicode(value)
  85. if self.max_length is not None and len(value) > self.max_length:
  86. raise ValidationError(gettext(u'Ensure this value has at most %d characters.') % self.max_length)
  87. if self.min_length is not None and len(value) < self.min_length:
  88. raise ValidationError(gettext(u'Ensure this value has at least %d characters.') % self.min_length)
  89. return value
  90. def widget_attrs(self, widget):
  91. if self.max_length is not None and isinstance(widget, (TextInput, PasswordInput)):
  92. return {'maxlength': str(self.max_length)}
  93. class IntegerField(Field):
  94. def __init__(self, max_value=None, min_value=None, *args, **kwargs):
  95. self.max_value, self.min_value = max_value, min_value
  96. super(IntegerField, self).__init__(*args, **kwargs)
  97. def clean(self, value):
  98. """
  99. Validates that int() can be called on the input. Returns the result
  100. of int(). Returns None for empty values.
  101. """
  102. super(IntegerField, self).clean(value)
  103. if value in EMPTY_VALUES:
  104. return None
  105. try:
  106. value = int(value)
  107. except (ValueError, TypeError):
  108. raise ValidationError(gettext(u'Enter a whole number.'))
  109. if self.max_value is not None and value > self.max_value:
  110. raise ValidationError(gettext(u'Ensure this value is less than or equal to %s.') % self.max_value)
  111. if self.min_value is not None and value < self.min_value:
  112. raise ValidationError(gettext(u'Ensure this value is greater than or equal to %s.') % self.min_value)
  113. return value
  114. DEFAULT_DATE_INPUT_FORMATS = (
  115. '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
  116. '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
  117. '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
  118. '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
  119. '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
  120. )
  121. class DateField(Field):
  122. def __init__(self, input_formats=None, *args, **kwargs):
  123. super(DateField, self).__init__(*args, **kwargs)
  124. self.input_formats = input_formats or DEFAULT_DATE_INPUT_FORMATS
  125. def clean(self, value):
  126. """
  127. Validates that the input can be converted to a date. Returns a Python
  128. datetime.date object.
  129. """
  130. super(DateField, self).clean(value)
  131. if value in EMPTY_VALUES:
  132. return None
  133. if isinstance(value, datetime.datetime):
  134. return value.date()
  135. if isinstance(value, datetime.date):
  136. return value
  137. for format in self.input_formats:
  138. try:
  139. return datetime.date(*time.strptime(value, format)[:3])
  140. except ValueError:
  141. continue
  142. raise ValidationError(gettext(u'Enter a valid date.'))
  143. DEFAULT_TIME_INPUT_FORMATS = (
  144. '%H:%M:%S', # '14:30:59'
  145. '%H:%M', # '14:30'
  146. )
  147. class TimeField(Field):
  148. def __init__(self, input_formats=None, *args, **kwargs):
  149. super(TimeField, self).__init__(*args, **kwargs)
  150. self.input_formats = input_formats or DEFAULT_TIME_INPUT_FORMATS
  151. def clean(self, value):
  152. """
  153. Validates that the input can be converted to a time. Returns a Python
  154. datetime.time object.
  155. """
  156. super(TimeField, self).clean(value)
  157. if value in EMPTY_VALUES:
  158. return None
  159. if isinstance(value, datetime.time):
  160. return value
  161. for format in self.input_formats:
  162. try:
  163. return datetime.time(*time.strptime(value, format)[3:6])
  164. except ValueError:
  165. continue
  166. raise ValidationError(gettext(u'Enter a valid time.'))
  167. DEFAULT_DATETIME_INPUT_FORMATS = (
  168. '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
  169. '%Y-%m-%d %H:%M', # '2006-10-25 14:30'
  170. '%Y-%m-%d', # '2006-10-25'
  171. '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
  172. '%m/%d/%Y %H:%M', # '10/25/2006 14:30'
  173. '%m/%d/%Y', # '10/25/2006'
  174. '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
  175. '%m/%d/%y %H:%M', # '10/25/06 14:30'
  176. '%m/%d/%y', # '10/25/06'
  177. )
  178. class DateTimeField(Field):
  179. def __init__(self, input_formats=None, *args, **kwargs):
  180. super(DateTimeField, self).__init__(*args, **kwargs)
  181. self.input_formats = input_formats or DEFAULT_DATETIME_INPUT_FORMATS
  182. def clean(self, value):
  183. """
  184. Validates that the input can be converted to a datetime. Returns a
  185. Python datetime.datetime object.
  186. """
  187. super(DateTimeField, self).clean(value)
  188. if value in EMPTY_VALUES:
  189. return None
  190. if isinstance(value, datetime.datetime):
  191. return value
  192. if isinstance(value, datetime.date):
  193. return datetime.datetime(value.year, value.month, value.day)
  194. for format in self.input_formats:
  195. try:
  196. return datetime.datetime(*time.strptime(value, format)[:6])
  197. except ValueError:
  198. continue
  199. raise ValidationError(gettext(u'Enter a valid date/time.'))
  200. class RegexField(Field):
  201. def __init__(self, regex, max_length=None, min_length=None, error_message=None, *args, **kwargs):
  202. """
  203. regex can be either a string or a compiled regular expression object.
  204. error_message is an optional error message to use, if
  205. 'Enter a valid value' is too generic for you.
  206. """
  207. super(RegexField, self).__init__(*args, **kwargs)
  208. if isinstance(regex, basestring):
  209. regex = re.compile(regex)
  210. self.regex = regex
  211. self.max_length, self.min_length = max_length, min_length
  212. self.error_message = error_message or gettext(u'Enter a valid value.')
  213. def clean(self, value):
  214. """
  215. Validates that the input matches the regular expression. Returns a
  216. Unicode object.
  217. """
  218. super(RegexField, self).clean(value)
  219. if value in EMPTY_VALUES:
  220. value = u''
  221. value = smart_unicode(value)
  222. if value == u'':
  223. return value
  224. if self.max_length is not None and len(value) > self.max_length:
  225. raise ValidationError(gettext(u'Ensure this value has at most %d characters.') % self.max_length)
  226. if self.min_length is not None and len(value) < self.min_length:
  227. raise ValidationError(gettext(u'Ensure this value has at least %d characters.') % self.min_length)
  228. if not self.regex.search(value):
  229. raise ValidationError(self.error_message)
  230. return value
  231. email_re = re.compile(
  232. r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom
  233. r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string
  234. r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE) # domain
  235. class EmailField(RegexField):
  236. def __init__(self, max_length=None, min_length=None, *args, **kwargs):
  237. RegexField.__init__(self, email_re, max_length, min_length,
  238. gettext(u'Enter a valid e-mail address.'), *args, **kwargs)
  239. url_re = re.compile(
  240. r'^https?://' # http:// or https://
  241. r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|' #domain...
  242. r'localhost|' #localhost...
  243. r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
  244. r'(?::\d+)?' # optional port
  245. r'(?:/?|/\S+)$', re.IGNORECASE)
  246. try:
  247. from django.conf import settings
  248. URL_VALIDATOR_USER_AGENT = settings.URL_VALIDATOR_USER_AGENT
  249. except ImportError:
  250. # It's OK if Django settings aren't configured.
  251. URL_VALIDATOR_USER_AGENT = 'Django (http://www.djangoproject.com/)'
  252. class URLField(RegexField):
  253. def __init__(self, max_length=None, min_length=None, verify_exists=False,
  254. validator_user_agent=URL_VALIDATOR_USER_AGENT, *args, **kwargs):
  255. super(URLField, self).__init__(url_re, max_length, min_length, gettext(u'Enter a valid URL.'), *args, **kwargs)
  256. self.verify_exists = verify_exists
  257. self.user_agent = validator_user_agent
  258. def clean(self, value):
  259. value = super(URLField, self).clean(value)
  260. if value == u'':
  261. return value
  262. if self.verify_exists:
  263. import urllib2
  264. from django.conf import settings
  265. headers = {
  266. "Accept": "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
  267. "Accept-Language": "en-us,en;q=0.5",
  268. "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
  269. "Connection": "close",
  270. "User-Agent": self.user_agent,
  271. }
  272. try:
  273. req = urllib2.Request(value, None, headers)
  274. u = urllib2.urlopen(req)
  275. except ValueError:
  276. raise ValidationError(gettext(u'Enter a valid URL.'))
  277. except: # urllib2.URLError, httplib.InvalidURL, etc.
  278. raise ValidationError(gettext(u'This URL appears to be a broken link.'))
  279. return value
  280. class BooleanField(Field):
  281. widget = CheckboxInput
  282. def clean(self, value):
  283. "Returns a Python boolean object."
  284. super(BooleanField, self).clean(value)
  285. return bool(value)
  286. class NullBooleanField(BooleanField):
  287. """
  288. A field whose valid values are None, True and False. Invalid values are
  289. cleaned to None.
  290. """
  291. widget = NullBooleanSelect
  292. def clean(self, value):
  293. return {True: True, False: False}.get(value, None)
  294. class ChoiceField(Field):
  295. def __init__(self, choices=(), required=True, widget=Select, label=None, initial=None, help_text=None):
  296. super(ChoiceField, self).__init__(required, widget, label, initial, help_text)
  297. self.choices = choices
  298. def _get_choices(self):
  299. return self._choices
  300. def _set_choices(self, value):
  301. # Setting choices also sets the choices on the widget.
  302. # choices can be any iterable, but we call list() on it because
  303. # it will be consumed more than once.
  304. self._choices = self.widget.choices = list(value)
  305. choices = property(_get_choices, _set_choices)
  306. def clean(self, value):
  307. """
  308. Validates that the input is in self.choices.
  309. """
  310. value = super(ChoiceField, self).clean(value)
  311. if value in EMPTY_VALUES:
  312. value = u''
  313. value = smart_unicode(value)
  314. if value == u'':
  315. return value
  316. valid_values = set([str(k) for k, v in self.choices])
  317. if value not in valid_values:
  318. raise ValidationError(gettext(u'Select a valid choice. That choice is not one of the available choices.'))
  319. return value
  320. class MultipleChoiceField(ChoiceField):
  321. hidden_widget = MultipleHiddenInput
  322. def __init__(self, choices=(), required=True, widget=SelectMultiple, label=None, initial=None, help_text=None):
  323. super(MultipleChoiceField, self).__init__(choices, required, widget, label, initial, help_text)
  324. def clean(self, value):
  325. """
  326. Validates that the input is a list or tuple.
  327. """
  328. if self.required and not value:
  329. raise ValidationError(gettext(u'This field is required.'))
  330. elif not self.required and not value:
  331. return []
  332. if not isinstance(value, (list, tuple)):
  333. raise ValidationError(gettext(u'Enter a list of values.'))
  334. new_value = []
  335. for val in value:
  336. val = smart_unicode(val)
  337. new_value.append(val)
  338. # Validate that each value in the value list is in self.choices.
  339. valid_values = set([smart_unicode(k) for k, v in self.choices])
  340. for val in new_value:
  341. if val not in valid_values:
  342. raise ValidationError(gettext(u'Select a valid choice. %s is not one of the available choices.') % val)
  343. return new_value
  344. class ComboField(Field):
  345. """
  346. A Field whose clean() method calls multiple Field clean() methods.
  347. """
  348. def __init__(self, fields=(), *args, **kwargs):
  349. super(ComboField, self).__init__(*args, **kwargs)
  350. # Set 'required' to False on the individual fields, because the
  351. # required validation will be handled by ComboField, not by those
  352. # individual fields.
  353. for f in fields:
  354. f.required = False
  355. self.fields = fields
  356. def clean(self, value):
  357. """
  358. Validates the given value against all of self.fields, which is a
  359. list of Field instances.
  360. """
  361. super(ComboField, self).clean(value)
  362. for field in self.fields:
  363. value = field.clean(value)
  364. return value
  365. class MultiValueField(Field):
  366. """
  367. A Field that is composed of multiple Fields.
  368. Its clean() method takes a "decompressed" list of values. Each value in
  369. this list is cleaned by the corresponding field -- the first value is
  370. cleaned by the first field, the second value is cleaned by the second
  371. field, etc. Once all fields are cleaned, the list of clean values is
  372. "compressed" into a single value.
  373. Subclasses should implement compress(), which specifies how a list of
  374. valid values should be converted to a single value. Subclasses should not
  375. have to implement clean().
  376. You'll probably want to use this with MultiWidget.
  377. """
  378. def __init__(self, fields=(), *args, **kwargs):
  379. super(MultiValueField, self).__init__(*args, **kwargs)
  380. # Set 'required' to False on the individual fields, because the
  381. # required validation will be handled by MultiValueField, not by those
  382. # individual fields.
  383. for f in fields:
  384. f.required = False
  385. self.fields = fields
  386. def clean(self, value):
  387. """
  388. Validates every value in the given list. A value is validated against
  389. the corresponding Field in self.fields.
  390. For example, if this MultiValueField was instantiated with
  391. fields=(DateField(), TimeField()), clean() would call
  392. DateField.clean(value[0]) and TimeField.clean(value[1]).
  393. """
  394. clean_data = []
  395. errors = ErrorList()
  396. if self.required and not value:
  397. raise ValidationError(gettext(u'This field is required.'))
  398. elif not self.required and not value:
  399. return self.compress([])
  400. if not isinstance(value, (list, tuple)):
  401. raise ValidationError(gettext(u'Enter a list of values.'))
  402. for i, field in enumerate(self.fields):
  403. try:
  404. field_value = value[i]
  405. except KeyError:
  406. field_value = None
  407. if self.required and field_value in EMPTY_VALUES:
  408. raise ValidationError(gettext(u'This field is required.'))
  409. try:
  410. clean_data.append(field.clean(field_value))
  411. except ValidationError, e:
  412. # Collect all validation errors in a single list, which we'll
  413. # raise at the end of clean(), rather than raising a single
  414. # exception for the first error we encounter.
  415. errors.extend(e.messages)
  416. if errors:
  417. raise ValidationError(errors)
  418. return self.compress(clean_data)
  419. def compress(self, data_list):
  420. """
  421. Returns a single value for the given list of values. The values can be
  422. assumed to be valid.
  423. For example, if this MultiValueField was instantiated with
  424. fields=(DateField(), TimeField()), this might return a datetime
  425. object created by combining the date and time in data_list.
  426. """
  427. raise NotImplementedError('Subclasses must implement this method.')
  428. class SplitDateTimeField(MultiValueField):
  429. def __init__(self, *args, **kwargs):
  430. fields = (DateField(), TimeField())
  431. super(SplitDateTimeField, self).__init__(fields, *args, **kwargs)
  432. def compress(self, data_list):
  433. if data_list:
  434. return datetime.datetime.combine(*data_list)
  435. return None