6 from itertools
import tee
8 from django
.db
import connection
9 from django
.db
.models
.query_utils
import QueryWrapper
10 from django
.conf
import settings
11 from django
import forms
12 from django
.core
import exceptions
, validators
13 from django
.utils
.datastructures
import DictWrapper
14 from django
.utils
.dateparse
import parse_date
, parse_datetime
, parse_time
15 from django
.utils
.functional
import curry
16 from django
.utils
.text
import capfirst
17 from django
.utils
import timezone
18 from django
.utils
.translation
import ugettext_lazy
as _
19 from django
.utils
.encoding
import smart_unicode
, force_unicode
, smart_str
20 from django
.utils
.ipv6
import clean_ipv6_address
25 # The values to use for "blank" in SelectFields. Will be appended to the start
26 # of most "choices" lists.
27 BLANK_CHOICE_DASH
= [("", "---------")]
28 BLANK_CHOICE_NONE
= [("", "None")]
30 class FieldDoesNotExist(Exception):
33 # A guide to Field parameters:
35 # * name: The name of the field specifed in the model.
36 # * attname: The attribute to use on the model object. This is the same as
37 # "name", except in the case of ForeignKeys, where "_id" is
39 # * db_column: The db_column specified in the model (or None).
40 # * column: The database column for this field. This is the same as
41 # "attname", except if db_column is specified.
43 # Code that introspects values, or does other dynamic things, should use
44 # attname. For example, this gets the primary key value of object "obj":
46 # getattr(obj, opts.pk.attname)
49 """Base class for all field types"""
51 # Designates whether empty strings fundamentally are allowed at the
53 empty_strings_allowed
= True
55 # These track each time a Field instance is created. Used to retain order.
56 # The auto_creation_counter is used for fields that Django implicitly
57 # creates, creation_counter is used for all user-specified fields.
59 auto_creation_counter
= -1
60 default_validators
= [] # Default set of validators
61 default_error_messages
= {
62 'invalid_choice': _(u
'Value %r is not a valid choice.'),
63 'null': _(u
'This field cannot be null.'),
64 'blank': _(u
'This field cannot be blank.'),
65 'unique': _(u
'%(model_name)s with this %(field_label)s '
69 # Generic field type description, usually overriden by subclasses
70 def _description(self
):
71 return _(u
'Field of type: %(field_type)s') % {
72 'field_type': self
.__class
__.__name
__
74 description
= property(_description
)
76 def __init__(self
, verbose_name
=None, name
=None, primary_key
=False,
77 max_length
=None, unique
=False, blank
=False, null
=False,
78 db_index
=False, rel
=None, default
=NOT_PROVIDED
, editable
=True,
79 serialize
=True, unique_for_date
=None, unique_for_month
=None,
80 unique_for_year
=None, choices
=None, help_text
='', db_column
=None,
81 db_tablespace
=None, auto_created
=False, validators
=[],
84 self
.verbose_name
= verbose_name
85 self
.primary_key
= primary_key
86 self
.max_length
, self
._unique
= max_length
, unique
87 self
.blank
, self
.null
= blank
, null
88 # Oracle treats the empty string ('') as null, so coerce the null
89 # option whenever '' is a possible value.
90 if (self
.empty_strings_allowed
and
91 connection
.features
.interprets_empty_strings_as_nulls
):
94 self
.default
= default
95 self
.editable
= editable
96 self
.serialize
= serialize
97 self
.unique_for_date
, self
.unique_for_month
= (unique_for_date
,
99 self
.unique_for_year
= unique_for_year
100 self
._choices
= choices
or []
101 self
.help_text
= help_text
102 self
.db_column
= db_column
103 self
.db_tablespace
= db_tablespace
or settings
.DEFAULT_INDEX_TABLESPACE
104 self
.auto_created
= auto_created
106 # Set db_index to True if the field has a relationship and doesn't
107 # explicitly set db_index.
108 self
.db_index
= db_index
110 # Adjust the appropriate creation counter, and save our local copy.
112 self
.creation_counter
= Field
.auto_creation_counter
113 Field
.auto_creation_counter
-= 1
115 self
.creation_counter
= Field
.creation_counter
116 Field
.creation_counter
+= 1
118 self
.validators
= self
.default_validators
+ validators
121 for c
in reversed(self
.__class
__.__mro
__):
122 messages
.update(getattr(c
, 'default_error_messages', {}))
123 messages
.update(error_messages
or {})
124 self
.error_messages
= messages
126 def __cmp__(self
, other
):
127 # This is needed because bisect does not take a comparison function.
128 return cmp(self
.creation_counter
, other
.creation_counter
)
130 def __deepcopy__(self
, memodict
):
131 # We don't have to deepcopy very much here, since most things are not
132 # intended to be altered after initial creation.
133 obj
= copy
.copy(self
)
135 obj
.rel
= copy
.copy(self
.rel
)
136 memodict
[id(self
)] = obj
139 def to_python(self
, value
):
141 Converts the input value into the expected Python data type, raising
142 django.core.exceptions.ValidationError if the data can't be converted.
143 Returns the converted value. Subclasses should override this.
147 def run_validators(self
, value
):
148 if value
in validators
.EMPTY_VALUES
:
152 for v
in self
.validators
:
155 except exceptions
.ValidationError
, e
:
156 if hasattr(e
, 'code') and e
.code
in self
.error_messages
:
157 message
= self
.error_messages
[e
.code
]
159 message
= message
% e
.params
160 errors
.append(message
)
162 errors
.extend(e
.messages
)
164 raise exceptions
.ValidationError(errors
)
166 def validate(self
, value
, model_instance
):
168 Validates value and throws ValidationError. Subclasses should override
169 this to provide validation logic.
171 if not self
.editable
:
172 # Skip validation for non-editable fields.
174 if self
._choices
and value
:
175 for option_key
, option_value
in self
.choices
:
176 if isinstance(option_value
, (list, tuple)):
177 # This is an optgroup, so look inside the group for
179 for optgroup_key
, optgroup_value
in option_value
:
180 if value
== optgroup_key
:
182 elif value
== option_key
:
184 msg
= self
.error_messages
['invalid_choice'] % value
185 raise exceptions
.ValidationError(msg
)
187 if value
is None and not self
.null
:
188 raise exceptions
.ValidationError(self
.error_messages
['null'])
190 if not self
.blank
and value
in validators
.EMPTY_VALUES
:
191 raise exceptions
.ValidationError(self
.error_messages
['blank'])
193 def clean(self
, value
, model_instance
):
195 Convert the value's type and run validation. Validation errors
196 from to_python and validate are propagated. The correct value is
197 returned if no error is raised.
199 value
= self
.to_python(value
)
200 self
.validate(value
, model_instance
)
201 self
.run_validators(value
)
204 def db_type(self
, connection
):
206 Returns the database column data type for this field, for the provided
209 # The default implementation of this method looks at the
210 # backend-specific DATA_TYPES dictionary, looking up the field by its
213 # A Field class can implement the get_internal_type() method to specify
214 # which *preexisting* Django Field class it's most similar to -- i.e.,
215 # a custom field might be represented by a TEXT column type, which is
216 # the same as the TextField Django field type, which means the custom
217 # field's get_internal_type() returns 'TextField'.
219 # But the limitation of the get_internal_type() / data_types approach
220 # is that it cannot handle database column types that aren't already
221 # mapped to one of the built-in Django field types. In this case, you
222 # can implement db_type() instead of get_internal_type() to specify
223 # exactly which wacky database column type you want to use.
224 data
= DictWrapper(self
.__dict
__, connection
.ops
.quote_name
, "qn_")
226 return (connection
.creation
.data_types
[self
.get_internal_type()]
233 return self
._unique
or self
.primary_key
235 def set_attributes_from_name(self
, name
):
238 self
.attname
, self
.column
= self
.get_attname_column()
239 if self
.verbose_name
is None and self
.name
:
240 self
.verbose_name
= self
.name
.replace('_', ' ')
242 def contribute_to_class(self
, cls
, name
):
243 self
.set_attributes_from_name(name
)
245 cls
._meta
.add_field(self
)
247 setattr(cls
, 'get_%s_display' % self
.name
,
248 curry(cls
._get
_FIELD
_display
, field
=self
))
250 def get_attname(self
):
253 def get_attname_column(self
):
254 attname
= self
.get_attname()
255 column
= self
.db_column
or attname
256 return attname
, column
258 def get_cache_name(self
):
259 return '_%s_cache' % self
.name
261 def get_internal_type(self
):
262 return self
.__class
__.__name
__
264 def pre_save(self
, model_instance
, add
):
266 Returns field's value just before saving.
268 return getattr(model_instance
, self
.attname
)
270 def get_prep_value(self
, value
):
272 Perform preliminary non-db specific value checks and conversions.
276 def get_db_prep_value(self
, value
, connection
, prepared
=False):
277 """Returns field's value prepared for interacting with the database
280 Used by the default implementations of ``get_db_prep_save``and
281 `get_db_prep_lookup```
284 value
= self
.get_prep_value(value
)
287 def get_db_prep_save(self
, value
, connection
):
289 Returns field's value prepared for saving into a database.
291 return self
.get_db_prep_value(value
, connection
=connection
,
294 def get_prep_lookup(self
, lookup_type
, value
):
296 Perform preliminary non-db specific lookup checks and conversions
298 if hasattr(value
, 'prepare'):
299 return value
.prepare()
300 if hasattr(value
, '_prepare'):
301 return value
._prepare
()
304 'regex', 'iregex', 'month', 'day', 'week_day', 'search',
305 'contains', 'icontains', 'iexact', 'startswith', 'istartswith',
306 'endswith', 'iendswith', 'isnull'
309 elif lookup_type
in ('exact', 'gt', 'gte', 'lt', 'lte'):
310 return self
.get_prep_value(value
)
311 elif lookup_type
in ('range', 'in'):
312 return [self
.get_prep_value(v
) for v
in value
]
313 elif lookup_type
== 'year':
317 raise ValueError("The __year lookup type requires an integer "
320 raise TypeError("Field has invalid lookup: %s" % lookup_type
)
322 def get_db_prep_lookup(self
, lookup_type
, value
, connection
,
325 Returns field's value prepared for database lookup.
328 value
= self
.get_prep_lookup(lookup_type
, value
)
329 if hasattr(value
, 'get_compiler'):
330 value
= value
.get_compiler(connection
=connection
)
331 if hasattr(value
, 'as_sql') or hasattr(value
, '_as_sql'):
332 # If the value has a relabel_aliases method, it will need to
333 # be invoked before the final SQL is evaluated
334 if hasattr(value
, 'relabel_aliases'):
336 if hasattr(value
, 'as_sql'):
337 sql
, params
= value
.as_sql()
339 sql
, params
= value
._as
_sql
(connection
=connection
)
340 return QueryWrapper(('(%s)' % sql
), params
)
342 if lookup_type
in ('regex', 'iregex', 'month', 'day', 'week_day',
345 elif lookup_type
in ('exact', 'gt', 'gte', 'lt', 'lte'):
346 return [self
.get_db_prep_value(value
, connection
=connection
,
348 elif lookup_type
in ('range', 'in'):
349 return [self
.get_db_prep_value(v
, connection
=connection
,
350 prepared
=prepared
) for v
in value
]
351 elif lookup_type
in ('contains', 'icontains'):
352 return ["%%%s%%" % connection
.ops
.prep_for_like_query(value
)]
353 elif lookup_type
== 'iexact':
354 return [connection
.ops
.prep_for_iexact_query(value
)]
355 elif lookup_type
in ('startswith', 'istartswith'):
356 return ["%s%%" % connection
.ops
.prep_for_like_query(value
)]
357 elif lookup_type
in ('endswith', 'iendswith'):
358 return ["%%%s" % connection
.ops
.prep_for_like_query(value
)]
359 elif lookup_type
== 'isnull':
361 elif lookup_type
== 'year':
362 if self
.get_internal_type() == 'DateField':
363 return connection
.ops
.year_lookup_bounds_for_date_field(value
)
365 return connection
.ops
.year_lookup_bounds(value
)
367 def has_default(self
):
369 Returns a boolean of whether this field has a default value.
371 return self
.default
is not NOT_PROVIDED
373 def get_default(self
):
375 Returns the default value for this field.
377 if self
.has_default():
378 if callable(self
.default
):
379 return self
.default()
380 return force_unicode(self
.default
, strings_only
=True)
381 if (not self
.empty_strings_allowed
or (self
.null
and
382 not connection
.features
.interprets_empty_strings_as_nulls
)):
386 def get_validator_unique_lookup_type(self
):
387 return '%s__exact' % self
.name
389 def get_choices(self
, include_blank
=True, blank_choice
=BLANK_CHOICE_DASH
):
390 """Returns choices with a default blank choices included, for use
391 as SelectField choices for this field."""
392 first_choice
= include_blank
and blank_choice
or []
394 return first_choice
+ list(self
.choices
)
395 rel_model
= self
.rel
.to
396 if hasattr(self
.rel
, 'get_related_field'):
397 lst
= [(getattr(x
, self
.rel
.get_related_field().attname
),
399 for x
in rel_model
._default
_manager
.complex_filter(
400 self
.rel
.limit_choices_to
)]
402 lst
= [(x
._get
_pk
_val
(), smart_unicode(x
))
403 for x
in rel_model
._default
_manager
.complex_filter(
404 self
.rel
.limit_choices_to
)]
405 return first_choice
+ lst
407 def get_choices_default(self
):
408 return self
.get_choices()
410 def get_flatchoices(self
, include_blank
=True,
411 blank_choice
=BLANK_CHOICE_DASH
):
413 Returns flattened choices with a default blank choice included.
415 first_choice
= include_blank
and blank_choice
or []
416 return first_choice
+ list(self
.flatchoices
)
418 def _get_val_from_obj(self
, obj
):
420 return getattr(obj
, self
.attname
)
422 return self
.get_default()
424 def value_to_string(self
, obj
):
426 Returns a string value of this field from the passed obj.
427 This is used by the serialization framework.
429 return smart_unicode(self
._get
_val
_from
_obj
(obj
))
431 def bind(self
, fieldmapping
, original
, bound_field_class
):
432 return bound_field_class(self
, fieldmapping
, original
)
434 def _get_choices(self
):
435 if hasattr(self
._choices
, 'next'):
436 choices
, self
._choices
= tee(self
._choices
)
440 choices
= property(_get_choices
)
442 def _get_flatchoices(self
):
443 """Flattened version of choices tuple."""
445 for choice
, value
in self
.choices
:
446 if isinstance(value
, (list, tuple)):
449 flat
.append((choice
,value
))
451 flatchoices
= property(_get_flatchoices
)
453 def save_form_data(self
, instance
, data
):
454 setattr(instance
, self
.name
, data
)
456 def formfield(self
, form_class
=forms
.CharField
, **kwargs
):
458 Returns a django.forms.Field instance for this database Field.
460 defaults
= {'required': not self
.blank
,
461 'label': capfirst(self
.verbose_name
),
462 'help_text': self
.help_text
}
463 if self
.has_default():
464 if callable(self
.default
):
465 defaults
['initial'] = self
.default
466 defaults
['show_hidden_initial'] = True
468 defaults
['initial'] = self
.get_default()
470 # Fields with choices get special treatment.
471 include_blank
= (self
.blank
or
472 not (self
.has_default() or 'initial' in kwargs
))
473 defaults
['choices'] = self
.get_choices(include_blank
=include_blank
)
474 defaults
['coerce'] = self
.to_python
476 defaults
['empty_value'] = None
477 form_class
= forms
.TypedChoiceField
478 # Many of the subclass-specific formfield arguments (min_value,
479 # max_value) don't apply for choice fields, so be sure to only pass
480 # the values that TypedChoiceField will understand.
481 for k
in kwargs
.keys():
482 if k
not in ('coerce', 'empty_value', 'choices', 'required',
483 'widget', 'label', 'initial', 'help_text',
484 'error_messages', 'show_hidden_initial'):
486 defaults
.update(kwargs
)
487 return form_class(**defaults
)
489 def value_from_object(self
, obj
):
491 Returns the value of this field in the given model instance.
493 return getattr(obj
, self
.attname
)
497 Displays the module, class and name of the field.
499 path
= '%s.%s' % (self
.__class
__.__module
__, self
.__class
__.__name
__)
500 name
= getattr(self
, 'name', None)
502 return '<%s: %s>' % (path
, name
)
505 class AutoField(Field
):
506 description
= _("Integer")
508 empty_strings_allowed
= False
509 default_error_messages
= {
510 'invalid': _(u
"'%s' value must be an integer."),
513 def __init__(self
, *args
, **kwargs
):
514 assert kwargs
.get('primary_key', False) is True, \
515 "%ss must have primary_key=True." % self
.__class
__.__name
__
516 kwargs
['blank'] = True
517 Field
.__init
__(self
, *args
, **kwargs
)
519 def get_internal_type(self
):
522 def to_python(self
, value
):
527 except (TypeError, ValueError):
528 msg
= self
.error_messages
['invalid'] % str(value
)
529 raise exceptions
.ValidationError(msg
)
531 def validate(self
, value
, model_instance
):
534 def get_prep_value(self
, value
):
539 def contribute_to_class(self
, cls
, name
):
540 assert not cls
._meta
.has_auto_field
, \
541 "A model can't have more than one AutoField."
542 super(AutoField
, self
).contribute_to_class(cls
, name
)
543 cls
._meta
.has_auto_field
= True
544 cls
._meta
.auto_field
= self
546 def formfield(self
, **kwargs
):
549 class BooleanField(Field
):
550 empty_strings_allowed
= False
551 default_error_messages
= {
552 'invalid': _(u
"'%s' value must be either True or False."),
554 description
= _("Boolean (Either True or False)")
556 def __init__(self
, *args
, **kwargs
):
557 kwargs
['blank'] = True
558 if 'default' not in kwargs
and not kwargs
.get('null'):
559 kwargs
['default'] = False
560 Field
.__init
__(self
, *args
, **kwargs
)
562 def get_internal_type(self
):
563 return "BooleanField"
565 def to_python(self
, value
):
566 if value
in (True, False):
567 # if value is 1 or 0 than it's equal to True or False, but we want
568 # to return a true bool for semantic reasons.
570 if value
in ('t', 'True', '1'):
572 if value
in ('f', 'False', '0'):
574 msg
= self
.error_messages
['invalid'] % str(value
)
575 raise exceptions
.ValidationError(msg
)
577 def get_prep_lookup(self
, lookup_type
, value
):
578 # Special-case handling for filters coming from a Web request (e.g. the
579 # admin interface). Only works for scalar values (not lists). If you're
580 # passing in a list, you might as well make things the right type when
581 # constructing the list.
582 if value
in ('1', '0'):
583 value
= bool(int(value
))
584 return super(BooleanField
, self
).get_prep_lookup(lookup_type
, value
)
586 def get_prep_value(self
, value
):
591 def formfield(self
, **kwargs
):
592 # Unlike most fields, BooleanField figures out include_blank from
593 # self.null instead of self.blank.
595 include_blank
= (self
.null
or
596 not (self
.has_default() or 'initial' in kwargs
))
597 defaults
= {'choices': self
.get_choices(
598 include_blank
=include_blank
)}
600 defaults
= {'form_class': forms
.BooleanField
}
601 defaults
.update(kwargs
)
602 return super(BooleanField
, self
).formfield(**defaults
)
604 class CharField(Field
):
605 description
= _("String (up to %(max_length)s)")
607 def __init__(self
, *args
, **kwargs
):
608 super(CharField
, self
).__init
__(*args
, **kwargs
)
609 self
.validators
.append(validators
.MaxLengthValidator(self
.max_length
))
611 def get_internal_type(self
):
614 def to_python(self
, value
):
615 if isinstance(value
, basestring
) or value
is None:
617 return smart_unicode(value
)
619 def get_prep_value(self
, value
):
620 return self
.to_python(value
)
622 def formfield(self
, **kwargs
):
623 # Passing max_length to forms.CharField means that the value's length
624 # will be validated twice. This is considered acceptable since we want
625 # the value in the form field (to pass into widget for example).
626 defaults
= {'max_length': self
.max_length
}
627 defaults
.update(kwargs
)
628 return super(CharField
, self
).formfield(**defaults
)
630 # TODO: Maybe move this into contrib, because it's specialized.
631 class CommaSeparatedIntegerField(CharField
):
632 default_validators
= [validators
.validate_comma_separated_integer_list
]
633 description
= _("Comma-separated integers")
635 def formfield(self
, **kwargs
):
638 'invalid': _(u
'Enter only digits separated by commas.'),
641 defaults
.update(kwargs
)
642 return super(CommaSeparatedIntegerField
, self
).formfield(**defaults
)
644 class DateField(Field
):
645 empty_strings_allowed
= False
646 default_error_messages
= {
647 'invalid': _(u
"'%s' value has an invalid date format. It must be "
648 u
"in YYYY-MM-DD format."),
649 'invalid_date': _(u
"'%s' value has the correct format (YYYY-MM-DD) "
650 u
"but it is an invalid date."),
652 description
= _("Date (without time)")
654 def __init__(self
, verbose_name
=None, name
=None, auto_now
=False,
655 auto_now_add
=False, **kwargs
):
656 self
.auto_now
, self
.auto_now_add
= auto_now
, auto_now_add
657 if auto_now
or auto_now_add
:
658 kwargs
['editable'] = False
659 kwargs
['blank'] = True
660 Field
.__init
__(self
, verbose_name
, name
, **kwargs
)
662 def get_internal_type(self
):
665 def to_python(self
, value
):
668 if isinstance(value
, datetime
.datetime
):
670 if isinstance(value
, datetime
.date
):
673 value
= smart_str(value
)
676 parsed
= parse_date(value
)
677 if parsed
is not None:
680 msg
= self
.error_messages
['invalid_date'] % value
681 raise exceptions
.ValidationError(msg
)
683 msg
= self
.error_messages
['invalid'] % value
684 raise exceptions
.ValidationError(msg
)
686 def pre_save(self
, model_instance
, add
):
687 if self
.auto_now
or (self
.auto_now_add
and add
):
688 value
= datetime
.date
.today()
689 setattr(model_instance
, self
.attname
, value
)
692 return super(DateField
, self
).pre_save(model_instance
, add
)
694 def contribute_to_class(self
, cls
, name
):
695 super(DateField
,self
).contribute_to_class(cls
, name
)
697 setattr(cls
, 'get_next_by_%s' % self
.name
,
698 curry(cls
._get
_next
_or
_previous
_by
_FIELD
, field
=self
,
700 setattr(cls
, 'get_previous_by_%s' % self
.name
,
701 curry(cls
._get
_next
_or
_previous
_by
_FIELD
, field
=self
,
704 def get_prep_lookup(self
, lookup_type
, value
):
705 # For "__month", "__day", and "__week_day" lookups, convert the value
706 # to an int so the database backend always sees a consistent type.
707 if lookup_type
in ('month', 'day', 'week_day'):
709 return super(DateField
, self
).get_prep_lookup(lookup_type
, value
)
711 def get_prep_value(self
, value
):
712 return self
.to_python(value
)
714 def get_db_prep_value(self
, value
, connection
, prepared
=False):
715 # Casts dates into the format expected by the backend
717 value
= self
.get_prep_value(value
)
718 return connection
.ops
.value_to_db_date(value
)
720 def value_to_string(self
, obj
):
721 val
= self
._get
_val
_from
_obj
(obj
)
722 return '' if val
is None else val
.isoformat()
724 def formfield(self
, **kwargs
):
725 defaults
= {'form_class': forms
.DateField
}
726 defaults
.update(kwargs
)
727 return super(DateField
, self
).formfield(**defaults
)
729 class DateTimeField(DateField
):
730 empty_strings_allowed
= False
731 default_error_messages
= {
732 'invalid': _(u
"'%s' value has an invalid format. It must be in "
733 u
"YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."),
734 'invalid_date': _(u
"'%s' value has the correct format "
735 u
"(YYYY-MM-DD) but it is an invalid date."),
736 'invalid_datetime': _(u
"'%s' value has the correct format "
737 u
"(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
738 u
"but it is an invalid date/time."),
740 description
= _("Date (with time)")
742 # __init__ is inherited from DateField
744 def get_internal_type(self
):
745 return "DateTimeField"
747 def to_python(self
, value
):
750 if isinstance(value
, datetime
.datetime
):
752 if isinstance(value
, datetime
.date
):
753 value
= datetime
.datetime(value
.year
, value
.month
, value
.day
)
755 # For backwards compatibility, interpret naive datetimes in
756 # local time. This won't work during DST change, but we can't
757 # do much about it, so we let the exceptions percolate up the
759 warnings
.warn(u
"DateTimeField received a naive datetime (%s)"
760 u
" while time zone support is active." % value
,
762 default_timezone
= timezone
.get_default_timezone()
763 value
= timezone
.make_aware(value
, default_timezone
)
766 value
= smart_str(value
)
769 parsed
= parse_datetime(value
)
770 if parsed
is not None:
773 msg
= self
.error_messages
['invalid_datetime'] % value
774 raise exceptions
.ValidationError(msg
)
777 parsed
= parse_date(value
)
778 if parsed
is not None:
779 return datetime
.datetime(parsed
.year
, parsed
.month
, parsed
.day
)
781 msg
= self
.error_messages
['invalid_date'] % value
782 raise exceptions
.ValidationError(msg
)
784 msg
= self
.error_messages
['invalid'] % value
785 raise exceptions
.ValidationError(msg
)
787 def pre_save(self
, model_instance
, add
):
788 if self
.auto_now
or (self
.auto_now_add
and add
):
789 value
= timezone
.now()
790 setattr(model_instance
, self
.attname
, value
)
793 return super(DateTimeField
, self
).pre_save(model_instance
, add
)
795 # contribute_to_class is inherited from DateField, it registers
796 # get_next_by_FOO and get_prev_by_FOO
798 # get_prep_lookup is inherited from DateField
800 def get_prep_value(self
, value
):
801 value
= self
.to_python(value
)
802 if value
is not None and settings
.USE_TZ
and timezone
.is_naive(value
):
803 # For backwards compatibility, interpret naive datetimes in local
804 # time. This won't work during DST change, but we can't do much
805 # about it, so we let the exceptions percolate up the call stack.
806 warnings
.warn(u
"DateTimeField received a naive datetime (%s)"
807 u
" while time zone support is active." % value
,
809 default_timezone
= timezone
.get_default_timezone()
810 value
= timezone
.make_aware(value
, default_timezone
)
813 def get_db_prep_value(self
, value
, connection
, prepared
=False):
814 # Casts datetimes into the format expected by the backend
816 value
= self
.get_prep_value(value
)
817 return connection
.ops
.value_to_db_datetime(value
)
819 def value_to_string(self
, obj
):
820 val
= self
._get
_val
_from
_obj
(obj
)
821 return '' if val
is None else val
.isoformat()
823 def formfield(self
, **kwargs
):
824 defaults
= {'form_class': forms
.DateTimeField
}
825 defaults
.update(kwargs
)
826 return super(DateTimeField
, self
).formfield(**defaults
)
828 class DecimalField(Field
):
829 empty_strings_allowed
= False
830 default_error_messages
= {
831 'invalid': _(u
"'%s' value must be a decimal number."),
833 description
= _("Decimal number")
835 def __init__(self
, verbose_name
=None, name
=None, max_digits
=None,
836 decimal_places
=None, **kwargs
):
837 self
.max_digits
, self
.decimal_places
= max_digits
, decimal_places
838 Field
.__init
__(self
, verbose_name
, name
, **kwargs
)
840 def get_internal_type(self
):
841 return "DecimalField"
843 def to_python(self
, value
):
847 return decimal
.Decimal(value
)
848 except decimal
.InvalidOperation
:
849 msg
= self
.error_messages
['invalid'] % str(value
)
850 raise exceptions
.ValidationError(msg
)
852 def _format(self
, value
):
853 if isinstance(value
, basestring
) or value
is None:
856 return self
.format_number(value
)
858 def format_number(self
, value
):
860 Formats a number into a string with the requisite number of digits and
863 # Method moved to django.db.backends.util.
865 # It is preserved because it is used by the oracle backend
866 # (django.db.backends.oracle.query), and also for
867 # backwards-compatibility with any external code which may have used
869 from django
.db
.backends
import util
870 return util
.format_number(value
, self
.max_digits
, self
.decimal_places
)
872 def get_db_prep_save(self
, value
, connection
):
873 return connection
.ops
.value_to_db_decimal(self
.to_python(value
),
874 self
.max_digits
, self
.decimal_places
)
876 def get_prep_value(self
, value
):
877 return self
.to_python(value
)
879 def formfield(self
, **kwargs
):
881 'max_digits': self
.max_digits
,
882 'decimal_places': self
.decimal_places
,
883 'form_class': forms
.DecimalField
,
885 defaults
.update(kwargs
)
886 return super(DecimalField
, self
).formfield(**defaults
)
888 class EmailField(CharField
):
889 default_validators
= [validators
.validate_email
]
890 description
= _("E-mail address")
892 def __init__(self
, *args
, **kwargs
):
893 kwargs
['max_length'] = kwargs
.get('max_length', 75)
894 CharField
.__init
__(self
, *args
, **kwargs
)
896 def formfield(self
, **kwargs
):
897 # As with CharField, this will cause email validation to be performed
900 'form_class': forms
.EmailField
,
902 defaults
.update(kwargs
)
903 return super(EmailField
, self
).formfield(**defaults
)
905 class FilePathField(Field
):
906 description
= _("File path")
908 def __init__(self
, verbose_name
=None, name
=None, path
='', match
=None,
909 recursive
=False, **kwargs
):
910 self
.path
, self
.match
, self
.recursive
= path
, match
, recursive
911 kwargs
['max_length'] = kwargs
.get('max_length', 100)
912 Field
.__init
__(self
, verbose_name
, name
, **kwargs
)
914 def formfield(self
, **kwargs
):
918 'recursive': self
.recursive
,
919 'form_class': forms
.FilePathField
,
921 defaults
.update(kwargs
)
922 return super(FilePathField
, self
).formfield(**defaults
)
924 def get_internal_type(self
):
925 return "FilePathField"
927 class FloatField(Field
):
928 empty_strings_allowed
= False
929 default_error_messages
= {
930 'invalid': _("'%s' value must be a float."),
932 description
= _("Floating point number")
934 def get_prep_value(self
, value
):
939 def get_internal_type(self
):
942 def to_python(self
, value
):
947 except (TypeError, ValueError):
948 msg
= self
.error_messages
['invalid'] % str(value
)
949 raise exceptions
.ValidationError(msg
)
951 def formfield(self
, **kwargs
):
952 defaults
= {'form_class': forms
.FloatField
}
953 defaults
.update(kwargs
)
954 return super(FloatField
, self
).formfield(**defaults
)
956 class IntegerField(Field
):
957 empty_strings_allowed
= False
958 default_error_messages
= {
959 'invalid': _("'%s' value must be an integer."),
961 description
= _("Integer")
963 def get_prep_value(self
, value
):
968 def get_prep_lookup(self
, lookup_type
, value
):
969 if ((lookup_type
== 'gte' or lookup_type
== 'lt')
970 and isinstance(value
, float)):
971 value
= math
.ceil(value
)
972 return super(IntegerField
, self
).get_prep_lookup(lookup_type
, value
)
974 def get_internal_type(self
):
975 return "IntegerField"
977 def to_python(self
, value
):
982 except (TypeError, ValueError):
983 msg
= self
.error_messages
['invalid'] % str(value
)
984 raise exceptions
.ValidationError(msg
)
986 def formfield(self
, **kwargs
):
987 defaults
= {'form_class': forms
.IntegerField
}
988 defaults
.update(kwargs
)
989 return super(IntegerField
, self
).formfield(**defaults
)
991 class BigIntegerField(IntegerField
):
992 empty_strings_allowed
= False
993 description
= _("Big (8 byte) integer")
994 MAX_BIGINT
= 9223372036854775807
996 def get_internal_type(self
):
997 return "BigIntegerField"
999 def formfield(self
, **kwargs
):
1000 defaults
= {'min_value': -BigIntegerField
.MAX_BIGINT
- 1,
1001 'max_value': BigIntegerField
.MAX_BIGINT
}
1002 defaults
.update(kwargs
)
1003 return super(BigIntegerField
, self
).formfield(**defaults
)
1005 class IPAddressField(Field
):
1006 empty_strings_allowed
= False
1007 description
= _("IPv4 address")
1009 def __init__(self
, *args
, **kwargs
):
1010 kwargs
['max_length'] = 15
1011 Field
.__init
__(self
, *args
, **kwargs
)
1013 def get_internal_type(self
):
1014 return "IPAddressField"
1016 def formfield(self
, **kwargs
):
1017 defaults
= {'form_class': forms
.IPAddressField
}
1018 defaults
.update(kwargs
)
1019 return super(IPAddressField
, self
).formfield(**defaults
)
1021 class GenericIPAddressField(Field
):
1022 empty_strings_allowed
= True
1023 description
= _("IP address")
1024 default_error_messages
= {}
1026 def __init__(self
, verbose_name
=None, name
=None, protocol
='both',
1027 unpack_ipv4
=False, *args
, **kwargs
):
1028 self
.unpack_ipv4
= unpack_ipv4
1029 self
.default_validators
, invalid_error_message
= \
1030 validators
.ip_address_validators(protocol
, unpack_ipv4
)
1031 self
.default_error_messages
['invalid'] = invalid_error_message
1032 kwargs
['max_length'] = 39
1033 Field
.__init
__(self
, verbose_name
, name
, *args
, **kwargs
)
1035 def get_internal_type(self
):
1036 return "GenericIPAddressField"
1038 def to_python(self
, value
):
1039 if value
and ':' in value
:
1040 return clean_ipv6_address(value
,
1041 self
.unpack_ipv4
, self
.error_messages
['invalid'])
1044 def get_db_prep_value(self
, value
, connection
, prepared
=False):
1046 value
= self
.get_prep_value(value
)
1047 return value
or None
1049 def get_prep_value(self
, value
):
1050 if value
and ':' in value
:
1052 return clean_ipv6_address(value
, self
.unpack_ipv4
)
1053 except exceptions
.ValidationError
:
1057 def formfield(self
, **kwargs
):
1058 defaults
= {'form_class': forms
.GenericIPAddressField
}
1059 defaults
.update(kwargs
)
1060 return super(GenericIPAddressField
, self
).formfield(**defaults
)
1063 class NullBooleanField(Field
):
1064 empty_strings_allowed
= False
1065 default_error_messages
= {
1066 'invalid': _("'%s' value must be either None, True or False."),
1068 description
= _("Boolean (Either True, False or None)")
1070 def __init__(self
, *args
, **kwargs
):
1071 kwargs
['null'] = True
1072 kwargs
['blank'] = True
1073 Field
.__init
__(self
, *args
, **kwargs
)
1075 def get_internal_type(self
):
1076 return "NullBooleanField"
1078 def to_python(self
, value
):
1081 if value
in (True, False):
1083 if value
in ('None',):
1085 if value
in ('t', 'True', '1'):
1087 if value
in ('f', 'False', '0'):
1089 msg
= self
.error_messages
['invalid'] % str(value
)
1090 raise exceptions
.ValidationError(msg
)
1092 def get_prep_lookup(self
, lookup_type
, value
):
1093 # Special-case handling for filters coming from a Web request (e.g. the
1094 # admin interface). Only works for scalar values (not lists). If you're
1095 # passing in a list, you might as well make things the right type when
1096 # constructing the list.
1097 if value
in ('1', '0'):
1098 value
= bool(int(value
))
1099 return super(NullBooleanField
, self
).get_prep_lookup(lookup_type
,
1102 def get_prep_value(self
, value
):
1107 def formfield(self
, **kwargs
):
1109 'form_class': forms
.NullBooleanField
,
1110 'required': not self
.blank
,
1111 'label': capfirst(self
.verbose_name
),
1112 'help_text': self
.help_text
}
1113 defaults
.update(kwargs
)
1114 return super(NullBooleanField
, self
).formfield(**defaults
)
1116 class PositiveIntegerField(IntegerField
):
1117 description
= _("Positive integer")
1119 def get_internal_type(self
):
1120 return "PositiveIntegerField"
1122 def formfield(self
, **kwargs
):
1123 defaults
= {'min_value': 0}
1124 defaults
.update(kwargs
)
1125 return super(PositiveIntegerField
, self
).formfield(**defaults
)
1127 class PositiveSmallIntegerField(IntegerField
):
1128 description
= _("Positive small integer")
1130 def get_internal_type(self
):
1131 return "PositiveSmallIntegerField"
1133 def formfield(self
, **kwargs
):
1134 defaults
= {'min_value': 0}
1135 defaults
.update(kwargs
)
1136 return super(PositiveSmallIntegerField
, self
).formfield(**defaults
)
1138 class SlugField(CharField
):
1139 description
= _("Slug (up to %(max_length)s)")
1141 def __init__(self
, *args
, **kwargs
):
1142 kwargs
['max_length'] = kwargs
.get('max_length', 50)
1143 # Set db_index=True unless it's been set manually.
1144 if 'db_index' not in kwargs
:
1145 kwargs
['db_index'] = True
1146 super(SlugField
, self
).__init
__(*args
, **kwargs
)
1148 def get_internal_type(self
):
1151 def formfield(self
, **kwargs
):
1152 defaults
= {'form_class': forms
.SlugField
}
1153 defaults
.update(kwargs
)
1154 return super(SlugField
, self
).formfield(**defaults
)
1156 class SmallIntegerField(IntegerField
):
1157 description
= _("Small integer")
1159 def get_internal_type(self
):
1160 return "SmallIntegerField"
1162 class TextField(Field
):
1163 description
= _("Text")
1165 def get_internal_type(self
):
1168 def get_prep_value(self
, value
):
1169 if isinstance(value
, basestring
) or value
is None:
1171 return smart_unicode(value
)
1173 def formfield(self
, **kwargs
):
1174 defaults
= {'widget': forms
.Textarea
}
1175 defaults
.update(kwargs
)
1176 return super(TextField
, self
).formfield(**defaults
)
1178 class TimeField(Field
):
1179 empty_strings_allowed
= False
1180 default_error_messages
= {
1181 'invalid': _(u
"'%s' value has an invalid format. It must be in "
1182 u
"HH:MM[:ss[.uuuuuu]] format."),
1183 'invalid_time': _(u
"'%s' value has the correct format "
1184 u
"(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."),
1186 description
= _("Time")
1188 def __init__(self
, verbose_name
=None, name
=None, auto_now
=False,
1189 auto_now_add
=False, **kwargs
):
1190 self
.auto_now
, self
.auto_now_add
= auto_now
, auto_now_add
1191 if auto_now
or auto_now_add
:
1192 kwargs
['editable'] = False
1193 kwargs
['blank'] = True
1194 Field
.__init
__(self
, verbose_name
, name
, **kwargs
)
1196 def get_internal_type(self
):
1199 def to_python(self
, value
):
1202 if isinstance(value
, datetime
.time
):
1204 if isinstance(value
, datetime
.datetime
):
1205 # Not usually a good idea to pass in a datetime here (it loses
1206 # information), but this can be a side-effect of interacting with a
1207 # database backend (e.g. Oracle), so we'll be accommodating.
1210 value
= smart_str(value
)
1213 parsed
= parse_time(value
)
1214 if parsed
is not None:
1217 msg
= self
.error_messages
['invalid_time'] % value
1218 raise exceptions
.ValidationError(msg
)
1220 msg
= self
.error_messages
['invalid'] % value
1221 raise exceptions
.ValidationError(msg
)
1223 def pre_save(self
, model_instance
, add
):
1224 if self
.auto_now
or (self
.auto_now_add
and add
):
1225 value
= datetime
.datetime
.now().time()
1226 setattr(model_instance
, self
.attname
, value
)
1229 return super(TimeField
, self
).pre_save(model_instance
, add
)
1231 def get_prep_value(self
, value
):
1232 return self
.to_python(value
)
1234 def get_db_prep_value(self
, value
, connection
, prepared
=False):
1235 # Casts times into the format expected by the backend
1237 value
= self
.get_prep_value(value
)
1238 return connection
.ops
.value_to_db_time(value
)
1240 def value_to_string(self
, obj
):
1241 val
= self
._get
_val
_from
_obj
(obj
)
1242 return '' if val
is None else val
.isoformat()
1244 def formfield(self
, **kwargs
):
1245 defaults
= {'form_class': forms
.TimeField
}
1246 defaults
.update(kwargs
)
1247 return super(TimeField
, self
).formfield(**defaults
)
1249 class URLField(CharField
):
1250 description
= _("URL")
1252 def __init__(self
, verbose_name
=None, name
=None, verify_exists
=False,
1254 kwargs
['max_length'] = kwargs
.get('max_length', 200)
1255 CharField
.__init
__(self
, verbose_name
, name
, **kwargs
)
1256 self
.validators
.append(
1257 validators
.URLValidator(verify_exists
=verify_exists
))
1259 def formfield(self
, **kwargs
):
1260 # As with CharField, this will cause URL validation to be performed
1263 'form_class': forms
.URLField
,
1265 defaults
.update(kwargs
)
1266 return super(URLField
, self
).formfield(**defaults
)