|
1 import copy |
|
2 import datetime |
|
3 import os |
|
4 import re |
|
5 import time |
|
6 try: |
|
7 import decimal |
|
8 except ImportError: |
|
9 from django.utils import _decimal as decimal # for Python 2.3 |
|
10 |
|
11 from django.db import connection |
|
12 from django.db.models import signals |
|
13 from django.db.models.query_utils import QueryWrapper |
|
14 from django.dispatch import dispatcher |
|
15 from django.conf import settings |
|
16 from django import forms |
|
17 from django.core import exceptions |
|
18 from django.utils.datastructures import DictWrapper |
|
19 from django.utils.functional import curry |
|
20 from django.utils.itercompat import tee |
|
21 from django.utils.text import capfirst |
|
22 from django.utils.translation import ugettext_lazy, ugettext as _ |
|
23 from django.utils.encoding import smart_unicode, force_unicode, smart_str |
|
24 from django.utils import datetime_safe |
|
25 |
|
26 class NOT_PROVIDED: |
|
27 pass |
|
28 |
|
29 # The values to use for "blank" in SelectFields. Will be appended to the start of most "choices" lists. |
|
30 BLANK_CHOICE_DASH = [("", "---------")] |
|
31 BLANK_CHOICE_NONE = [("", "None")] |
|
32 |
|
33 class FieldDoesNotExist(Exception): |
|
34 pass |
|
35 |
|
36 # A guide to Field parameters: |
|
37 # |
|
38 # * name: The name of the field specifed in the model. |
|
39 # * attname: The attribute to use on the model object. This is the same as |
|
40 # "name", except in the case of ForeignKeys, where "_id" is |
|
41 # appended. |
|
42 # * db_column: The db_column specified in the model (or None). |
|
43 # * column: The database column for this field. This is the same as |
|
44 # "attname", except if db_column is specified. |
|
45 # |
|
46 # Code that introspects values, or does other dynamic things, should use |
|
47 # attname. For example, this gets the primary key value of object "obj": |
|
48 # |
|
49 # getattr(obj, opts.pk.attname) |
|
50 |
|
51 class Field(object): |
|
52 # Designates whether empty strings fundamentally are allowed at the |
|
53 # database level. |
|
54 empty_strings_allowed = True |
|
55 |
|
56 # These track each time a Field instance is created. Used to retain order. |
|
57 # The auto_creation_counter is used for fields that Django implicitly |
|
58 # creates, creation_counter is used for all user-specified fields. |
|
59 creation_counter = 0 |
|
60 auto_creation_counter = -1 |
|
61 |
|
62 def __init__(self, verbose_name=None, name=None, primary_key=False, |
|
63 max_length=None, unique=False, blank=False, null=False, |
|
64 db_index=False, rel=None, default=NOT_PROVIDED, editable=True, |
|
65 serialize=True, unique_for_date=None, unique_for_month=None, |
|
66 unique_for_year=None, choices=None, help_text='', db_column=None, |
|
67 db_tablespace=None, auto_created=False): |
|
68 self.name = name |
|
69 self.verbose_name = verbose_name |
|
70 self.primary_key = primary_key |
|
71 self.max_length, self._unique = max_length, unique |
|
72 self.blank, self.null = blank, null |
|
73 # Oracle treats the empty string ('') as null, so coerce the null |
|
74 # option whenever '' is a possible value. |
|
75 if self.empty_strings_allowed and connection.features.interprets_empty_strings_as_nulls: |
|
76 self.null = True |
|
77 self.rel = rel |
|
78 self.default = default |
|
79 self.editable = editable |
|
80 self.serialize = serialize |
|
81 self.unique_for_date, self.unique_for_month = unique_for_date, unique_for_month |
|
82 self.unique_for_year = unique_for_year |
|
83 self._choices = choices or [] |
|
84 self.help_text = help_text |
|
85 self.db_column = db_column |
|
86 self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE |
|
87 self.auto_created = auto_created |
|
88 |
|
89 # Set db_index to True if the field has a relationship and doesn't explicitly set db_index. |
|
90 self.db_index = db_index |
|
91 |
|
92 # Adjust the appropriate creation counter, and save our local copy. |
|
93 if auto_created: |
|
94 self.creation_counter = Field.auto_creation_counter |
|
95 Field.auto_creation_counter -= 1 |
|
96 else: |
|
97 self.creation_counter = Field.creation_counter |
|
98 Field.creation_counter += 1 |
|
99 |
|
100 def __cmp__(self, other): |
|
101 # This is needed because bisect does not take a comparison function. |
|
102 return cmp(self.creation_counter, other.creation_counter) |
|
103 |
|
104 def __deepcopy__(self, memodict): |
|
105 # We don't have to deepcopy very much here, since most things are not |
|
106 # intended to be altered after initial creation. |
|
107 obj = copy.copy(self) |
|
108 if self.rel: |
|
109 obj.rel = copy.copy(self.rel) |
|
110 memodict[id(self)] = obj |
|
111 return obj |
|
112 |
|
113 def to_python(self, value): |
|
114 """ |
|
115 Converts the input value into the expected Python data type, raising |
|
116 django.core.exceptions.ValidationError if the data can't be converted. |
|
117 Returns the converted value. Subclasses should override this. |
|
118 """ |
|
119 return value |
|
120 |
|
121 def db_type(self): |
|
122 """ |
|
123 Returns the database column data type for this field, taking into |
|
124 account the DATABASE_ENGINE setting. |
|
125 """ |
|
126 # The default implementation of this method looks at the |
|
127 # backend-specific DATA_TYPES dictionary, looking up the field by its |
|
128 # "internal type". |
|
129 # |
|
130 # A Field class can implement the get_internal_type() method to specify |
|
131 # which *preexisting* Django Field class it's most similar to -- i.e., |
|
132 # an XMLField is represented by a TEXT column type, which is the same |
|
133 # as the TextField Django field type, which means XMLField's |
|
134 # get_internal_type() returns 'TextField'. |
|
135 # |
|
136 # But the limitation of the get_internal_type() / data_types approach |
|
137 # is that it cannot handle database column types that aren't already |
|
138 # mapped to one of the built-in Django field types. In this case, you |
|
139 # can implement db_type() instead of get_internal_type() to specify |
|
140 # exactly which wacky database column type you want to use. |
|
141 data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_") |
|
142 try: |
|
143 return connection.creation.data_types[self.get_internal_type()] % data |
|
144 except KeyError: |
|
145 return None |
|
146 |
|
147 def unique(self): |
|
148 return self._unique or self.primary_key |
|
149 unique = property(unique) |
|
150 |
|
151 def set_attributes_from_name(self, name): |
|
152 self.name = name |
|
153 self.attname, self.column = self.get_attname_column() |
|
154 if self.verbose_name is None and name: |
|
155 self.verbose_name = name.replace('_', ' ') |
|
156 |
|
157 def contribute_to_class(self, cls, name): |
|
158 self.set_attributes_from_name(name) |
|
159 cls._meta.add_field(self) |
|
160 if self.choices: |
|
161 setattr(cls, 'get_%s_display' % self.name, curry(cls._get_FIELD_display, field=self)) |
|
162 |
|
163 def get_attname(self): |
|
164 return self.name |
|
165 |
|
166 def get_attname_column(self): |
|
167 attname = self.get_attname() |
|
168 column = self.db_column or attname |
|
169 return attname, column |
|
170 |
|
171 def get_cache_name(self): |
|
172 return '_%s_cache' % self.name |
|
173 |
|
174 def get_internal_type(self): |
|
175 return self.__class__.__name__ |
|
176 |
|
177 def pre_save(self, model_instance, add): |
|
178 "Returns field's value just before saving." |
|
179 return getattr(model_instance, self.attname) |
|
180 |
|
181 def get_db_prep_value(self, value): |
|
182 """Returns field's value prepared for interacting with the database |
|
183 backend. |
|
184 |
|
185 Used by the default implementations of ``get_db_prep_save``and |
|
186 `get_db_prep_lookup``` |
|
187 """ |
|
188 return value |
|
189 |
|
190 def get_db_prep_save(self, value): |
|
191 "Returns field's value prepared for saving into a database." |
|
192 return self.get_db_prep_value(value) |
|
193 |
|
194 def get_db_prep_lookup(self, lookup_type, value): |
|
195 "Returns field's value prepared for database lookup." |
|
196 if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'): |
|
197 # If the value has a relabel_aliases method, it will need to |
|
198 # be invoked before the final SQL is evaluated |
|
199 if hasattr(value, 'relabel_aliases'): |
|
200 return value |
|
201 if hasattr(value, 'as_sql'): |
|
202 sql, params = value.as_sql() |
|
203 else: |
|
204 sql, params = value._as_sql() |
|
205 return QueryWrapper(('(%s)' % sql), params) |
|
206 |
|
207 if lookup_type in ('regex', 'iregex', 'month', 'day', 'week_day', 'search'): |
|
208 return [value] |
|
209 elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'): |
|
210 return [self.get_db_prep_value(value)] |
|
211 elif lookup_type in ('range', 'in'): |
|
212 return [self.get_db_prep_value(v) for v in value] |
|
213 elif lookup_type in ('contains', 'icontains'): |
|
214 return ["%%%s%%" % connection.ops.prep_for_like_query(value)] |
|
215 elif lookup_type == 'iexact': |
|
216 return [connection.ops.prep_for_iexact_query(value)] |
|
217 elif lookup_type in ('startswith', 'istartswith'): |
|
218 return ["%s%%" % connection.ops.prep_for_like_query(value)] |
|
219 elif lookup_type in ('endswith', 'iendswith'): |
|
220 return ["%%%s" % connection.ops.prep_for_like_query(value)] |
|
221 elif lookup_type == 'isnull': |
|
222 return [] |
|
223 elif lookup_type == 'year': |
|
224 try: |
|
225 value = int(value) |
|
226 except ValueError: |
|
227 raise ValueError("The __year lookup type requires an integer argument") |
|
228 |
|
229 if self.get_internal_type() == 'DateField': |
|
230 return connection.ops.year_lookup_bounds_for_date_field(value) |
|
231 else: |
|
232 return connection.ops.year_lookup_bounds(value) |
|
233 |
|
234 raise TypeError("Field has invalid lookup: %s" % lookup_type) |
|
235 |
|
236 def has_default(self): |
|
237 "Returns a boolean of whether this field has a default value." |
|
238 return self.default is not NOT_PROVIDED |
|
239 |
|
240 def get_default(self): |
|
241 "Returns the default value for this field." |
|
242 if self.has_default(): |
|
243 if callable(self.default): |
|
244 return self.default() |
|
245 return force_unicode(self.default, strings_only=True) |
|
246 if not self.empty_strings_allowed or (self.null and not connection.features.interprets_empty_strings_as_nulls): |
|
247 return None |
|
248 return "" |
|
249 |
|
250 def get_validator_unique_lookup_type(self): |
|
251 return '%s__exact' % self.name |
|
252 |
|
253 def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH): |
|
254 """Returns choices with a default blank choices included, for use |
|
255 as SelectField choices for this field.""" |
|
256 first_choice = include_blank and blank_choice or [] |
|
257 if self.choices: |
|
258 return first_choice + list(self.choices) |
|
259 rel_model = self.rel.to |
|
260 if hasattr(self.rel, 'get_related_field'): |
|
261 lst = [(getattr(x, self.rel.get_related_field().attname), smart_unicode(x)) for x in rel_model._default_manager.complex_filter(self.rel.limit_choices_to)] |
|
262 else: |
|
263 lst = [(x._get_pk_val(), smart_unicode(x)) for x in rel_model._default_manager.complex_filter(self.rel.limit_choices_to)] |
|
264 return first_choice + lst |
|
265 |
|
266 def get_choices_default(self): |
|
267 return self.get_choices() |
|
268 |
|
269 def get_flatchoices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH): |
|
270 "Returns flattened choices with a default blank choice included." |
|
271 first_choice = include_blank and blank_choice or [] |
|
272 return first_choice + list(self.flatchoices) |
|
273 |
|
274 def _get_val_from_obj(self, obj): |
|
275 if obj: |
|
276 return getattr(obj, self.attname) |
|
277 else: |
|
278 return self.get_default() |
|
279 |
|
280 def value_to_string(self, obj): |
|
281 """ |
|
282 Returns a string value of this field from the passed obj. |
|
283 This is used by the serialization framework. |
|
284 """ |
|
285 return smart_unicode(self._get_val_from_obj(obj)) |
|
286 |
|
287 def bind(self, fieldmapping, original, bound_field_class): |
|
288 return bound_field_class(self, fieldmapping, original) |
|
289 |
|
290 def _get_choices(self): |
|
291 if hasattr(self._choices, 'next'): |
|
292 choices, self._choices = tee(self._choices) |
|
293 return choices |
|
294 else: |
|
295 return self._choices |
|
296 choices = property(_get_choices) |
|
297 |
|
298 def _get_flatchoices(self): |
|
299 """Flattened version of choices tuple.""" |
|
300 flat = [] |
|
301 for choice, value in self.choices: |
|
302 if type(value) in (list, tuple): |
|
303 flat.extend(value) |
|
304 else: |
|
305 flat.append((choice,value)) |
|
306 return flat |
|
307 flatchoices = property(_get_flatchoices) |
|
308 |
|
309 def save_form_data(self, instance, data): |
|
310 setattr(instance, self.name, data) |
|
311 |
|
312 def formfield(self, form_class=forms.CharField, **kwargs): |
|
313 "Returns a django.forms.Field instance for this database Field." |
|
314 defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} |
|
315 if self.has_default(): |
|
316 defaults['initial'] = self.get_default() |
|
317 if callable(self.default): |
|
318 defaults['show_hidden_initial'] = True |
|
319 if self.choices: |
|
320 # Fields with choices get special treatment. |
|
321 include_blank = self.blank or not (self.has_default() or 'initial' in kwargs) |
|
322 defaults['choices'] = self.get_choices(include_blank=include_blank) |
|
323 defaults['coerce'] = self.to_python |
|
324 if self.null: |
|
325 defaults['empty_value'] = None |
|
326 form_class = forms.TypedChoiceField |
|
327 # Many of the subclass-specific formfield arguments (min_value, |
|
328 # max_value) don't apply for choice fields, so be sure to only pass |
|
329 # the values that TypedChoiceField will understand. |
|
330 for k in kwargs.keys(): |
|
331 if k not in ('coerce', 'empty_value', 'choices', 'required', |
|
332 'widget', 'label', 'initial', 'help_text', |
|
333 'error_messages'): |
|
334 del kwargs[k] |
|
335 defaults.update(kwargs) |
|
336 return form_class(**defaults) |
|
337 |
|
338 def value_from_object(self, obj): |
|
339 "Returns the value of this field in the given model instance." |
|
340 return getattr(obj, self.attname) |
|
341 |
|
342 class AutoField(Field): |
|
343 empty_strings_allowed = False |
|
344 def __init__(self, *args, **kwargs): |
|
345 assert kwargs.get('primary_key', False) is True, "%ss must have primary_key=True." % self.__class__.__name__ |
|
346 kwargs['blank'] = True |
|
347 Field.__init__(self, *args, **kwargs) |
|
348 |
|
349 def to_python(self, value): |
|
350 if value is None: |
|
351 return value |
|
352 try: |
|
353 return int(value) |
|
354 except (TypeError, ValueError): |
|
355 raise exceptions.ValidationError( |
|
356 _("This value must be an integer.")) |
|
357 |
|
358 def get_db_prep_value(self, value): |
|
359 if value is None: |
|
360 return None |
|
361 return int(value) |
|
362 |
|
363 def contribute_to_class(self, cls, name): |
|
364 assert not cls._meta.has_auto_field, "A model can't have more than one AutoField." |
|
365 super(AutoField, self).contribute_to_class(cls, name) |
|
366 cls._meta.has_auto_field = True |
|
367 cls._meta.auto_field = self |
|
368 |
|
369 def formfield(self, **kwargs): |
|
370 return None |
|
371 |
|
372 class BooleanField(Field): |
|
373 empty_strings_allowed = False |
|
374 def __init__(self, *args, **kwargs): |
|
375 kwargs['blank'] = True |
|
376 if 'default' not in kwargs and not kwargs.get('null'): |
|
377 kwargs['default'] = False |
|
378 Field.__init__(self, *args, **kwargs) |
|
379 |
|
380 def get_internal_type(self): |
|
381 return "BooleanField" |
|
382 |
|
383 def to_python(self, value): |
|
384 if value in (True, False): return value |
|
385 if value in ('t', 'True', '1'): return True |
|
386 if value in ('f', 'False', '0'): return False |
|
387 raise exceptions.ValidationError( |
|
388 _("This value must be either True or False.")) |
|
389 |
|
390 def get_db_prep_lookup(self, lookup_type, value): |
|
391 # Special-case handling for filters coming from a web request (e.g. the |
|
392 # admin interface). Only works for scalar values (not lists). If you're |
|
393 # passing in a list, you might as well make things the right type when |
|
394 # constructing the list. |
|
395 if value in ('1', '0'): |
|
396 value = bool(int(value)) |
|
397 return super(BooleanField, self).get_db_prep_lookup(lookup_type, value) |
|
398 |
|
399 def get_db_prep_value(self, value): |
|
400 if value is None: |
|
401 return None |
|
402 return bool(value) |
|
403 |
|
404 def formfield(self, **kwargs): |
|
405 # Unlike most fields, BooleanField figures out include_blank from |
|
406 # self.null instead of self.blank. |
|
407 if self.choices: |
|
408 include_blank = self.null or not (self.has_default() or 'initial' in kwargs) |
|
409 defaults = {'choices': self.get_choices(include_blank=include_blank)} |
|
410 else: |
|
411 defaults = {'form_class': forms.BooleanField} |
|
412 defaults.update(kwargs) |
|
413 return super(BooleanField, self).formfield(**defaults) |
|
414 |
|
415 class CharField(Field): |
|
416 def get_internal_type(self): |
|
417 return "CharField" |
|
418 |
|
419 def to_python(self, value): |
|
420 if isinstance(value, basestring): |
|
421 return value |
|
422 if value is None: |
|
423 if self.null: |
|
424 return value |
|
425 else: |
|
426 raise exceptions.ValidationError( |
|
427 ugettext_lazy("This field cannot be null.")) |
|
428 return smart_unicode(value) |
|
429 |
|
430 def formfield(self, **kwargs): |
|
431 defaults = {'max_length': self.max_length} |
|
432 defaults.update(kwargs) |
|
433 return super(CharField, self).formfield(**defaults) |
|
434 |
|
435 # TODO: Maybe move this into contrib, because it's specialized. |
|
436 class CommaSeparatedIntegerField(CharField): |
|
437 def formfield(self, **kwargs): |
|
438 defaults = { |
|
439 'form_class': forms.RegexField, |
|
440 'regex': '^[\d,]+$', |
|
441 'max_length': self.max_length, |
|
442 'error_messages': { |
|
443 'invalid': _(u'Enter only digits separated by commas.'), |
|
444 } |
|
445 } |
|
446 defaults.update(kwargs) |
|
447 return super(CommaSeparatedIntegerField, self).formfield(**defaults) |
|
448 |
|
449 ansi_date_re = re.compile(r'^\d{4}-\d{1,2}-\d{1,2}$') |
|
450 |
|
451 class DateField(Field): |
|
452 empty_strings_allowed = False |
|
453 def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): |
|
454 self.auto_now, self.auto_now_add = auto_now, auto_now_add |
|
455 #HACKs : auto_now_add/auto_now should be done as a default or a pre_save. |
|
456 if auto_now or auto_now_add: |
|
457 kwargs['editable'] = False |
|
458 kwargs['blank'] = True |
|
459 Field.__init__(self, verbose_name, name, **kwargs) |
|
460 |
|
461 def get_internal_type(self): |
|
462 return "DateField" |
|
463 |
|
464 def to_python(self, value): |
|
465 if value is None: |
|
466 return value |
|
467 if isinstance(value, datetime.datetime): |
|
468 return value.date() |
|
469 if isinstance(value, datetime.date): |
|
470 return value |
|
471 |
|
472 if not ansi_date_re.search(value): |
|
473 raise exceptions.ValidationError( |
|
474 _('Enter a valid date in YYYY-MM-DD format.')) |
|
475 # Now that we have the date string in YYYY-MM-DD format, check to make |
|
476 # sure it's a valid date. |
|
477 # We could use time.strptime here and catch errors, but datetime.date |
|
478 # produces much friendlier error messages. |
|
479 year, month, day = map(int, value.split('-')) |
|
480 try: |
|
481 return datetime.date(year, month, day) |
|
482 except ValueError, e: |
|
483 msg = _('Invalid date: %s') % _(str(e)) |
|
484 raise exceptions.ValidationError(msg) |
|
485 |
|
486 def pre_save(self, model_instance, add): |
|
487 if self.auto_now or (self.auto_now_add and add): |
|
488 value = datetime.datetime.now() |
|
489 setattr(model_instance, self.attname, value) |
|
490 return value |
|
491 else: |
|
492 return super(DateField, self).pre_save(model_instance, add) |
|
493 |
|
494 def contribute_to_class(self, cls, name): |
|
495 super(DateField,self).contribute_to_class(cls, name) |
|
496 if not self.null: |
|
497 setattr(cls, 'get_next_by_%s' % self.name, |
|
498 curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=True)) |
|
499 setattr(cls, 'get_previous_by_%s' % self.name, |
|
500 curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=False)) |
|
501 |
|
502 def get_db_prep_lookup(self, lookup_type, value): |
|
503 # For "__month", "__day", and "__week_day" lookups, convert the value |
|
504 # to an int so the database backend always sees a consistent type. |
|
505 if lookup_type in ('month', 'day', 'week_day'): |
|
506 return [int(value)] |
|
507 return super(DateField, self).get_db_prep_lookup(lookup_type, value) |
|
508 |
|
509 def get_db_prep_value(self, value): |
|
510 # Casts dates into the format expected by the backend |
|
511 return connection.ops.value_to_db_date(self.to_python(value)) |
|
512 |
|
513 def value_to_string(self, obj): |
|
514 val = self._get_val_from_obj(obj) |
|
515 if val is None: |
|
516 data = '' |
|
517 else: |
|
518 data = datetime_safe.new_date(val).strftime("%Y-%m-%d") |
|
519 return data |
|
520 |
|
521 def formfield(self, **kwargs): |
|
522 defaults = {'form_class': forms.DateField} |
|
523 defaults.update(kwargs) |
|
524 return super(DateField, self).formfield(**defaults) |
|
525 |
|
526 class DateTimeField(DateField): |
|
527 def get_internal_type(self): |
|
528 return "DateTimeField" |
|
529 |
|
530 def to_python(self, value): |
|
531 if value is None: |
|
532 return value |
|
533 if isinstance(value, datetime.datetime): |
|
534 return value |
|
535 if isinstance(value, datetime.date): |
|
536 return datetime.datetime(value.year, value.month, value.day) |
|
537 |
|
538 # Attempt to parse a datetime: |
|
539 value = smart_str(value) |
|
540 # split usecs, because they are not recognized by strptime. |
|
541 if '.' in value: |
|
542 try: |
|
543 value, usecs = value.split('.') |
|
544 usecs = int(usecs) |
|
545 except ValueError: |
|
546 raise exceptions.ValidationError( |
|
547 _('Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format.')) |
|
548 else: |
|
549 usecs = 0 |
|
550 kwargs = {'microsecond': usecs} |
|
551 try: # Seconds are optional, so try converting seconds first. |
|
552 return datetime.datetime(*time.strptime(value, '%Y-%m-%d %H:%M:%S')[:6], |
|
553 **kwargs) |
|
554 |
|
555 except ValueError: |
|
556 try: # Try without seconds. |
|
557 return datetime.datetime(*time.strptime(value, '%Y-%m-%d %H:%M')[:5], |
|
558 **kwargs) |
|
559 except ValueError: # Try without hour/minutes/seconds. |
|
560 try: |
|
561 return datetime.datetime(*time.strptime(value, '%Y-%m-%d')[:3], |
|
562 **kwargs) |
|
563 except ValueError: |
|
564 raise exceptions.ValidationError( |
|
565 _('Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format.')) |
|
566 |
|
567 def get_db_prep_value(self, value): |
|
568 # Casts dates into the format expected by the backend |
|
569 return connection.ops.value_to_db_datetime(self.to_python(value)) |
|
570 |
|
571 def value_to_string(self, obj): |
|
572 val = self._get_val_from_obj(obj) |
|
573 if val is None: |
|
574 data = '' |
|
575 else: |
|
576 d = datetime_safe.new_datetime(val) |
|
577 data = d.strftime('%Y-%m-%d %H:%M:%S') |
|
578 return data |
|
579 |
|
580 def formfield(self, **kwargs): |
|
581 defaults = {'form_class': forms.DateTimeField} |
|
582 defaults.update(kwargs) |
|
583 return super(DateTimeField, self).formfield(**defaults) |
|
584 |
|
585 class DecimalField(Field): |
|
586 empty_strings_allowed = False |
|
587 def __init__(self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs): |
|
588 self.max_digits, self.decimal_places = max_digits, decimal_places |
|
589 Field.__init__(self, verbose_name, name, **kwargs) |
|
590 |
|
591 def get_internal_type(self): |
|
592 return "DecimalField" |
|
593 |
|
594 def to_python(self, value): |
|
595 if value is None: |
|
596 return value |
|
597 try: |
|
598 return decimal.Decimal(value) |
|
599 except decimal.InvalidOperation: |
|
600 raise exceptions.ValidationError( |
|
601 _("This value must be a decimal number.")) |
|
602 |
|
603 def _format(self, value): |
|
604 if isinstance(value, basestring) or value is None: |
|
605 return value |
|
606 else: |
|
607 return self.format_number(value) |
|
608 |
|
609 def format_number(self, value): |
|
610 """ |
|
611 Formats a number into a string with the requisite number of digits and |
|
612 decimal places. |
|
613 """ |
|
614 # Method moved to django.db.backends.util. |
|
615 # |
|
616 # It is preserved because it is used by the oracle backend |
|
617 # (django.db.backends.oracle.query), and also for |
|
618 # backwards-compatibility with any external code which may have used |
|
619 # this method. |
|
620 from django.db.backends import util |
|
621 return util.format_number(value, self.max_digits, self.decimal_places) |
|
622 |
|
623 def get_db_prep_save(self, value): |
|
624 return connection.ops.value_to_db_decimal(self.to_python(value), |
|
625 self.max_digits, self.decimal_places) |
|
626 |
|
627 def get_db_prep_value(self, value): |
|
628 return self.to_python(value) |
|
629 |
|
630 def formfield(self, **kwargs): |
|
631 defaults = { |
|
632 'max_digits': self.max_digits, |
|
633 'decimal_places': self.decimal_places, |
|
634 'form_class': forms.DecimalField, |
|
635 } |
|
636 defaults.update(kwargs) |
|
637 return super(DecimalField, self).formfield(**defaults) |
|
638 |
|
639 class EmailField(CharField): |
|
640 def __init__(self, *args, **kwargs): |
|
641 kwargs['max_length'] = kwargs.get('max_length', 75) |
|
642 CharField.__init__(self, *args, **kwargs) |
|
643 |
|
644 def formfield(self, **kwargs): |
|
645 defaults = {'form_class': forms.EmailField} |
|
646 defaults.update(kwargs) |
|
647 return super(EmailField, self).formfield(**defaults) |
|
648 |
|
649 class FilePathField(Field): |
|
650 def __init__(self, verbose_name=None, name=None, path='', match=None, recursive=False, **kwargs): |
|
651 self.path, self.match, self.recursive = path, match, recursive |
|
652 kwargs['max_length'] = kwargs.get('max_length', 100) |
|
653 Field.__init__(self, verbose_name, name, **kwargs) |
|
654 |
|
655 def formfield(self, **kwargs): |
|
656 defaults = { |
|
657 'path': self.path, |
|
658 'match': self.match, |
|
659 'recursive': self.recursive, |
|
660 'form_class': forms.FilePathField, |
|
661 } |
|
662 defaults.update(kwargs) |
|
663 return super(FilePathField, self).formfield(**defaults) |
|
664 |
|
665 def get_internal_type(self): |
|
666 return "FilePathField" |
|
667 |
|
668 class FloatField(Field): |
|
669 empty_strings_allowed = False |
|
670 |
|
671 def get_db_prep_value(self, value): |
|
672 if value is None: |
|
673 return None |
|
674 return float(value) |
|
675 |
|
676 def get_internal_type(self): |
|
677 return "FloatField" |
|
678 |
|
679 def to_python(self, value): |
|
680 if value is None: |
|
681 return value |
|
682 try: |
|
683 return float(value) |
|
684 except (TypeError, ValueError): |
|
685 raise exceptions.ValidationError( |
|
686 _("This value must be a float.")) |
|
687 |
|
688 def formfield(self, **kwargs): |
|
689 defaults = {'form_class': forms.FloatField} |
|
690 defaults.update(kwargs) |
|
691 return super(FloatField, self).formfield(**defaults) |
|
692 |
|
693 class IntegerField(Field): |
|
694 empty_strings_allowed = False |
|
695 def get_db_prep_value(self, value): |
|
696 if value is None: |
|
697 return None |
|
698 return int(value) |
|
699 |
|
700 def get_internal_type(self): |
|
701 return "IntegerField" |
|
702 |
|
703 def to_python(self, value): |
|
704 if value is None: |
|
705 return value |
|
706 try: |
|
707 return int(value) |
|
708 except (TypeError, ValueError): |
|
709 raise exceptions.ValidationError( |
|
710 _("This value must be an integer.")) |
|
711 |
|
712 def formfield(self, **kwargs): |
|
713 defaults = {'form_class': forms.IntegerField} |
|
714 defaults.update(kwargs) |
|
715 return super(IntegerField, self).formfield(**defaults) |
|
716 |
|
717 class IPAddressField(Field): |
|
718 empty_strings_allowed = False |
|
719 def __init__(self, *args, **kwargs): |
|
720 kwargs['max_length'] = 15 |
|
721 Field.__init__(self, *args, **kwargs) |
|
722 |
|
723 def get_internal_type(self): |
|
724 return "IPAddressField" |
|
725 |
|
726 def formfield(self, **kwargs): |
|
727 defaults = {'form_class': forms.IPAddressField} |
|
728 defaults.update(kwargs) |
|
729 return super(IPAddressField, self).formfield(**defaults) |
|
730 |
|
731 class NullBooleanField(Field): |
|
732 empty_strings_allowed = False |
|
733 def __init__(self, *args, **kwargs): |
|
734 kwargs['null'] = True |
|
735 Field.__init__(self, *args, **kwargs) |
|
736 |
|
737 def get_internal_type(self): |
|
738 return "NullBooleanField" |
|
739 |
|
740 def to_python(self, value): |
|
741 if value in (None, True, False): return value |
|
742 if value in ('None',): return None |
|
743 if value in ('t', 'True', '1'): return True |
|
744 if value in ('f', 'False', '0'): return False |
|
745 raise exceptions.ValidationError( |
|
746 _("This value must be either None, True or False.")) |
|
747 |
|
748 def get_db_prep_lookup(self, lookup_type, value): |
|
749 # Special-case handling for filters coming from a web request (e.g. the |
|
750 # admin interface). Only works for scalar values (not lists). If you're |
|
751 # passing in a list, you might as well make things the right type when |
|
752 # constructing the list. |
|
753 if value in ('1', '0'): |
|
754 value = bool(int(value)) |
|
755 return super(NullBooleanField, self).get_db_prep_lookup(lookup_type, value) |
|
756 |
|
757 def get_db_prep_value(self, value): |
|
758 if value is None: |
|
759 return None |
|
760 return bool(value) |
|
761 |
|
762 def formfield(self, **kwargs): |
|
763 defaults = { |
|
764 'form_class': forms.NullBooleanField, |
|
765 'required': not self.blank, |
|
766 'label': capfirst(self.verbose_name), |
|
767 'help_text': self.help_text} |
|
768 defaults.update(kwargs) |
|
769 return super(NullBooleanField, self).formfield(**defaults) |
|
770 |
|
771 class PositiveIntegerField(IntegerField): |
|
772 def get_internal_type(self): |
|
773 return "PositiveIntegerField" |
|
774 |
|
775 def formfield(self, **kwargs): |
|
776 defaults = {'min_value': 0} |
|
777 defaults.update(kwargs) |
|
778 return super(PositiveIntegerField, self).formfield(**defaults) |
|
779 |
|
780 class PositiveSmallIntegerField(IntegerField): |
|
781 def get_internal_type(self): |
|
782 return "PositiveSmallIntegerField" |
|
783 |
|
784 def formfield(self, **kwargs): |
|
785 defaults = {'min_value': 0} |
|
786 defaults.update(kwargs) |
|
787 return super(PositiveSmallIntegerField, self).formfield(**defaults) |
|
788 |
|
789 class SlugField(CharField): |
|
790 def __init__(self, *args, **kwargs): |
|
791 kwargs['max_length'] = kwargs.get('max_length', 50) |
|
792 # Set db_index=True unless it's been set manually. |
|
793 if 'db_index' not in kwargs: |
|
794 kwargs['db_index'] = True |
|
795 super(SlugField, self).__init__(*args, **kwargs) |
|
796 |
|
797 def get_internal_type(self): |
|
798 return "SlugField" |
|
799 |
|
800 def formfield(self, **kwargs): |
|
801 defaults = {'form_class': forms.SlugField} |
|
802 defaults.update(kwargs) |
|
803 return super(SlugField, self).formfield(**defaults) |
|
804 |
|
805 class SmallIntegerField(IntegerField): |
|
806 def get_internal_type(self): |
|
807 return "SmallIntegerField" |
|
808 |
|
809 class TextField(Field): |
|
810 def get_internal_type(self): |
|
811 return "TextField" |
|
812 |
|
813 def formfield(self, **kwargs): |
|
814 defaults = {'widget': forms.Textarea} |
|
815 defaults.update(kwargs) |
|
816 return super(TextField, self).formfield(**defaults) |
|
817 |
|
818 class TimeField(Field): |
|
819 empty_strings_allowed = False |
|
820 def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): |
|
821 self.auto_now, self.auto_now_add = auto_now, auto_now_add |
|
822 if auto_now or auto_now_add: |
|
823 kwargs['editable'] = False |
|
824 Field.__init__(self, verbose_name, name, **kwargs) |
|
825 |
|
826 def get_internal_type(self): |
|
827 return "TimeField" |
|
828 |
|
829 def to_python(self, value): |
|
830 if value is None: |
|
831 return None |
|
832 if isinstance(value, datetime.time): |
|
833 return value |
|
834 if isinstance(value, datetime.datetime): |
|
835 # Not usually a good idea to pass in a datetime here (it loses |
|
836 # information), but this can be a side-effect of interacting with a |
|
837 # database backend (e.g. Oracle), so we'll be accommodating. |
|
838 return value.time |
|
839 |
|
840 # Attempt to parse a datetime: |
|
841 value = smart_str(value) |
|
842 # split usecs, because they are not recognized by strptime. |
|
843 if '.' in value: |
|
844 try: |
|
845 value, usecs = value.split('.') |
|
846 usecs = int(usecs) |
|
847 except ValueError: |
|
848 raise exceptions.ValidationError( |
|
849 _('Enter a valid time in HH:MM[:ss[.uuuuuu]] format.')) |
|
850 else: |
|
851 usecs = 0 |
|
852 kwargs = {'microsecond': usecs} |
|
853 |
|
854 try: # Seconds are optional, so try converting seconds first. |
|
855 return datetime.time(*time.strptime(value, '%H:%M:%S')[3:6], |
|
856 **kwargs) |
|
857 except ValueError: |
|
858 try: # Try without seconds. |
|
859 return datetime.time(*time.strptime(value, '%H:%M')[3:5], |
|
860 **kwargs) |
|
861 except ValueError: |
|
862 raise exceptions.ValidationError( |
|
863 _('Enter a valid time in HH:MM[:ss[.uuuuuu]] format.')) |
|
864 |
|
865 def pre_save(self, model_instance, add): |
|
866 if self.auto_now or (self.auto_now_add and add): |
|
867 value = datetime.datetime.now().time() |
|
868 setattr(model_instance, self.attname, value) |
|
869 return value |
|
870 else: |
|
871 return super(TimeField, self).pre_save(model_instance, add) |
|
872 |
|
873 def get_db_prep_value(self, value): |
|
874 # Casts times into the format expected by the backend |
|
875 return connection.ops.value_to_db_time(self.to_python(value)) |
|
876 |
|
877 def value_to_string(self, obj): |
|
878 val = self._get_val_from_obj(obj) |
|
879 if val is None: |
|
880 data = '' |
|
881 else: |
|
882 data = val.strftime("%H:%M:%S") |
|
883 return data |
|
884 |
|
885 def formfield(self, **kwargs): |
|
886 defaults = {'form_class': forms.TimeField} |
|
887 defaults.update(kwargs) |
|
888 return super(TimeField, self).formfield(**defaults) |
|
889 |
|
890 class URLField(CharField): |
|
891 def __init__(self, verbose_name=None, name=None, verify_exists=True, **kwargs): |
|
892 kwargs['max_length'] = kwargs.get('max_length', 200) |
|
893 self.verify_exists = verify_exists |
|
894 CharField.__init__(self, verbose_name, name, **kwargs) |
|
895 |
|
896 def formfield(self, **kwargs): |
|
897 defaults = {'form_class': forms.URLField, 'verify_exists': self.verify_exists} |
|
898 defaults.update(kwargs) |
|
899 return super(URLField, self).formfield(**defaults) |
|
900 |
|
901 class XMLField(TextField): |
|
902 def __init__(self, verbose_name=None, name=None, schema_path=None, **kwargs): |
|
903 self.schema_path = schema_path |
|
904 Field.__init__(self, verbose_name, name, **kwargs) |