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