PageRenderTime 34ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/django/branches/attic/multiple-db-support/django/newforms/fields.py

https://bitbucket.org/mirror/django/
Python | 322 lines | 302 code | 12 blank | 8 comment | 7 complexity | fb028ff7610a84f79f49948c5933c6bf MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. Field classes
  3. """
  4. from django.utils.translation import gettext
  5. from util import ValidationError, smart_unicode
  6. from widgets import TextInput, PasswordInput, CheckboxInput, Select, SelectMultiple
  7. import datetime
  8. import re
  9. import time
  10. __all__ = (
  11. 'Field', 'CharField', 'IntegerField',
  12. 'DEFAULT_DATE_INPUT_FORMATS', 'DateField',
  13. 'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField',
  14. 'RegexField', 'EmailField', 'URLField', 'BooleanField',
  15. 'ChoiceField', 'MultipleChoiceField',
  16. 'ComboField',
  17. )
  18. # These values, if given to to_python(), will trigger the self.required check.
  19. EMPTY_VALUES = (None, '')
  20. try:
  21. set # Only available in Python 2.4+
  22. except NameError:
  23. from sets import Set as set # Python 2.3 fallback
  24. class Field(object):
  25. widget = TextInput # Default widget to use when rendering this type of Field.
  26. # Tracks each time a Field instance is created. Used to retain order.
  27. creation_counter = 0
  28. def __init__(self, required=True, widget=None, label=None):
  29. self.required, self.label = required, label
  30. widget = widget or self.widget
  31. if isinstance(widget, type):
  32. widget = widget()
  33. # Hook into self.widget_attrs() for any Field-specific HTML attributes.
  34. extra_attrs = self.widget_attrs(widget)
  35. if extra_attrs:
  36. widget.attrs.update(extra_attrs)
  37. self.widget = widget
  38. # Increase the creation counter, and save our local copy.
  39. self.creation_counter = Field.creation_counter
  40. Field.creation_counter += 1
  41. def clean(self, value):
  42. """
  43. Validates the given value and returns its "cleaned" value as an
  44. appropriate Python object.
  45. Raises ValidationError for any errors.
  46. """
  47. if self.required and value in EMPTY_VALUES:
  48. raise ValidationError(gettext(u'This field is required.'))
  49. return value
  50. def widget_attrs(self, widget):
  51. """
  52. Given a Widget instance (*not* a Widget class), returns a dictionary of
  53. any HTML attributes that should be added to the Widget, based on this
  54. Field.
  55. """
  56. return {}
  57. class CharField(Field):
  58. def __init__(self, max_length=None, min_length=None, required=True, widget=None, label=None):
  59. self.max_length, self.min_length = max_length, min_length
  60. Field.__init__(self, required, widget, label)
  61. def clean(self, value):
  62. "Validates max_length and min_length. Returns a Unicode object."
  63. Field.clean(self, value)
  64. if value in EMPTY_VALUES: value = u''
  65. value = smart_unicode(value)
  66. if self.max_length is not None and len(value) > self.max_length:
  67. raise ValidationError(gettext(u'Ensure this value has at most %d characters.') % self.max_length)
  68. if self.min_length is not None and len(value) < self.min_length:
  69. raise ValidationError(gettext(u'Ensure this value has at least %d characters.') % self.min_length)
  70. return value
  71. def widget_attrs(self, widget):
  72. if self.max_length is not None and isinstance(widget, (TextInput, PasswordInput)):
  73. return {'maxlength': str(self.max_length)}
  74. class IntegerField(Field):
  75. def clean(self, value):
  76. """
  77. Validates that int() can be called on the input. Returns the result
  78. of int().
  79. """
  80. super(IntegerField, self).clean(value)
  81. if not self.required and value in EMPTY_VALUES:
  82. return u''
  83. try:
  84. return int(value)
  85. except (ValueError, TypeError):
  86. raise ValidationError(gettext(u'Enter a whole number.'))
  87. DEFAULT_DATE_INPUT_FORMATS = (
  88. '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
  89. '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
  90. '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006'
  91. '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006'
  92. '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006'
  93. )
  94. class DateField(Field):
  95. def __init__(self, input_formats=None, required=True, widget=None, label=None):
  96. Field.__init__(self, required, widget, label)
  97. self.input_formats = input_formats or DEFAULT_DATE_INPUT_FORMATS
  98. def clean(self, value):
  99. """
  100. Validates that the input can be converted to a date. Returns a Python
  101. datetime.date object.
  102. """
  103. Field.clean(self, value)
  104. if value in EMPTY_VALUES:
  105. return None
  106. if isinstance(value, datetime.datetime):
  107. return value.date()
  108. if isinstance(value, datetime.date):
  109. return value
  110. for format in self.input_formats:
  111. try:
  112. return datetime.date(*time.strptime(value, format)[:3])
  113. except ValueError:
  114. continue
  115. raise ValidationError(gettext(u'Enter a valid date.'))
  116. DEFAULT_DATETIME_INPUT_FORMATS = (
  117. '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59'
  118. '%Y-%m-%d %H:%M', # '2006-10-25 14:30'
  119. '%Y-%m-%d', # '2006-10-25'
  120. '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59'
  121. '%m/%d/%Y %H:%M', # '10/25/2006 14:30'
  122. '%m/%d/%Y', # '10/25/2006'
  123. '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59'
  124. '%m/%d/%y %H:%M', # '10/25/06 14:30'
  125. '%m/%d/%y', # '10/25/06'
  126. )
  127. class DateTimeField(Field):
  128. def __init__(self, input_formats=None, required=True, widget=None, label=None):
  129. Field.__init__(self, required, widget, label)
  130. self.input_formats = input_formats or DEFAULT_DATETIME_INPUT_FORMATS
  131. def clean(self, value):
  132. """
  133. Validates that the input can be converted to a datetime. Returns a
  134. Python datetime.datetime object.
  135. """
  136. Field.clean(self, value)
  137. if value in EMPTY_VALUES:
  138. return None
  139. if isinstance(value, datetime.datetime):
  140. return value
  141. if isinstance(value, datetime.date):
  142. return datetime.datetime(value.year, value.month, value.day)
  143. for format in self.input_formats:
  144. try:
  145. return datetime.datetime(*time.strptime(value, format)[:6])
  146. except ValueError:
  147. continue
  148. raise ValidationError(gettext(u'Enter a valid date/time.'))
  149. class RegexField(Field):
  150. def __init__(self, regex, error_message=None, required=True, widget=None, label=None):
  151. """
  152. regex can be either a string or a compiled regular expression object.
  153. error_message is an optional error message to use, if
  154. 'Enter a valid value' is too generic for you.
  155. """
  156. Field.__init__(self, required, widget, label)
  157. if isinstance(regex, basestring):
  158. regex = re.compile(regex)
  159. self.regex = regex
  160. self.error_message = error_message or gettext(u'Enter a valid value.')
  161. def clean(self, value):
  162. """
  163. Validates that the input matches the regular expression. Returns a
  164. Unicode object.
  165. """
  166. Field.clean(self, value)
  167. if value in EMPTY_VALUES: value = u''
  168. value = smart_unicode(value)
  169. if not self.required and value == u'':
  170. return value
  171. if not self.regex.search(value):
  172. raise ValidationError(self.error_message)
  173. return value
  174. email_re = re.compile(
  175. r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom
  176. r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string
  177. r')@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}$', re.IGNORECASE) # domain
  178. class EmailField(RegexField):
  179. def __init__(self, required=True, widget=None, label=None):
  180. RegexField.__init__(self, email_re, gettext(u'Enter a valid e-mail address.'), required, widget, label)
  181. url_re = re.compile(
  182. r'^https?://' # http:// or https://
  183. r'(?:[A-Z0-9-]+\.)+[A-Z]{2,6}' # domain
  184. r'(?::\d+)?' # optional port
  185. r'(?:/?|/\S+)$', re.IGNORECASE)
  186. try:
  187. from django.conf import settings
  188. URL_VALIDATOR_USER_AGENT = settings.URL_VALIDATOR_USER_AGENT
  189. except ImportError:
  190. # It's OK if Django settings aren't configured.
  191. URL_VALIDATOR_USER_AGENT = 'Django (http://www.djangoproject.com/)'
  192. class URLField(RegexField):
  193. def __init__(self, required=True, verify_exists=False, widget=None, label=None,
  194. validator_user_agent=URL_VALIDATOR_USER_AGENT):
  195. RegexField.__init__(self, url_re, gettext(u'Enter a valid URL.'), required, widget, label)
  196. self.verify_exists = verify_exists
  197. self.user_agent = validator_user_agent
  198. def clean(self, value):
  199. value = RegexField.clean(self, value)
  200. if self.verify_exists:
  201. import urllib2
  202. from django.conf import settings
  203. headers = {
  204. "Accept": "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
  205. "Accept-Language": "en-us,en;q=0.5",
  206. "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
  207. "Connection": "close",
  208. "User-Agent": self.user_agent,
  209. }
  210. try:
  211. req = urllib2.Request(value, None, headers)
  212. u = urllib2.urlopen(req)
  213. except ValueError:
  214. raise ValidationError(gettext(u'Enter a valid URL.'))
  215. except: # urllib2.URLError, httplib.InvalidURL, etc.
  216. raise ValidationError(gettext(u'This URL appears to be a broken link.'))
  217. return value
  218. class BooleanField(Field):
  219. widget = CheckboxInput
  220. def clean(self, value):
  221. "Returns a Python boolean object."
  222. Field.clean(self, value)
  223. return bool(value)
  224. class ChoiceField(Field):
  225. def __init__(self, choices=(), required=True, widget=Select, label=None):
  226. if isinstance(widget, type):
  227. widget = widget(choices=choices)
  228. Field.__init__(self, required, widget, label)
  229. self.choices = choices
  230. def clean(self, value):
  231. """
  232. Validates that the input is in self.choices.
  233. """
  234. value = Field.clean(self, value)
  235. if value in EMPTY_VALUES: value = u''
  236. value = smart_unicode(value)
  237. if not self.required and value == u'':
  238. return value
  239. valid_values = set([str(k) for k, v in self.choices])
  240. if value not in valid_values:
  241. raise ValidationError(gettext(u'Select a valid choice. %s is not one of the available choices.') % value)
  242. return value
  243. class MultipleChoiceField(ChoiceField):
  244. def __init__(self, choices=(), required=True, widget=SelectMultiple, label=None):
  245. ChoiceField.__init__(self, choices, required, widget, label)
  246. def clean(self, value):
  247. """
  248. Validates that the input is a list or tuple.
  249. """
  250. if self.required and not value:
  251. raise ValidationError(gettext(u'This field is required.'))
  252. elif not self.required and not value:
  253. return []
  254. if not isinstance(value, (list, tuple)):
  255. raise ValidationError(gettext(u'Enter a list of values.'))
  256. new_value = []
  257. for val in value:
  258. val = smart_unicode(val)
  259. new_value.append(val)
  260. # Validate that each value in the value list is in self.choices.
  261. valid_values = set([smart_unicode(k) for k, v in self.choices])
  262. for val in new_value:
  263. if val not in valid_values:
  264. raise ValidationError(gettext(u'Select a valid choice. %s is not one of the available choices.') % val)
  265. return new_value
  266. class ComboField(Field):
  267. def __init__(self, fields=(), required=True, widget=None, label=None):
  268. Field.__init__(self, required, widget, label)
  269. # Set 'required' to False on the individual fields, because the
  270. # required validation will be handled by ComboField, not by those
  271. # individual fields.
  272. for f in fields:
  273. f.required = False
  274. self.fields = fields
  275. def clean(self, value):
  276. """
  277. Validates the given value against all of self.fields, which is a
  278. list of Field instances.
  279. """
  280. Field.clean(self, value)
  281. for field in self.fields:
  282. value = field.clean(value)
  283. return value