Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/django/db/models/fields/__init__.py: 32%
1324 statements
« prev ^ index » next coverage.py v7.0.5, created at 2023-01-17 06:13 +0000
« prev ^ index » next coverage.py v7.0.5, created at 2023-01-17 06:13 +0000
1import collections.abc
2import copy
3import datetime
4import decimal
5import operator
6import uuid
7import warnings
8from base64 import b64decode, b64encode
9from functools import partialmethod, total_ordering
11from django import forms
12from django.apps import apps
13from django.conf import settings
14from django.core import checks, exceptions, validators
15from django.db import connection, connections, router
16from django.db.models.constants import LOOKUP_SEP
17from django.db.models.query_utils import DeferredAttribute, RegisterLookupMixin
18from django.utils import timezone
19from django.utils.datastructures import DictWrapper
20from django.utils.dateparse import (
21 parse_date,
22 parse_datetime,
23 parse_duration,
24 parse_time,
25)
26from django.utils.duration import duration_microseconds, duration_string
27from django.utils.functional import Promise, cached_property
28from django.utils.ipv6 import clean_ipv6_address
29from django.utils.itercompat import is_iterable
30from django.utils.text import capfirst
31from django.utils.translation import gettext_lazy as _
33__all__ = [
34 "AutoField",
35 "BLANK_CHOICE_DASH",
36 "BigAutoField",
37 "BigIntegerField",
38 "BinaryField",
39 "BooleanField",
40 "CharField",
41 "CommaSeparatedIntegerField",
42 "DateField",
43 "DateTimeField",
44 "DecimalField",
45 "DurationField",
46 "EmailField",
47 "Empty",
48 "Field",
49 "FilePathField",
50 "FloatField",
51 "GenericIPAddressField",
52 "IPAddressField",
53 "IntegerField",
54 "NOT_PROVIDED",
55 "NullBooleanField",
56 "PositiveBigIntegerField",
57 "PositiveIntegerField",
58 "PositiveSmallIntegerField",
59 "SlugField",
60 "SmallAutoField",
61 "SmallIntegerField",
62 "TextField",
63 "TimeField",
64 "URLField",
65 "UUIDField",
66]
69class Empty:
70 pass
73class NOT_PROVIDED:
74 pass
77# The values to use for "blank" in SelectFields. Will be appended to the start
78# of most "choices" lists.
79BLANK_CHOICE_DASH = [("", "---------")]
82def _load_field(app_label, model_name, field_name):
83 return apps.get_model(app_label, model_name)._meta.get_field(field_name)
86# A guide to Field parameters:
87#
88# * name: The name of the field specified in the model.
89# * attname: The attribute to use on the model object. This is the same as
90# "name", except in the case of ForeignKeys, where "_id" is
91# appended.
92# * db_column: The db_column specified in the model (or None).
93# * column: The database column for this field. This is the same as
94# "attname", except if db_column is specified.
95#
96# Code that introspects values, or does other dynamic things, should use
97# attname. For example, this gets the primary key value of object "obj":
98#
99# getattr(obj, opts.pk.attname)
102def _empty(of_cls):
103 new = Empty()
104 new.__class__ = of_cls
105 return new
108def return_None():
109 return None
112@total_ordering
113class Field(RegisterLookupMixin):
114 """Base class for all field types"""
116 # Designates whether empty strings fundamentally are allowed at the
117 # database level.
118 empty_strings_allowed = True
119 empty_values = list(validators.EMPTY_VALUES)
121 # These track each time a Field instance is created. Used to retain order.
122 # The auto_creation_counter is used for fields that Django implicitly
123 # creates, creation_counter is used for all user-specified fields.
124 creation_counter = 0
125 auto_creation_counter = -1
126 default_validators = [] # Default set of validators
127 default_error_messages = {
128 "invalid_choice": _("Value %(value)r is not a valid choice."),
129 "null": _("This field cannot be null."),
130 "blank": _("This field cannot be blank."),
131 "unique": _("%(model_name)s with this %(field_label)s already exists."),
132 "unique_for_date": _(
133 # Translators: The 'lookup_type' is one of 'date', 'year' or
134 # 'month'. Eg: "Title must be unique for pub_date year"
135 "%(field_label)s must be unique for "
136 "%(date_field_label)s %(lookup_type)s."
137 ),
138 }
139 system_check_deprecated_details = None
140 system_check_removed_details = None
142 # Attributes that don't affect a column definition.
143 # These attributes are ignored when altering the field.
144 non_db_attrs = (
145 "blank",
146 "choices",
147 "db_column",
148 "editable",
149 "error_messages",
150 "help_text",
151 "limit_choices_to",
152 # Database-level options are not supported, see #21961.
153 "on_delete",
154 "related_name",
155 "related_query_name",
156 "validators",
157 "verbose_name",
158 )
160 # Field flags
161 hidden = False
163 many_to_many = None
164 many_to_one = None
165 one_to_many = None
166 one_to_one = None
167 related_model = None
169 descriptor_class = DeferredAttribute
171 # Generic field type description, usually overridden by subclasses
172 def _description(self):
173 return _("Field of type: %(field_type)s") % {
174 "field_type": self.__class__.__name__
175 }
177 description = property(_description)
179 def __init__(
180 self,
181 verbose_name=None,
182 name=None,
183 primary_key=False,
184 max_length=None,
185 unique=False,
186 blank=False,
187 null=False,
188 db_index=False,
189 rel=None,
190 default=NOT_PROVIDED,
191 editable=True,
192 serialize=True,
193 unique_for_date=None,
194 unique_for_month=None,
195 unique_for_year=None,
196 choices=None,
197 help_text="",
198 db_column=None,
199 db_tablespace=None,
200 auto_created=False,
201 validators=(),
202 error_messages=None,
203 db_comment=None,
204 ):
205 self.name = name
206 self.verbose_name = verbose_name # May be set by set_attributes_from_name
207 self._verbose_name = verbose_name # Store original for deconstruction
208 self.primary_key = primary_key
209 self.max_length, self._unique = max_length, unique
210 self.blank, self.null = blank, null
211 self.remote_field = rel
212 self.is_relation = self.remote_field is not None
213 self.default = default
214 self.editable = editable
215 self.serialize = serialize
216 self.unique_for_date = unique_for_date
217 self.unique_for_month = unique_for_month
218 self.unique_for_year = unique_for_year
219 if isinstance(choices, collections.abc.Iterator):
220 choices = list(choices)
221 self.choices = choices
222 self.help_text = help_text
223 self.db_index = db_index
224 self.db_column = db_column
225 self.db_comment = db_comment
226 self._db_tablespace = db_tablespace
227 self.auto_created = auto_created
229 # Adjust the appropriate creation counter, and save our local copy.
230 if auto_created:
231 self.creation_counter = Field.auto_creation_counter
232 Field.auto_creation_counter -= 1
233 else:
234 self.creation_counter = Field.creation_counter
235 Field.creation_counter += 1
237 self._validators = list(validators) # Store for deconstruction later
239 self._error_messages = error_messages # Store for deconstruction later
241 def __str__(self):
242 """
243 Return "app_label.model_label.field_name" for fields attached to
244 models.
245 """
246 if not hasattr(self, "model"):
247 return super().__str__()
248 model = self.model
249 return "%s.%s" % (model._meta.label, self.name)
251 def __repr__(self):
252 """Display the module, class, and name of the field."""
253 path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__)
254 name = getattr(self, "name", None)
255 if name is not None:
256 return "<%s: %s>" % (path, name)
257 return "<%s>" % path
259 def check(self, **kwargs):
260 return [
261 *self._check_field_name(),
262 *self._check_choices(),
263 *self._check_db_index(),
264 *self._check_db_comment(**kwargs),
265 *self._check_null_allowed_for_primary_keys(),
266 *self._check_backend_specific_checks(**kwargs),
267 *self._check_validators(),
268 *self._check_deprecation_details(),
269 ]
271 def _check_field_name(self):
272 """
273 Check if field name is valid, i.e. 1) does not end with an
274 underscore, 2) does not contain "__" and 3) is not "pk".
275 """
276 if self.name.endswith("_"):
277 return [
278 checks.Error(
279 "Field names must not end with an underscore.",
280 obj=self,
281 id="fields.E001",
282 )
283 ]
284 elif LOOKUP_SEP in self.name:
285 return [
286 checks.Error(
287 'Field names must not contain "%s".' % LOOKUP_SEP,
288 obj=self,
289 id="fields.E002",
290 )
291 ]
292 elif self.name == "pk":
293 return [
294 checks.Error(
295 "'pk' is a reserved word that cannot be used as a field name.",
296 obj=self,
297 id="fields.E003",
298 )
299 ]
300 else:
301 return []
303 @classmethod
304 def _choices_is_value(cls, value):
305 return isinstance(value, (str, Promise)) or not is_iterable(value)
307 def _check_choices(self):
308 if not self.choices:
309 return []
311 if not is_iterable(self.choices) or isinstance(self.choices, str):
312 return [
313 checks.Error(
314 "'choices' must be an iterable (e.g., a list or tuple).",
315 obj=self,
316 id="fields.E004",
317 )
318 ]
320 choice_max_length = 0
321 # Expect [group_name, [value, display]]
322 for choices_group in self.choices:
323 try:
324 group_name, group_choices = choices_group
325 except (TypeError, ValueError):
326 # Containing non-pairs
327 break
328 try:
329 if not all(
330 self._choices_is_value(value) and self._choices_is_value(human_name)
331 for value, human_name in group_choices
332 ):
333 break
334 if self.max_length is not None and group_choices:
335 choice_max_length = max(
336 [
337 choice_max_length,
338 *(
339 len(value)
340 for value, _ in group_choices
341 if isinstance(value, str)
342 ),
343 ]
344 )
345 except (TypeError, ValueError):
346 # No groups, choices in the form [value, display]
347 value, human_name = group_name, group_choices
348 if not self._choices_is_value(value) or not self._choices_is_value(
349 human_name
350 ):
351 break
352 if self.max_length is not None and isinstance(value, str):
353 choice_max_length = max(choice_max_length, len(value))
355 # Special case: choices=['ab']
356 if isinstance(choices_group, str):
357 break
358 else:
359 if self.max_length is not None and choice_max_length > self.max_length:
360 return [
361 checks.Error(
362 "'max_length' is too small to fit the longest value "
363 "in 'choices' (%d characters)." % choice_max_length,
364 obj=self,
365 id="fields.E009",
366 ),
367 ]
368 return []
370 return [
371 checks.Error(
372 "'choices' must be an iterable containing "
373 "(actual value, human readable name) tuples.",
374 obj=self,
375 id="fields.E005",
376 )
377 ]
379 def _check_db_index(self):
380 if self.db_index not in (None, True, False):
381 return [
382 checks.Error(
383 "'db_index' must be None, True or False.",
384 obj=self,
385 id="fields.E006",
386 )
387 ]
388 else:
389 return []
391 def _check_db_comment(self, databases=None, **kwargs):
392 if not self.db_comment or not databases:
393 return []
394 errors = []
395 for db in databases:
396 if not router.allow_migrate_model(db, self.model):
397 continue
398 connection = connections[db]
399 if not (
400 connection.features.supports_comments
401 or "supports_comments" in self.model._meta.required_db_features
402 ):
403 errors.append(
404 checks.Warning(
405 f"{connection.display_name} does not support comments on "
406 f"columns (db_comment).",
407 obj=self,
408 id="fields.W163",
409 )
410 )
411 return errors
413 def _check_null_allowed_for_primary_keys(self):
414 if (
415 self.primary_key
416 and self.null
417 and not connection.features.interprets_empty_strings_as_nulls
418 ):
419 # We cannot reliably check this for backends like Oracle which
420 # consider NULL and '' to be equal (and thus set up
421 # character-based fields a little differently).
422 return [
423 checks.Error(
424 "Primary keys must not have null=True.",
425 hint=(
426 "Set null=False on the field, or "
427 "remove primary_key=True argument."
428 ),
429 obj=self,
430 id="fields.E007",
431 )
432 ]
433 else:
434 return []
436 def _check_backend_specific_checks(self, databases=None, **kwargs):
437 if databases is None:
438 return []
439 errors = []
440 for alias in databases:
441 if router.allow_migrate_model(alias, self.model):
442 errors.extend(connections[alias].validation.check_field(self, **kwargs))
443 return errors
445 def _check_validators(self):
446 errors = []
447 for i, validator in enumerate(self.validators):
448 if not callable(validator):
449 errors.append(
450 checks.Error(
451 "All 'validators' must be callable.",
452 hint=(
453 "validators[{i}] ({repr}) isn't a function or "
454 "instance of a validator class.".format(
455 i=i,
456 repr=repr(validator),
457 )
458 ),
459 obj=self,
460 id="fields.E008",
461 )
462 )
463 return errors
465 def _check_deprecation_details(self):
466 if self.system_check_removed_details is not None:
467 return [
468 checks.Error(
469 self.system_check_removed_details.get(
470 "msg",
471 "%s has been removed except for support in historical "
472 "migrations." % self.__class__.__name__,
473 ),
474 hint=self.system_check_removed_details.get("hint"),
475 obj=self,
476 id=self.system_check_removed_details.get("id", "fields.EXXX"),
477 )
478 ]
479 elif self.system_check_deprecated_details is not None:
480 return [
481 checks.Warning(
482 self.system_check_deprecated_details.get(
483 "msg", "%s has been deprecated." % self.__class__.__name__
484 ),
485 hint=self.system_check_deprecated_details.get("hint"),
486 obj=self,
487 id=self.system_check_deprecated_details.get("id", "fields.WXXX"),
488 )
489 ]
490 return []
492 def get_col(self, alias, output_field=None):
493 if alias == self.model._meta.db_table and (
494 output_field is None or output_field == self
495 ):
496 return self.cached_col
497 from django.db.models.expressions import Col
499 return Col(alias, self, output_field)
501 @cached_property
502 def cached_col(self):
503 from django.db.models.expressions import Col
505 return Col(self.model._meta.db_table, self)
507 def select_format(self, compiler, sql, params):
508 """
509 Custom format for select clauses. For example, GIS columns need to be
510 selected as AsText(table.col) on MySQL as the table.col data can't be
511 used by Django.
512 """
513 return sql, params
515 def deconstruct(self):
516 """
517 Return enough information to recreate the field as a 4-tuple:
519 * The name of the field on the model, if contribute_to_class() has
520 been run.
521 * The import path of the field, including the class, e.g.
522 django.db.models.IntegerField. This should be the most portable
523 version, so less specific may be better.
524 * A list of positional arguments.
525 * A dict of keyword arguments.
527 Note that the positional or keyword arguments must contain values of
528 the following types (including inner values of collection types):
530 * None, bool, str, int, float, complex, set, frozenset, list, tuple,
531 dict
532 * UUID
533 * datetime.datetime (naive), datetime.date
534 * top-level classes, top-level functions - will be referenced by their
535 full import path
536 * Storage instances - these have their own deconstruct() method
538 This is because the values here must be serialized into a text format
539 (possibly new Python code, possibly JSON) and these are the only types
540 with encoding handlers defined.
542 There's no need to return the exact way the field was instantiated this
543 time, just ensure that the resulting field is the same - prefer keyword
544 arguments over positional ones, and omit parameters with their default
545 values.
546 """
547 # Short-form way of fetching all the default parameters
548 keywords = {}
549 possibles = {
550 "verbose_name": None,
551 "primary_key": False,
552 "max_length": None,
553 "unique": False,
554 "blank": False,
555 "null": False,
556 "db_index": False,
557 "default": NOT_PROVIDED,
558 "editable": True,
559 "serialize": True,
560 "unique_for_date": None,
561 "unique_for_month": None,
562 "unique_for_year": None,
563 "choices": None,
564 "help_text": "",
565 "db_column": None,
566 "db_comment": None,
567 "db_tablespace": None,
568 "auto_created": False,
569 "validators": [],
570 "error_messages": None,
571 }
572 attr_overrides = {
573 "unique": "_unique",
574 "error_messages": "_error_messages",
575 "validators": "_validators",
576 "verbose_name": "_verbose_name",
577 "db_tablespace": "_db_tablespace",
578 }
579 equals_comparison = {"choices", "validators"}
580 for name, default in possibles.items():
581 value = getattr(self, attr_overrides.get(name, name))
582 # Unroll anything iterable for choices into a concrete list
583 if name == "choices" and isinstance(value, collections.abc.Iterable):
584 value = list(value)
585 # Do correct kind of comparison
586 if name in equals_comparison:
587 if value != default:
588 keywords[name] = value
589 else:
590 if value is not default:
591 keywords[name] = value
592 # Work out path - we shorten it for known Django core fields
593 path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__)
594 if path.startswith("django.db.models.fields.related"):
595 path = path.replace("django.db.models.fields.related", "django.db.models")
596 elif path.startswith("django.db.models.fields.files"):
597 path = path.replace("django.db.models.fields.files", "django.db.models")
598 elif path.startswith("django.db.models.fields.json"):
599 path = path.replace("django.db.models.fields.json", "django.db.models")
600 elif path.startswith("django.db.models.fields.proxy"):
601 path = path.replace("django.db.models.fields.proxy", "django.db.models")
602 elif path.startswith("django.db.models.fields"):
603 path = path.replace("django.db.models.fields", "django.db.models")
604 # Return basic info - other fields should override this.
605 return (self.name, path, [], keywords)
607 def clone(self):
608 """
609 Uses deconstruct() to clone a new copy of this Field.
610 Will not preserve any class attachments/attribute names.
611 """
612 name, path, args, kwargs = self.deconstruct()
613 return self.__class__(*args, **kwargs)
615 def __eq__(self, other):
616 # Needed for @total_ordering
617 if isinstance(other, Field):
618 return self.creation_counter == other.creation_counter and getattr(
619 self, "model", None
620 ) == getattr(other, "model", None)
621 return NotImplemented
623 def __lt__(self, other):
624 # This is needed because bisect does not take a comparison function.
625 # Order by creation_counter first for backward compatibility.
626 if isinstance(other, Field):
627 if (
628 self.creation_counter != other.creation_counter
629 or not hasattr(self, "model")
630 and not hasattr(other, "model")
631 ):
632 return self.creation_counter < other.creation_counter
633 elif hasattr(self, "model") != hasattr(other, "model"):
634 return not hasattr(self, "model") # Order no-model fields first
635 else:
636 # creation_counter's are equal, compare only models.
637 return (self.model._meta.app_label, self.model._meta.model_name) < (
638 other.model._meta.app_label,
639 other.model._meta.model_name,
640 )
641 return NotImplemented
643 def __hash__(self):
644 return hash(self.creation_counter)
646 def __deepcopy__(self, memodict):
647 # We don't have to deepcopy very much here, since most things are not
648 # intended to be altered after initial creation.
649 obj = copy.copy(self)
650 if self.remote_field:
651 obj.remote_field = copy.copy(self.remote_field)
652 if hasattr(self.remote_field, "field") and self.remote_field.field is self:
653 obj.remote_field.field = obj
654 memodict[id(self)] = obj
655 return obj
657 def __copy__(self):
658 # We need to avoid hitting __reduce__, so define this
659 # slightly weird copy construct.
660 obj = Empty()
661 obj.__class__ = self.__class__
662 obj.__dict__ = self.__dict__.copy()
663 return obj
665 def __reduce__(self):
666 """
667 Pickling should return the model._meta.fields instance of the field,
668 not a new copy of that field. So, use the app registry to load the
669 model and then the field back.
670 """
671 if not hasattr(self, "model"):
672 # Fields are sometimes used without attaching them to models (for
673 # example in aggregation). In this case give back a plain field
674 # instance. The code below will create a new empty instance of
675 # class self.__class__, then update its dict with self.__dict__
676 # values - so, this is very close to normal pickle.
677 state = self.__dict__.copy()
678 # The _get_default cached_property can't be pickled due to lambda
679 # usage.
680 state.pop("_get_default", None)
681 return _empty, (self.__class__,), state
682 return _load_field, (
683 self.model._meta.app_label,
684 self.model._meta.object_name,
685 self.name,
686 )
688 def get_pk_value_on_save(self, instance):
689 """
690 Hook to generate new PK values on save. This method is called when
691 saving instances with no primary key value set. If this method returns
692 something else than None, then the returned value is used when saving
693 the new instance.
694 """
695 if self.default:
696 return self.get_default()
697 return None
699 def to_python(self, value):
700 """
701 Convert the input value into the expected Python data type, raising
702 django.core.exceptions.ValidationError if the data can't be converted.
703 Return the converted value. Subclasses should override this.
704 """
705 return value
707 @cached_property
708 def error_messages(self):
709 messages = {}
710 for c in reversed(self.__class__.__mro__):
711 messages.update(getattr(c, "default_error_messages", {}))
712 messages.update(self._error_messages or {})
713 return messages
715 @cached_property
716 def validators(self):
717 """
718 Some validators can't be created at field initialization time.
719 This method provides a way to delay their creation until required.
720 """
721 return [*self.default_validators, *self._validators]
723 def run_validators(self, value):
724 if value in self.empty_values:
725 return
727 errors = []
728 for v in self.validators:
729 try:
730 v(value)
731 except exceptions.ValidationError as e:
732 if hasattr(e, "code") and e.code in self.error_messages:
733 e.message = self.error_messages[e.code]
734 errors.extend(e.error_list)
736 if errors:
737 raise exceptions.ValidationError(errors)
739 def validate(self, value, model_instance):
740 """
741 Validate value and raise ValidationError if necessary. Subclasses
742 should override this to provide validation logic.
743 """
744 if not self.editable:
745 # Skip validation for non-editable fields.
746 return
748 if self.choices is not None and value not in self.empty_values:
749 for option_key, option_value in self.choices:
750 if isinstance(option_value, (list, tuple)):
751 # This is an optgroup, so look inside the group for
752 # options.
753 for optgroup_key, optgroup_value in option_value:
754 if value == optgroup_key:
755 return
756 elif value == option_key:
757 return
758 raise exceptions.ValidationError(
759 self.error_messages["invalid_choice"],
760 code="invalid_choice",
761 params={"value": value},
762 )
764 if value is None and not self.null:
765 raise exceptions.ValidationError(self.error_messages["null"], code="null")
767 if not self.blank and value in self.empty_values:
768 raise exceptions.ValidationError(self.error_messages["blank"], code="blank")
770 def clean(self, value, model_instance):
771 """
772 Convert the value's type and run validation. Validation errors
773 from to_python() and validate() are propagated. Return the correct
774 value if no error is raised.
775 """
776 value = self.to_python(value)
777 self.validate(value, model_instance)
778 self.run_validators(value)
779 return value
781 def db_type_parameters(self, connection):
782 return DictWrapper(self.__dict__, connection.ops.quote_name, "qn_")
784 def db_check(self, connection):
785 """
786 Return the database column check constraint for this field, for the
787 provided connection. Works the same way as db_type() for the case that
788 get_internal_type() does not map to a preexisting model field.
789 """
790 data = self.db_type_parameters(connection)
791 try:
792 return (
793 connection.data_type_check_constraints[self.get_internal_type()] % data
794 )
795 except KeyError:
796 return None
798 def db_type(self, connection):
799 """
800 Return the database column data type for this field, for the provided
801 connection.
802 """
803 # The default implementation of this method looks at the
804 # backend-specific data_types dictionary, looking up the field by its
805 # "internal type".
806 #
807 # A Field class can implement the get_internal_type() method to specify
808 # which *preexisting* Django Field class it's most similar to -- i.e.,
809 # a custom field might be represented by a TEXT column type, which is
810 # the same as the TextField Django field type, which means the custom
811 # field's get_internal_type() returns 'TextField'.
812 #
813 # But the limitation of the get_internal_type() / data_types approach
814 # is that it cannot handle database column types that aren't already
815 # mapped to one of the built-in Django field types. In this case, you
816 # can implement db_type() instead of get_internal_type() to specify
817 # exactly which wacky database column type you want to use.
818 data = self.db_type_parameters(connection)
819 try:
820 column_type = connection.data_types[self.get_internal_type()]
821 except KeyError:
822 return None
823 else:
824 # column_type is either a single-parameter function or a string.
825 if callable(column_type):
826 return column_type(data)
827 return column_type % data
829 def rel_db_type(self, connection):
830 """
831 Return the data type that a related field pointing to this field should
832 use. For example, this method is called by ForeignKey and OneToOneField
833 to determine its data type.
834 """
835 return self.db_type(connection)
837 def cast_db_type(self, connection):
838 """Return the data type to use in the Cast() function."""
839 db_type = connection.ops.cast_data_types.get(self.get_internal_type())
840 if db_type:
841 return db_type % self.db_type_parameters(connection)
842 return self.db_type(connection)
844 def db_parameters(self, connection):
845 """
846 Extension of db_type(), providing a range of different return values
847 (type, checks). This will look at db_type(), allowing custom model
848 fields to override it.
849 """
850 type_string = self.db_type(connection)
851 check_string = self.db_check(connection)
852 return {
853 "type": type_string,
854 "check": check_string,
855 }
857 def db_type_suffix(self, connection):
858 return connection.data_types_suffix.get(self.get_internal_type())
860 def get_db_converters(self, connection):
861 if hasattr(self, "from_db_value"):
862 return [self.from_db_value]
863 return []
865 @property
866 def unique(self):
867 return self._unique or self.primary_key
869 @property
870 def db_tablespace(self):
871 return self._db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
873 @property
874 def db_returning(self):
875 """
876 Private API intended only to be used by Django itself. Currently only
877 the PostgreSQL backend supports returning multiple fields on a model.
878 """
879 return False
881 def set_attributes_from_name(self, name):
882 self.name = self.name or name
883 self.attname, self.column = self.get_attname_column()
884 self.concrete = self.column is not None
885 if self.verbose_name is None and self.name:
886 self.verbose_name = self.name.replace("_", " ")
888 def contribute_to_class(self, cls, name, private_only=False):
889 """
890 Register the field with the model class it belongs to.
892 If private_only is True, create a separate instance of this field
893 for every subclass of cls, even if cls is not an abstract model.
894 """
895 self.set_attributes_from_name(name)
896 self.model = cls
897 cls._meta.add_field(self, private=private_only)
898 if self.column:
899 setattr(cls, self.attname, self.descriptor_class(self))
900 if self.choices is not None:
901 # Don't override a get_FOO_display() method defined explicitly on
902 # this class, but don't check methods derived from inheritance, to
903 # allow overriding inherited choices. For more complex inheritance
904 # structures users should override contribute_to_class().
905 if "get_%s_display" % self.name not in cls.__dict__:
906 setattr(
907 cls,
908 "get_%s_display" % self.name,
909 partialmethod(cls._get_FIELD_display, field=self),
910 )
912 def get_filter_kwargs_for_object(self, obj):
913 """
914 Return a dict that when passed as kwargs to self.model.filter(), would
915 yield all instances having the same value for this field as obj has.
916 """
917 return {self.name: getattr(obj, self.attname)}
919 def get_attname(self):
920 return self.name
922 def get_attname_column(self):
923 attname = self.get_attname()
924 column = self.db_column or attname
925 return attname, column
927 def get_internal_type(self):
928 return self.__class__.__name__
930 def pre_save(self, model_instance, add):
931 """Return field's value just before saving."""
932 return getattr(model_instance, self.attname)
934 def get_prep_value(self, value):
935 """Perform preliminary non-db specific value checks and conversions."""
936 if isinstance(value, Promise):
937 value = value._proxy____cast()
938 return value
940 def get_db_prep_value(self, value, connection, prepared=False):
941 """
942 Return field's value prepared for interacting with the database backend.
944 Used by the default implementations of get_db_prep_save().
945 """
946 if not prepared:
947 value = self.get_prep_value(value)
948 return value
950 def get_db_prep_save(self, value, connection):
951 """Return field's value prepared for saving into a database."""
952 if hasattr(value, "as_sql"):
953 return value
954 return self.get_db_prep_value(value, connection=connection, prepared=False)
956 def has_default(self):
957 """Return a boolean of whether this field has a default value."""
958 return self.default is not NOT_PROVIDED
960 def get_default(self):
961 """Return the default value for this field."""
962 return self._get_default()
964 @cached_property
965 def _get_default(self):
966 if self.has_default():
967 if callable(self.default):
968 return self.default
969 return lambda: self.default
971 if (
972 not self.empty_strings_allowed
973 or self.null
974 and not connection.features.interprets_empty_strings_as_nulls
975 ):
976 return return_None
977 return str # return empty string
979 def get_choices(
980 self,
981 include_blank=True,
982 blank_choice=BLANK_CHOICE_DASH,
983 limit_choices_to=None,
984 ordering=(),
985 ):
986 """
987 Return choices with a default blank choices included, for use
988 as <select> choices for this field.
989 """
990 if self.choices is not None:
991 choices = list(self.choices)
992 if include_blank:
993 blank_defined = any(
994 choice in ("", None) for choice, _ in self.flatchoices
995 )
996 if not blank_defined:
997 choices = blank_choice + choices
998 return choices
999 rel_model = self.remote_field.model
1000 limit_choices_to = limit_choices_to or self.get_limit_choices_to()
1001 choice_func = operator.attrgetter(
1002 self.remote_field.get_related_field().attname
1003 if hasattr(self.remote_field, "get_related_field")
1004 else "pk"
1005 )
1006 qs = rel_model._default_manager.complex_filter(limit_choices_to)
1007 if ordering:
1008 qs = qs.order_by(*ordering)
1009 return (blank_choice if include_blank else []) + [
1010 (choice_func(x), str(x)) for x in qs
1011 ]
1013 def value_to_string(self, obj):
1014 """
1015 Return a string value of this field from the passed obj.
1016 This is used by the serialization framework.
1017 """
1018 return str(self.value_from_object(obj))
1020 def _get_flatchoices(self):
1021 """Flattened version of choices tuple."""
1022 if self.choices is None:
1023 return []
1024 flat = []
1025 for choice, value in self.choices:
1026 if isinstance(value, (list, tuple)):
1027 flat.extend(value)
1028 else:
1029 flat.append((choice, value))
1030 return flat
1032 flatchoices = property(_get_flatchoices)
1034 def save_form_data(self, instance, data):
1035 setattr(instance, self.name, data)
1037 def formfield(self, form_class=None, choices_form_class=None, **kwargs):
1038 """Return a django.forms.Field instance for this field."""
1039 defaults = {
1040 "required": not self.blank,
1041 "label": capfirst(self.verbose_name),
1042 "help_text": self.help_text,
1043 }
1044 if self.has_default():
1045 if callable(self.default):
1046 defaults["initial"] = self.default
1047 defaults["show_hidden_initial"] = True
1048 else:
1049 defaults["initial"] = self.get_default()
1050 if self.choices is not None:
1051 # Fields with choices get special treatment.
1052 include_blank = self.blank or not (
1053 self.has_default() or "initial" in kwargs
1054 )
1055 defaults["choices"] = self.get_choices(include_blank=include_blank)
1056 defaults["coerce"] = self.to_python
1057 if self.null:
1058 defaults["empty_value"] = None
1059 if choices_form_class is not None:
1060 form_class = choices_form_class
1061 else:
1062 form_class = forms.TypedChoiceField
1063 # Many of the subclass-specific formfield arguments (min_value,
1064 # max_value) don't apply for choice fields, so be sure to only pass
1065 # the values that TypedChoiceField will understand.
1066 for k in list(kwargs):
1067 if k not in (
1068 "coerce",
1069 "empty_value",
1070 "choices",
1071 "required",
1072 "widget",
1073 "label",
1074 "initial",
1075 "help_text",
1076 "error_messages",
1077 "show_hidden_initial",
1078 "disabled",
1079 ):
1080 del kwargs[k]
1081 defaults.update(kwargs)
1082 if form_class is None:
1083 form_class = forms.CharField
1084 return form_class(**defaults)
1086 def value_from_object(self, obj):
1087 """Return the value of this field in the given model instance."""
1088 return getattr(obj, self.attname)
1091class BooleanField(Field):
1092 empty_strings_allowed = False
1093 default_error_messages = {
1094 "invalid": _("“%(value)s” value must be either True or False."),
1095 "invalid_nullable": _("“%(value)s” value must be either True, False, or None."),
1096 }
1097 description = _("Boolean (Either True or False)")
1099 def get_internal_type(self):
1100 return "BooleanField"
1102 def to_python(self, value):
1103 if self.null and value in self.empty_values:
1104 return None
1105 if value in (True, False):
1106 # 1/0 are equal to True/False. bool() converts former to latter.
1107 return bool(value)
1108 if value in ("t", "True", "1"):
1109 return True
1110 if value in ("f", "False", "0"):
1111 return False
1112 raise exceptions.ValidationError(
1113 self.error_messages["invalid_nullable" if self.null else "invalid"],
1114 code="invalid",
1115 params={"value": value},
1116 )
1118 def get_prep_value(self, value):
1119 value = super().get_prep_value(value)
1120 if value is None:
1121 return None
1122 return self.to_python(value)
1124 def formfield(self, **kwargs):
1125 if self.choices is not None:
1126 include_blank = not (self.has_default() or "initial" in kwargs)
1127 defaults = {"choices": self.get_choices(include_blank=include_blank)}
1128 else:
1129 form_class = forms.NullBooleanField if self.null else forms.BooleanField
1130 # In HTML checkboxes, 'required' means "must be checked" which is
1131 # different from the choices case ("must select some value").
1132 # required=False allows unchecked checkboxes.
1133 defaults = {"form_class": form_class, "required": False}
1134 return super().formfield(**{**defaults, **kwargs})
1137class CharField(Field):
1138 def __init__(self, *args, db_collation=None, **kwargs):
1139 super().__init__(*args, **kwargs)
1140 self.db_collation = db_collation
1141 if self.max_length is not None:
1142 self.validators.append(validators.MaxLengthValidator(self.max_length))
1144 @property
1145 def description(self):
1146 if self.max_length is not None:
1147 return _("String (up to %(max_length)s)")
1148 else:
1149 return _("String (unlimited)")
1151 def check(self, **kwargs):
1152 databases = kwargs.get("databases") or []
1153 return [
1154 *super().check(**kwargs),
1155 *self._check_db_collation(databases),
1156 *self._check_max_length_attribute(**kwargs),
1157 ]
1159 def _check_max_length_attribute(self, **kwargs):
1160 if self.max_length is None:
1161 if (
1162 connection.features.supports_unlimited_charfield
1163 or "supports_unlimited_charfield"
1164 in self.model._meta.required_db_features
1165 ):
1166 return []
1167 return [
1168 checks.Error(
1169 "CharFields must define a 'max_length' attribute.",
1170 obj=self,
1171 id="fields.E120",
1172 )
1173 ]
1174 elif (
1175 not isinstance(self.max_length, int)
1176 or isinstance(self.max_length, bool)
1177 or self.max_length <= 0
1178 ):
1179 return [
1180 checks.Error(
1181 "'max_length' must be a positive integer.",
1182 obj=self,
1183 id="fields.E121",
1184 )
1185 ]
1186 else:
1187 return []
1189 def _check_db_collation(self, databases):
1190 errors = []
1191 for db in databases:
1192 if not router.allow_migrate_model(db, self.model):
1193 continue
1194 connection = connections[db]
1195 if not (
1196 self.db_collation is None
1197 or "supports_collation_on_charfield"
1198 in self.model._meta.required_db_features
1199 or connection.features.supports_collation_on_charfield
1200 ):
1201 errors.append(
1202 checks.Error(
1203 "%s does not support a database collation on "
1204 "CharFields." % connection.display_name,
1205 obj=self,
1206 id="fields.E190",
1207 ),
1208 )
1209 return errors
1211 def cast_db_type(self, connection):
1212 if self.max_length is None:
1213 return connection.ops.cast_char_field_without_max_length
1214 return super().cast_db_type(connection)
1216 def db_parameters(self, connection):
1217 db_params = super().db_parameters(connection)
1218 db_params["collation"] = self.db_collation
1219 return db_params
1221 def get_internal_type(self):
1222 return "CharField"
1224 def to_python(self, value):
1225 if isinstance(value, str) or value is None:
1226 return value
1227 return str(value)
1229 def get_prep_value(self, value):
1230 value = super().get_prep_value(value)
1231 return self.to_python(value)
1233 def formfield(self, **kwargs):
1234 # Passing max_length to forms.CharField means that the value's length
1235 # will be validated twice. This is considered acceptable since we want
1236 # the value in the form field (to pass into widget for example).
1237 defaults = {"max_length": self.max_length}
1238 # TODO: Handle multiple backends with different feature flags.
1239 if self.null and not connection.features.interprets_empty_strings_as_nulls:
1240 defaults["empty_value"] = None
1241 defaults.update(kwargs)
1242 return super().formfield(**defaults)
1244 def deconstruct(self):
1245 name, path, args, kwargs = super().deconstruct()
1246 if self.db_collation:
1247 kwargs["db_collation"] = self.db_collation
1248 return name, path, args, kwargs
1251class CommaSeparatedIntegerField(CharField):
1252 default_validators = [validators.validate_comma_separated_integer_list]
1253 description = _("Comma-separated integers")
1254 system_check_removed_details = {
1255 "msg": (
1256 "CommaSeparatedIntegerField is removed except for support in "
1257 "historical migrations."
1258 ),
1259 "hint": (
1260 "Use CharField(validators=[validate_comma_separated_integer_list]) "
1261 "instead."
1262 ),
1263 "id": "fields.E901",
1264 }
1267def _to_naive(value):
1268 if timezone.is_aware(value):
1269 value = timezone.make_naive(value, datetime.timezone.utc)
1270 return value
1273def _get_naive_now():
1274 return _to_naive(timezone.now())
1277class DateTimeCheckMixin:
1278 def check(self, **kwargs):
1279 return [
1280 *super().check(**kwargs),
1281 *self._check_mutually_exclusive_options(),
1282 *self._check_fix_default_value(),
1283 ]
1285 def _check_mutually_exclusive_options(self):
1286 # auto_now, auto_now_add, and default are mutually exclusive
1287 # options. The use of more than one of these options together
1288 # will trigger an Error
1289 mutually_exclusive_options = [
1290 self.auto_now_add,
1291 self.auto_now,
1292 self.has_default(),
1293 ]
1294 enabled_options = [
1295 option not in (None, False) for option in mutually_exclusive_options
1296 ].count(True)
1297 if enabled_options > 1:
1298 return [
1299 checks.Error(
1300 "The options auto_now, auto_now_add, and default "
1301 "are mutually exclusive. Only one of these options "
1302 "may be present.",
1303 obj=self,
1304 id="fields.E160",
1305 )
1306 ]
1307 else:
1308 return []
1310 def _check_fix_default_value(self):
1311 return []
1313 # Concrete subclasses use this in their implementations of
1314 # _check_fix_default_value().
1315 def _check_if_value_fixed(self, value, now=None):
1316 """
1317 Check if the given value appears to have been provided as a "fixed"
1318 time value, and include a warning in the returned list if it does. The
1319 value argument must be a date object or aware/naive datetime object. If
1320 now is provided, it must be a naive datetime object.
1321 """
1322 if now is None:
1323 now = _get_naive_now()
1324 offset = datetime.timedelta(seconds=10)
1325 lower = now - offset
1326 upper = now + offset
1327 if isinstance(value, datetime.datetime):
1328 value = _to_naive(value)
1329 else:
1330 assert isinstance(value, datetime.date)
1331 lower = lower.date()
1332 upper = upper.date()
1333 if lower <= value <= upper:
1334 return [
1335 checks.Warning(
1336 "Fixed default value provided.",
1337 hint=(
1338 "It seems you set a fixed date / time / datetime "
1339 "value as default for this field. This may not be "
1340 "what you want. If you want to have the current date "
1341 "as default, use `django.utils.timezone.now`"
1342 ),
1343 obj=self,
1344 id="fields.W161",
1345 )
1346 ]
1347 return []
1350class DateField(DateTimeCheckMixin, Field):
1351 empty_strings_allowed = False
1352 default_error_messages = {
1353 "invalid": _(
1354 "“%(value)s” value has an invalid date format. It must be "
1355 "in YYYY-MM-DD format."
1356 ),
1357 "invalid_date": _(
1358 "“%(value)s” value has the correct format (YYYY-MM-DD) "
1359 "but it is an invalid date."
1360 ),
1361 }
1362 description = _("Date (without time)")
1364 def __init__(
1365 self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs
1366 ):
1367 self.auto_now, self.auto_now_add = auto_now, auto_now_add
1368 if auto_now or auto_now_add:
1369 kwargs["editable"] = False
1370 kwargs["blank"] = True
1371 super().__init__(verbose_name, name, **kwargs)
1373 def _check_fix_default_value(self):
1374 """
1375 Warn that using an actual date or datetime value is probably wrong;
1376 it's only evaluated on server startup.
1377 """
1378 if not self.has_default():
1379 return []
1381 value = self.default
1382 if isinstance(value, datetime.datetime):
1383 value = _to_naive(value).date()
1384 elif isinstance(value, datetime.date):
1385 pass
1386 else:
1387 # No explicit date / datetime value -- no checks necessary
1388 return []
1389 # At this point, value is a date object.
1390 return self._check_if_value_fixed(value)
1392 def deconstruct(self):
1393 name, path, args, kwargs = super().deconstruct()
1394 if self.auto_now:
1395 kwargs["auto_now"] = True
1396 if self.auto_now_add:
1397 kwargs["auto_now_add"] = True
1398 if self.auto_now or self.auto_now_add:
1399 del kwargs["editable"]
1400 del kwargs["blank"]
1401 return name, path, args, kwargs
1403 def get_internal_type(self):
1404 return "DateField"
1406 def to_python(self, value):
1407 if value is None:
1408 return value
1409 if isinstance(value, datetime.datetime):
1410 if settings.USE_TZ and timezone.is_aware(value):
1411 # Convert aware datetimes to the default time zone
1412 # before casting them to dates (#17742).
1413 default_timezone = timezone.get_default_timezone()
1414 value = timezone.make_naive(value, default_timezone)
1415 return value.date()
1416 if isinstance(value, datetime.date):
1417 return value
1419 try:
1420 parsed = parse_date(value)
1421 if parsed is not None:
1422 return parsed
1423 except ValueError:
1424 raise exceptions.ValidationError(
1425 self.error_messages["invalid_date"],
1426 code="invalid_date",
1427 params={"value": value},
1428 )
1430 raise exceptions.ValidationError(
1431 self.error_messages["invalid"],
1432 code="invalid",
1433 params={"value": value},
1434 )
1436 def pre_save(self, model_instance, add):
1437 if self.auto_now or (self.auto_now_add and add):
1438 value = datetime.date.today()
1439 setattr(model_instance, self.attname, value)
1440 return value
1441 else:
1442 return super().pre_save(model_instance, add)
1444 def contribute_to_class(self, cls, name, **kwargs):
1445 super().contribute_to_class(cls, name, **kwargs)
1446 if not self.null:
1447 setattr(
1448 cls,
1449 "get_next_by_%s" % self.name,
1450 partialmethod(
1451 cls._get_next_or_previous_by_FIELD, field=self, is_next=True
1452 ),
1453 )
1454 setattr(
1455 cls,
1456 "get_previous_by_%s" % self.name,
1457 partialmethod(
1458 cls._get_next_or_previous_by_FIELD, field=self, is_next=False
1459 ),
1460 )
1462 def get_prep_value(self, value):
1463 value = super().get_prep_value(value)
1464 return self.to_python(value)
1466 def get_db_prep_value(self, value, connection, prepared=False):
1467 # Casts dates into the format expected by the backend
1468 if not prepared:
1469 value = self.get_prep_value(value)
1470 return connection.ops.adapt_datefield_value(value)
1472 def value_to_string(self, obj):
1473 val = self.value_from_object(obj)
1474 return "" if val is None else val.isoformat()
1476 def formfield(self, **kwargs):
1477 return super().formfield(
1478 **{
1479 "form_class": forms.DateField,
1480 **kwargs,
1481 }
1482 )
1485class DateTimeField(DateField):
1486 empty_strings_allowed = False
1487 default_error_messages = {
1488 "invalid": _(
1489 "“%(value)s” value has an invalid format. It must be in "
1490 "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."
1491 ),
1492 "invalid_date": _(
1493 "“%(value)s” value has the correct format "
1494 "(YYYY-MM-DD) but it is an invalid date."
1495 ),
1496 "invalid_datetime": _(
1497 "“%(value)s” value has the correct format "
1498 "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
1499 "but it is an invalid date/time."
1500 ),
1501 }
1502 description = _("Date (with time)")
1504 # __init__ is inherited from DateField
1506 def _check_fix_default_value(self):
1507 """
1508 Warn that using an actual date or datetime value is probably wrong;
1509 it's only evaluated on server startup.
1510 """
1511 if not self.has_default():
1512 return []
1514 value = self.default
1515 if isinstance(value, (datetime.datetime, datetime.date)):
1516 return self._check_if_value_fixed(value)
1517 # No explicit date / datetime value -- no checks necessary.
1518 return []
1520 def get_internal_type(self):
1521 return "DateTimeField"
1523 def to_python(self, value):
1524 if value is None:
1525 return value
1526 if isinstance(value, datetime.datetime):
1527 return value
1528 if isinstance(value, datetime.date):
1529 value = datetime.datetime(value.year, value.month, value.day)
1530 if settings.USE_TZ:
1531 # For backwards compatibility, interpret naive datetimes in
1532 # local time. This won't work during DST change, but we can't
1533 # do much about it, so we let the exceptions percolate up the
1534 # call stack.
1535 warnings.warn(
1536 "DateTimeField %s.%s received a naive datetime "
1537 "(%s) while time zone support is active."
1538 % (self.model.__name__, self.name, value),
1539 RuntimeWarning,
1540 )
1541 default_timezone = timezone.get_default_timezone()
1542 value = timezone.make_aware(value, default_timezone)
1543 return value
1545 try:
1546 parsed = parse_datetime(value)
1547 if parsed is not None:
1548 return parsed
1549 except ValueError:
1550 raise exceptions.ValidationError(
1551 self.error_messages["invalid_datetime"],
1552 code="invalid_datetime",
1553 params={"value": value},
1554 )
1556 try:
1557 parsed = parse_date(value)
1558 if parsed is not None:
1559 return datetime.datetime(parsed.year, parsed.month, parsed.day)
1560 except ValueError:
1561 raise exceptions.ValidationError(
1562 self.error_messages["invalid_date"],
1563 code="invalid_date",
1564 params={"value": value},
1565 )
1567 raise exceptions.ValidationError(
1568 self.error_messages["invalid"],
1569 code="invalid",
1570 params={"value": value},
1571 )
1573 def pre_save(self, model_instance, add):
1574 if self.auto_now or (self.auto_now_add and add):
1575 value = timezone.now()
1576 setattr(model_instance, self.attname, value)
1577 return value
1578 else:
1579 return super().pre_save(model_instance, add)
1581 # contribute_to_class is inherited from DateField, it registers
1582 # get_next_by_FOO and get_prev_by_FOO
1584 def get_prep_value(self, value):
1585 value = super().get_prep_value(value)
1586 value = self.to_python(value)
1587 if value is not None and settings.USE_TZ and timezone.is_naive(value):
1588 # For backwards compatibility, interpret naive datetimes in local
1589 # time. This won't work during DST change, but we can't do much
1590 # about it, so we let the exceptions percolate up the call stack.
1591 try:
1592 name = "%s.%s" % (self.model.__name__, self.name)
1593 except AttributeError:
1594 name = "(unbound)"
1595 warnings.warn(
1596 "DateTimeField %s received a naive datetime (%s)"
1597 " while time zone support is active." % (name, value),
1598 RuntimeWarning,
1599 )
1600 default_timezone = timezone.get_default_timezone()
1601 value = timezone.make_aware(value, default_timezone)
1602 return value
1604 def get_db_prep_value(self, value, connection, prepared=False):
1605 # Casts datetimes into the format expected by the backend
1606 if not prepared:
1607 value = self.get_prep_value(value)
1608 return connection.ops.adapt_datetimefield_value(value)
1610 def value_to_string(self, obj):
1611 val = self.value_from_object(obj)
1612 return "" if val is None else val.isoformat()
1614 def formfield(self, **kwargs):
1615 return super().formfield(
1616 **{
1617 "form_class": forms.DateTimeField,
1618 **kwargs,
1619 }
1620 )
1623class DecimalField(Field):
1624 empty_strings_allowed = False
1625 default_error_messages = {
1626 "invalid": _("“%(value)s” value must be a decimal number."),
1627 }
1628 description = _("Decimal number")
1630 def __init__(
1631 self,
1632 verbose_name=None,
1633 name=None,
1634 max_digits=None,
1635 decimal_places=None,
1636 **kwargs,
1637 ):
1638 self.max_digits, self.decimal_places = max_digits, decimal_places
1639 super().__init__(verbose_name, name, **kwargs)
1641 def check(self, **kwargs):
1642 errors = super().check(**kwargs)
1644 digits_errors = [
1645 *self._check_decimal_places(),
1646 *self._check_max_digits(),
1647 ]
1648 if not digits_errors:
1649 errors.extend(self._check_decimal_places_and_max_digits(**kwargs))
1650 else:
1651 errors.extend(digits_errors)
1652 return errors
1654 def _check_decimal_places(self):
1655 try:
1656 decimal_places = int(self.decimal_places)
1657 if decimal_places < 0:
1658 raise ValueError()
1659 except TypeError:
1660 return [
1661 checks.Error(
1662 "DecimalFields must define a 'decimal_places' attribute.",
1663 obj=self,
1664 id="fields.E130",
1665 )
1666 ]
1667 except ValueError:
1668 return [
1669 checks.Error(
1670 "'decimal_places' must be a non-negative integer.",
1671 obj=self,
1672 id="fields.E131",
1673 )
1674 ]
1675 else:
1676 return []
1678 def _check_max_digits(self):
1679 try:
1680 max_digits = int(self.max_digits)
1681 if max_digits <= 0:
1682 raise ValueError()
1683 except TypeError:
1684 return [
1685 checks.Error(
1686 "DecimalFields must define a 'max_digits' attribute.",
1687 obj=self,
1688 id="fields.E132",
1689 )
1690 ]
1691 except ValueError:
1692 return [
1693 checks.Error(
1694 "'max_digits' must be a positive integer.",
1695 obj=self,
1696 id="fields.E133",
1697 )
1698 ]
1699 else:
1700 return []
1702 def _check_decimal_places_and_max_digits(self, **kwargs):
1703 if int(self.decimal_places) > int(self.max_digits):
1704 return [
1705 checks.Error(
1706 "'max_digits' must be greater or equal to 'decimal_places'.",
1707 obj=self,
1708 id="fields.E134",
1709 )
1710 ]
1711 return []
1713 @cached_property
1714 def validators(self):
1715 return super().validators + [
1716 validators.DecimalValidator(self.max_digits, self.decimal_places)
1717 ]
1719 @cached_property
1720 def context(self):
1721 return decimal.Context(prec=self.max_digits)
1723 def deconstruct(self):
1724 name, path, args, kwargs = super().deconstruct()
1725 if self.max_digits is not None:
1726 kwargs["max_digits"] = self.max_digits
1727 if self.decimal_places is not None:
1728 kwargs["decimal_places"] = self.decimal_places
1729 return name, path, args, kwargs
1731 def get_internal_type(self):
1732 return "DecimalField"
1734 def to_python(self, value):
1735 if value is None:
1736 return value
1737 try:
1738 if isinstance(value, float):
1739 decimal_value = self.context.create_decimal_from_float(value)
1740 else:
1741 decimal_value = decimal.Decimal(value)
1742 except (decimal.InvalidOperation, TypeError, ValueError):
1743 raise exceptions.ValidationError(
1744 self.error_messages["invalid"],
1745 code="invalid",
1746 params={"value": value},
1747 )
1748 if not decimal_value.is_finite():
1749 raise exceptions.ValidationError(
1750 self.error_messages["invalid"],
1751 code="invalid",
1752 params={"value": value},
1753 )
1754 return decimal_value
1756 def get_db_prep_value(self, value, connection, prepared=False):
1757 if not prepared:
1758 value = self.get_prep_value(value)
1759 if hasattr(value, "as_sql"):
1760 return value
1761 return connection.ops.adapt_decimalfield_value(
1762 value, self.max_digits, self.decimal_places
1763 )
1765 def get_prep_value(self, value):
1766 value = super().get_prep_value(value)
1767 return self.to_python(value)
1769 def formfield(self, **kwargs):
1770 return super().formfield(
1771 **{
1772 "max_digits": self.max_digits,
1773 "decimal_places": self.decimal_places,
1774 "form_class": forms.DecimalField,
1775 **kwargs,
1776 }
1777 )
1780class DurationField(Field):
1781 """
1782 Store timedelta objects.
1784 Use interval on PostgreSQL, INTERVAL DAY TO SECOND on Oracle, and bigint
1785 of microseconds on other databases.
1786 """
1788 empty_strings_allowed = False
1789 default_error_messages = {
1790 "invalid": _(
1791 "“%(value)s” value has an invalid format. It must be in "
1792 "[DD] [[HH:]MM:]ss[.uuuuuu] format."
1793 )
1794 }
1795 description = _("Duration")
1797 def get_internal_type(self):
1798 return "DurationField"
1800 def to_python(self, value):
1801 if value is None:
1802 return value
1803 if isinstance(value, datetime.timedelta):
1804 return value
1805 try:
1806 parsed = parse_duration(value)
1807 except ValueError:
1808 pass
1809 else:
1810 if parsed is not None:
1811 return parsed
1813 raise exceptions.ValidationError(
1814 self.error_messages["invalid"],
1815 code="invalid",
1816 params={"value": value},
1817 )
1819 def get_db_prep_value(self, value, connection, prepared=False):
1820 if connection.features.has_native_duration_field:
1821 return value
1822 if value is None:
1823 return None
1824 return duration_microseconds(value)
1826 def get_db_converters(self, connection):
1827 converters = []
1828 if not connection.features.has_native_duration_field:
1829 converters.append(connection.ops.convert_durationfield_value)
1830 return converters + super().get_db_converters(connection)
1832 def value_to_string(self, obj):
1833 val = self.value_from_object(obj)
1834 return "" if val is None else duration_string(val)
1836 def formfield(self, **kwargs):
1837 return super().formfield(
1838 **{
1839 "form_class": forms.DurationField,
1840 **kwargs,
1841 }
1842 )
1845class EmailField(CharField):
1846 default_validators = [validators.validate_email]
1847 description = _("Email address")
1849 def __init__(self, *args, **kwargs):
1850 # max_length=254 to be compliant with RFCs 3696 and 5321
1851 kwargs.setdefault("max_length", 254)
1852 super().__init__(*args, **kwargs)
1854 def deconstruct(self):
1855 name, path, args, kwargs = super().deconstruct()
1856 # We do not exclude max_length if it matches default as we want to change
1857 # the default in future.
1858 return name, path, args, kwargs
1860 def formfield(self, **kwargs):
1861 # As with CharField, this will cause email validation to be performed
1862 # twice.
1863 return super().formfield(
1864 **{
1865 "form_class": forms.EmailField,
1866 **kwargs,
1867 }
1868 )
1871class FilePathField(Field):
1872 description = _("File path")
1874 def __init__(
1875 self,
1876 verbose_name=None,
1877 name=None,
1878 path="",
1879 match=None,
1880 recursive=False,
1881 allow_files=True,
1882 allow_folders=False,
1883 **kwargs,
1884 ):
1885 self.path, self.match, self.recursive = path, match, recursive
1886 self.allow_files, self.allow_folders = allow_files, allow_folders
1887 kwargs.setdefault("max_length", 100)
1888 super().__init__(verbose_name, name, **kwargs)
1890 def check(self, **kwargs):
1891 return [
1892 *super().check(**kwargs),
1893 *self._check_allowing_files_or_folders(**kwargs),
1894 ]
1896 def _check_allowing_files_or_folders(self, **kwargs):
1897 if not self.allow_files and not self.allow_folders:
1898 return [
1899 checks.Error(
1900 "FilePathFields must have either 'allow_files' or 'allow_folders' "
1901 "set to True.",
1902 obj=self,
1903 id="fields.E140",
1904 )
1905 ]
1906 return []
1908 def deconstruct(self):
1909 name, path, args, kwargs = super().deconstruct()
1910 if self.path != "":
1911 kwargs["path"] = self.path
1912 if self.match is not None:
1913 kwargs["match"] = self.match
1914 if self.recursive is not False:
1915 kwargs["recursive"] = self.recursive
1916 if self.allow_files is not True:
1917 kwargs["allow_files"] = self.allow_files
1918 if self.allow_folders is not False:
1919 kwargs["allow_folders"] = self.allow_folders
1920 if kwargs.get("max_length") == 100:
1921 del kwargs["max_length"]
1922 return name, path, args, kwargs
1924 def get_prep_value(self, value):
1925 value = super().get_prep_value(value)
1926 if value is None:
1927 return None
1928 return str(value)
1930 def formfield(self, **kwargs):
1931 return super().formfield(
1932 **{
1933 "path": self.path() if callable(self.path) else self.path,
1934 "match": self.match,
1935 "recursive": self.recursive,
1936 "form_class": forms.FilePathField,
1937 "allow_files": self.allow_files,
1938 "allow_folders": self.allow_folders,
1939 **kwargs,
1940 }
1941 )
1943 def get_internal_type(self):
1944 return "FilePathField"
1947class FloatField(Field):
1948 empty_strings_allowed = False
1949 default_error_messages = {
1950 "invalid": _("“%(value)s” value must be a float."),
1951 }
1952 description = _("Floating point number")
1954 def get_prep_value(self, value):
1955 value = super().get_prep_value(value)
1956 if value is None:
1957 return None
1958 try:
1959 return float(value)
1960 except (TypeError, ValueError) as e:
1961 raise e.__class__(
1962 "Field '%s' expected a number but got %r." % (self.name, value),
1963 ) from e
1965 def get_internal_type(self):
1966 return "FloatField"
1968 def to_python(self, value):
1969 if value is None:
1970 return value
1971 try:
1972 return float(value)
1973 except (TypeError, ValueError):
1974 raise exceptions.ValidationError(
1975 self.error_messages["invalid"],
1976 code="invalid",
1977 params={"value": value},
1978 )
1980 def formfield(self, **kwargs):
1981 return super().formfield(
1982 **{
1983 "form_class": forms.FloatField,
1984 **kwargs,
1985 }
1986 )
1989class IntegerField(Field):
1990 empty_strings_allowed = False
1991 default_error_messages = {
1992 "invalid": _("“%(value)s” value must be an integer."),
1993 }
1994 description = _("Integer")
1996 def check(self, **kwargs):
1997 return [
1998 *super().check(**kwargs),
1999 *self._check_max_length_warning(),
2000 ]
2002 def _check_max_length_warning(self):
2003 if self.max_length is not None:
2004 return [
2005 checks.Warning(
2006 "'max_length' is ignored when used with %s."
2007 % self.__class__.__name__,
2008 hint="Remove 'max_length' from field",
2009 obj=self,
2010 id="fields.W122",
2011 )
2012 ]
2013 return []
2015 @cached_property
2016 def validators(self):
2017 # These validators can't be added at field initialization time since
2018 # they're based on values retrieved from `connection`.
2019 validators_ = super().validators
2020 internal_type = self.get_internal_type()
2021 min_value, max_value = connection.ops.integer_field_range(internal_type)
2022 if min_value is not None and not any(
2023 (
2024 isinstance(validator, validators.MinValueValidator)
2025 and (
2026 validator.limit_value()
2027 if callable(validator.limit_value)
2028 else validator.limit_value
2029 )
2030 >= min_value
2031 )
2032 for validator in validators_
2033 ):
2034 validators_.append(validators.MinValueValidator(min_value))
2035 if max_value is not None and not any(
2036 (
2037 isinstance(validator, validators.MaxValueValidator)
2038 and (
2039 validator.limit_value()
2040 if callable(validator.limit_value)
2041 else validator.limit_value
2042 )
2043 <= max_value
2044 )
2045 for validator in validators_
2046 ):
2047 validators_.append(validators.MaxValueValidator(max_value))
2048 return validators_
2050 def get_prep_value(self, value):
2051 value = super().get_prep_value(value)
2052 if value is None:
2053 return None
2054 try:
2055 return int(value)
2056 except (TypeError, ValueError) as e:
2057 raise e.__class__(
2058 "Field '%s' expected a number but got %r." % (self.name, value),
2059 ) from e
2061 def get_db_prep_value(self, value, connection, prepared=False):
2062 value = super().get_db_prep_value(value, connection, prepared)
2063 return connection.ops.adapt_integerfield_value(value, self.get_internal_type())
2065 def get_internal_type(self):
2066 return "IntegerField"
2068 def to_python(self, value):
2069 if value is None:
2070 return value
2071 try:
2072 return int(value)
2073 except (TypeError, ValueError):
2074 raise exceptions.ValidationError(
2075 self.error_messages["invalid"],
2076 code="invalid",
2077 params={"value": value},
2078 )
2080 def formfield(self, **kwargs):
2081 return super().formfield(
2082 **{
2083 "form_class": forms.IntegerField,
2084 **kwargs,
2085 }
2086 )
2089class BigIntegerField(IntegerField):
2090 description = _("Big (8 byte) integer")
2091 MAX_BIGINT = 9223372036854775807
2093 def get_internal_type(self):
2094 return "BigIntegerField"
2096 def formfield(self, **kwargs):
2097 return super().formfield(
2098 **{
2099 "min_value": -BigIntegerField.MAX_BIGINT - 1,
2100 "max_value": BigIntegerField.MAX_BIGINT,
2101 **kwargs,
2102 }
2103 )
2106class SmallIntegerField(IntegerField):
2107 description = _("Small integer")
2109 def get_internal_type(self):
2110 return "SmallIntegerField"
2113class IPAddressField(Field):
2114 empty_strings_allowed = False
2115 description = _("IPv4 address")
2116 system_check_removed_details = {
2117 "msg": (
2118 "IPAddressField has been removed except for support in "
2119 "historical migrations."
2120 ),
2121 "hint": "Use GenericIPAddressField instead.",
2122 "id": "fields.E900",
2123 }
2125 def __init__(self, *args, **kwargs):
2126 kwargs["max_length"] = 15
2127 super().__init__(*args, **kwargs)
2129 def deconstruct(self):
2130 name, path, args, kwargs = super().deconstruct()
2131 del kwargs["max_length"]
2132 return name, path, args, kwargs
2134 def get_prep_value(self, value):
2135 value = super().get_prep_value(value)
2136 if value is None:
2137 return None
2138 return str(value)
2140 def get_internal_type(self):
2141 return "IPAddressField"
2144class GenericIPAddressField(Field):
2145 empty_strings_allowed = False
2146 description = _("IP address")
2147 default_error_messages = {}
2149 def __init__(
2150 self,
2151 verbose_name=None,
2152 name=None,
2153 protocol="both",
2154 unpack_ipv4=False,
2155 *args,
2156 **kwargs,
2157 ):
2158 self.unpack_ipv4 = unpack_ipv4
2159 self.protocol = protocol
2160 (
2161 self.default_validators,
2162 invalid_error_message,
2163 ) = validators.ip_address_validators(protocol, unpack_ipv4)
2164 self.default_error_messages["invalid"] = invalid_error_message
2165 kwargs["max_length"] = 39
2166 super().__init__(verbose_name, name, *args, **kwargs)
2168 def check(self, **kwargs):
2169 return [
2170 *super().check(**kwargs),
2171 *self._check_blank_and_null_values(**kwargs),
2172 ]
2174 def _check_blank_and_null_values(self, **kwargs):
2175 if not getattr(self, "null", False) and getattr(self, "blank", False):
2176 return [
2177 checks.Error(
2178 "GenericIPAddressFields cannot have blank=True if null=False, "
2179 "as blank values are stored as nulls.",
2180 obj=self,
2181 id="fields.E150",
2182 )
2183 ]
2184 return []
2186 def deconstruct(self):
2187 name, path, args, kwargs = super().deconstruct()
2188 if self.unpack_ipv4 is not False:
2189 kwargs["unpack_ipv4"] = self.unpack_ipv4
2190 if self.protocol != "both":
2191 kwargs["protocol"] = self.protocol
2192 if kwargs.get("max_length") == 39:
2193 del kwargs["max_length"]
2194 return name, path, args, kwargs
2196 def get_internal_type(self):
2197 return "GenericIPAddressField"
2199 def to_python(self, value):
2200 if value is None:
2201 return None
2202 if not isinstance(value, str):
2203 value = str(value)
2204 value = value.strip()
2205 if ":" in value:
2206 return clean_ipv6_address(
2207 value, self.unpack_ipv4, self.error_messages["invalid"]
2208 )
2209 return value
2211 def get_db_prep_value(self, value, connection, prepared=False):
2212 if not prepared:
2213 value = self.get_prep_value(value)
2214 return connection.ops.adapt_ipaddressfield_value(value)
2216 def get_prep_value(self, value):
2217 value = super().get_prep_value(value)
2218 if value is None:
2219 return None
2220 if value and ":" in value:
2221 try:
2222 return clean_ipv6_address(value, self.unpack_ipv4)
2223 except exceptions.ValidationError:
2224 pass
2225 return str(value)
2227 def formfield(self, **kwargs):
2228 return super().formfield(
2229 **{
2230 "protocol": self.protocol,
2231 "form_class": forms.GenericIPAddressField,
2232 **kwargs,
2233 }
2234 )
2237class NullBooleanField(BooleanField):
2238 default_error_messages = {
2239 "invalid": _("“%(value)s” value must be either None, True or False."),
2240 "invalid_nullable": _("“%(value)s” value must be either None, True or False."),
2241 }
2242 description = _("Boolean (Either True, False or None)")
2243 system_check_removed_details = {
2244 "msg": (
2245 "NullBooleanField is removed except for support in historical "
2246 "migrations."
2247 ),
2248 "hint": "Use BooleanField(null=True) instead.",
2249 "id": "fields.E903",
2250 }
2252 def __init__(self, *args, **kwargs):
2253 kwargs["null"] = True
2254 kwargs["blank"] = True
2255 super().__init__(*args, **kwargs)
2257 def deconstruct(self):
2258 name, path, args, kwargs = super().deconstruct()
2259 del kwargs["null"]
2260 del kwargs["blank"]
2261 return name, path, args, kwargs
2264class PositiveIntegerRelDbTypeMixin:
2265 def __init_subclass__(cls, **kwargs):
2266 super().__init_subclass__(**kwargs)
2267 if not hasattr(cls, "integer_field_class"):
2268 cls.integer_field_class = next(
2269 (
2270 parent
2271 for parent in cls.__mro__[1:]
2272 if issubclass(parent, IntegerField)
2273 ),
2274 None,
2275 )
2277 def rel_db_type(self, connection):
2278 """
2279 Return the data type that a related field pointing to this field should
2280 use. In most cases, a foreign key pointing to a positive integer
2281 primary key will have an integer column data type but some databases
2282 (e.g. MySQL) have an unsigned integer type. In that case
2283 (related_fields_match_type=True), the primary key should return its
2284 db_type.
2285 """
2286 if connection.features.related_fields_match_type:
2287 return self.db_type(connection)
2288 else:
2289 return self.integer_field_class().db_type(connection=connection)
2292class PositiveBigIntegerField(PositiveIntegerRelDbTypeMixin, BigIntegerField):
2293 description = _("Positive big integer")
2295 def get_internal_type(self):
2296 return "PositiveBigIntegerField"
2298 def formfield(self, **kwargs):
2299 return super().formfield(
2300 **{
2301 "min_value": 0,
2302 **kwargs,
2303 }
2304 )
2307class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField):
2308 description = _("Positive integer")
2310 def get_internal_type(self):
2311 return "PositiveIntegerField"
2313 def formfield(self, **kwargs):
2314 return super().formfield(
2315 **{
2316 "min_value": 0,
2317 **kwargs,
2318 }
2319 )
2322class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, SmallIntegerField):
2323 description = _("Positive small integer")
2325 def get_internal_type(self):
2326 return "PositiveSmallIntegerField"
2328 def formfield(self, **kwargs):
2329 return super().formfield(
2330 **{
2331 "min_value": 0,
2332 **kwargs,
2333 }
2334 )
2337class SlugField(CharField):
2338 default_validators = [validators.validate_slug]
2339 description = _("Slug (up to %(max_length)s)")
2341 def __init__(
2342 self, *args, max_length=50, db_index=True, allow_unicode=False, **kwargs
2343 ):
2344 self.allow_unicode = allow_unicode
2345 if self.allow_unicode:
2346 self.default_validators = [validators.validate_unicode_slug]
2347 super().__init__(*args, max_length=max_length, db_index=db_index, **kwargs)
2349 def deconstruct(self):
2350 name, path, args, kwargs = super().deconstruct()
2351 if kwargs.get("max_length") == 50:
2352 del kwargs["max_length"]
2353 if self.db_index is False:
2354 kwargs["db_index"] = False
2355 else:
2356 del kwargs["db_index"]
2357 if self.allow_unicode is not False:
2358 kwargs["allow_unicode"] = self.allow_unicode
2359 return name, path, args, kwargs
2361 def get_internal_type(self):
2362 return "SlugField"
2364 def formfield(self, **kwargs):
2365 return super().formfield(
2366 **{
2367 "form_class": forms.SlugField,
2368 "allow_unicode": self.allow_unicode,
2369 **kwargs,
2370 }
2371 )
2374class TextField(Field):
2375 description = _("Text")
2377 def __init__(self, *args, db_collation=None, **kwargs):
2378 super().__init__(*args, **kwargs)
2379 self.db_collation = db_collation
2381 def check(self, **kwargs):
2382 databases = kwargs.get("databases") or []
2383 return [
2384 *super().check(**kwargs),
2385 *self._check_db_collation(databases),
2386 ]
2388 def _check_db_collation(self, databases):
2389 errors = []
2390 for db in databases:
2391 if not router.allow_migrate_model(db, self.model):
2392 continue
2393 connection = connections[db]
2394 if not (
2395 self.db_collation is None
2396 or "supports_collation_on_textfield"
2397 in self.model._meta.required_db_features
2398 or connection.features.supports_collation_on_textfield
2399 ):
2400 errors.append(
2401 checks.Error(
2402 "%s does not support a database collation on "
2403 "TextFields." % connection.display_name,
2404 obj=self,
2405 id="fields.E190",
2406 ),
2407 )
2408 return errors
2410 def db_parameters(self, connection):
2411 db_params = super().db_parameters(connection)
2412 db_params["collation"] = self.db_collation
2413 return db_params
2415 def get_internal_type(self):
2416 return "TextField"
2418 def to_python(self, value):
2419 if isinstance(value, str) or value is None:
2420 return value
2421 return str(value)
2423 def get_prep_value(self, value):
2424 value = super().get_prep_value(value)
2425 return self.to_python(value)
2427 def formfield(self, **kwargs):
2428 # Passing max_length to forms.CharField means that the value's length
2429 # will be validated twice. This is considered acceptable since we want
2430 # the value in the form field (to pass into widget for example).
2431 return super().formfield(
2432 **{
2433 "max_length": self.max_length,
2434 **({} if self.choices is not None else {"widget": forms.Textarea}),
2435 **kwargs,
2436 }
2437 )
2439 def deconstruct(self):
2440 name, path, args, kwargs = super().deconstruct()
2441 if self.db_collation:
2442 kwargs["db_collation"] = self.db_collation
2443 return name, path, args, kwargs
2446class TimeField(DateTimeCheckMixin, Field):
2447 empty_strings_allowed = False
2448 default_error_messages = {
2449 "invalid": _(
2450 "“%(value)s” value has an invalid format. It must be in "
2451 "HH:MM[:ss[.uuuuuu]] format."
2452 ),
2453 "invalid_time": _(
2454 "“%(value)s” value has the correct format "
2455 "(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."
2456 ),
2457 }
2458 description = _("Time")
2460 def __init__(
2461 self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs
2462 ):
2463 self.auto_now, self.auto_now_add = auto_now, auto_now_add
2464 if auto_now or auto_now_add:
2465 kwargs["editable"] = False
2466 kwargs["blank"] = True
2467 super().__init__(verbose_name, name, **kwargs)
2469 def _check_fix_default_value(self):
2470 """
2471 Warn that using an actual date or datetime value is probably wrong;
2472 it's only evaluated on server startup.
2473 """
2474 if not self.has_default():
2475 return []
2477 value = self.default
2478 if isinstance(value, datetime.datetime):
2479 now = None
2480 elif isinstance(value, datetime.time):
2481 now = _get_naive_now()
2482 # This will not use the right date in the race condition where now
2483 # is just before the date change and value is just past 0:00.
2484 value = datetime.datetime.combine(now.date(), value)
2485 else:
2486 # No explicit time / datetime value -- no checks necessary
2487 return []
2488 # At this point, value is a datetime object.
2489 return self._check_if_value_fixed(value, now=now)
2491 def deconstruct(self):
2492 name, path, args, kwargs = super().deconstruct()
2493 if self.auto_now is not False:
2494 kwargs["auto_now"] = self.auto_now
2495 if self.auto_now_add is not False:
2496 kwargs["auto_now_add"] = self.auto_now_add
2497 if self.auto_now or self.auto_now_add:
2498 del kwargs["blank"]
2499 del kwargs["editable"]
2500 return name, path, args, kwargs
2502 def get_internal_type(self):
2503 return "TimeField"
2505 def to_python(self, value):
2506 if value is None:
2507 return None
2508 if isinstance(value, datetime.time):
2509 return value
2510 if isinstance(value, datetime.datetime):
2511 # Not usually a good idea to pass in a datetime here (it loses
2512 # information), but this can be a side-effect of interacting with a
2513 # database backend (e.g. Oracle), so we'll be accommodating.
2514 return value.time()
2516 try:
2517 parsed = parse_time(value)
2518 if parsed is not None:
2519 return parsed
2520 except ValueError:
2521 raise exceptions.ValidationError(
2522 self.error_messages["invalid_time"],
2523 code="invalid_time",
2524 params={"value": value},
2525 )
2527 raise exceptions.ValidationError(
2528 self.error_messages["invalid"],
2529 code="invalid",
2530 params={"value": value},
2531 )
2533 def pre_save(self, model_instance, add):
2534 if self.auto_now or (self.auto_now_add and add):
2535 value = datetime.datetime.now().time()
2536 setattr(model_instance, self.attname, value)
2537 return value
2538 else:
2539 return super().pre_save(model_instance, add)
2541 def get_prep_value(self, value):
2542 value = super().get_prep_value(value)
2543 return self.to_python(value)
2545 def get_db_prep_value(self, value, connection, prepared=False):
2546 # Casts times into the format expected by the backend
2547 if not prepared:
2548 value = self.get_prep_value(value)
2549 return connection.ops.adapt_timefield_value(value)
2551 def value_to_string(self, obj):
2552 val = self.value_from_object(obj)
2553 return "" if val is None else val.isoformat()
2555 def formfield(self, **kwargs):
2556 return super().formfield(
2557 **{
2558 "form_class": forms.TimeField,
2559 **kwargs,
2560 }
2561 )
2564class URLField(CharField):
2565 default_validators = [validators.URLValidator()]
2566 description = _("URL")
2568 def __init__(self, verbose_name=None, name=None, **kwargs):
2569 kwargs.setdefault("max_length", 200)
2570 super().__init__(verbose_name, name, **kwargs)
2572 def deconstruct(self):
2573 name, path, args, kwargs = super().deconstruct()
2574 if kwargs.get("max_length") == 200:
2575 del kwargs["max_length"]
2576 return name, path, args, kwargs
2578 def formfield(self, **kwargs):
2579 # As with CharField, this will cause URL validation to be performed
2580 # twice.
2581 return super().formfield(
2582 **{
2583 "form_class": forms.URLField,
2584 **kwargs,
2585 }
2586 )
2589class BinaryField(Field):
2590 description = _("Raw binary data")
2591 empty_values = [None, b""]
2593 def __init__(self, *args, **kwargs):
2594 kwargs.setdefault("editable", False)
2595 super().__init__(*args, **kwargs)
2596 if self.max_length is not None:
2597 self.validators.append(validators.MaxLengthValidator(self.max_length))
2599 def check(self, **kwargs):
2600 return [*super().check(**kwargs), *self._check_str_default_value()]
2602 def _check_str_default_value(self):
2603 if self.has_default() and isinstance(self.default, str):
2604 return [
2605 checks.Error(
2606 "BinaryField's default cannot be a string. Use bytes "
2607 "content instead.",
2608 obj=self,
2609 id="fields.E170",
2610 )
2611 ]
2612 return []
2614 def deconstruct(self):
2615 name, path, args, kwargs = super().deconstruct()
2616 if self.editable:
2617 kwargs["editable"] = True
2618 else:
2619 del kwargs["editable"]
2620 return name, path, args, kwargs
2622 def get_internal_type(self):
2623 return "BinaryField"
2625 def get_placeholder(self, value, compiler, connection):
2626 return connection.ops.binary_placeholder_sql(value)
2628 def get_default(self):
2629 if self.has_default() and not callable(self.default):
2630 return self.default
2631 default = super().get_default()
2632 if default == "":
2633 return b""
2634 return default
2636 def get_db_prep_value(self, value, connection, prepared=False):
2637 value = super().get_db_prep_value(value, connection, prepared)
2638 if value is not None:
2639 return connection.Database.Binary(value)
2640 return value
2642 def value_to_string(self, obj):
2643 """Binary data is serialized as base64"""
2644 return b64encode(self.value_from_object(obj)).decode("ascii")
2646 def to_python(self, value):
2647 # If it's a string, it should be base64-encoded data
2648 if isinstance(value, str):
2649 return memoryview(b64decode(value.encode("ascii")))
2650 return value
2653class UUIDField(Field):
2654 default_error_messages = {
2655 "invalid": _("“%(value)s” is not a valid UUID."),
2656 }
2657 description = _("Universally unique identifier")
2658 empty_strings_allowed = False
2660 def __init__(self, verbose_name=None, **kwargs):
2661 kwargs["max_length"] = 32
2662 super().__init__(verbose_name, **kwargs)
2664 def deconstruct(self):
2665 name, path, args, kwargs = super().deconstruct()
2666 del kwargs["max_length"]
2667 return name, path, args, kwargs
2669 def get_internal_type(self):
2670 return "UUIDField"
2672 def get_prep_value(self, value):
2673 value = super().get_prep_value(value)
2674 return self.to_python(value)
2676 def get_db_prep_value(self, value, connection, prepared=False):
2677 if value is None:
2678 return None
2679 if not isinstance(value, uuid.UUID):
2680 value = self.to_python(value)
2682 if connection.features.has_native_uuid_field:
2683 return value
2684 return value.hex
2686 def to_python(self, value):
2687 if value is not None and not isinstance(value, uuid.UUID):
2688 input_form = "int" if isinstance(value, int) else "hex"
2689 try:
2690 return uuid.UUID(**{input_form: value})
2691 except (AttributeError, ValueError):
2692 raise exceptions.ValidationError(
2693 self.error_messages["invalid"],
2694 code="invalid",
2695 params={"value": value},
2696 )
2697 return value
2699 def formfield(self, **kwargs):
2700 return super().formfield(
2701 **{
2702 "form_class": forms.UUIDField,
2703 **kwargs,
2704 }
2705 )
2708class AutoFieldMixin:
2709 db_returning = True
2711 def __init__(self, *args, **kwargs):
2712 kwargs["blank"] = True
2713 super().__init__(*args, **kwargs)
2715 def check(self, **kwargs):
2716 return [
2717 *super().check(**kwargs),
2718 *self._check_primary_key(),
2719 ]
2721 def _check_primary_key(self):
2722 if not self.primary_key:
2723 return [
2724 checks.Error(
2725 "AutoFields must set primary_key=True.",
2726 obj=self,
2727 id="fields.E100",
2728 ),
2729 ]
2730 else:
2731 return []
2733 def deconstruct(self):
2734 name, path, args, kwargs = super().deconstruct()
2735 del kwargs["blank"]
2736 kwargs["primary_key"] = True
2737 return name, path, args, kwargs
2739 def validate(self, value, model_instance):
2740 pass
2742 def get_db_prep_value(self, value, connection, prepared=False):
2743 if not prepared:
2744 value = self.get_prep_value(value)
2745 value = connection.ops.validate_autopk_value(value)
2746 return value
2748 def contribute_to_class(self, cls, name, **kwargs):
2749 if cls._meta.auto_field:
2750 raise ValueError(
2751 "Model %s can't have more than one auto-generated field."
2752 % cls._meta.label
2753 )
2754 super().contribute_to_class(cls, name, **kwargs)
2755 cls._meta.auto_field = self
2757 def formfield(self, **kwargs):
2758 return None
2761class AutoFieldMeta(type):
2762 """
2763 Metaclass to maintain backward inheritance compatibility for AutoField.
2765 It is intended that AutoFieldMixin become public API when it is possible to
2766 create a non-integer automatically-generated field using column defaults
2767 stored in the database.
2769 In many areas Django also relies on using isinstance() to check for an
2770 automatically-generated field as a subclass of AutoField. A new flag needs
2771 to be implemented on Field to be used instead.
2773 When these issues have been addressed, this metaclass could be used to
2774 deprecate inheritance from AutoField and use of isinstance() with AutoField
2775 for detecting automatically-generated fields.
2776 """
2778 @property
2779 def _subclasses(self):
2780 return (BigAutoField, SmallAutoField)
2782 def __instancecheck__(self, instance):
2783 return isinstance(instance, self._subclasses) or super().__instancecheck__(
2784 instance
2785 )
2787 def __subclasscheck__(self, subclass):
2788 return issubclass(subclass, self._subclasses) or super().__subclasscheck__(
2789 subclass
2790 )
2793class AutoField(AutoFieldMixin, IntegerField, metaclass=AutoFieldMeta):
2794 def get_internal_type(self):
2795 return "AutoField"
2797 def rel_db_type(self, connection):
2798 return IntegerField().db_type(connection=connection)
2801class BigAutoField(AutoFieldMixin, BigIntegerField):
2802 def get_internal_type(self):
2803 return "BigAutoField"
2805 def rel_db_type(self, connection):
2806 return BigIntegerField().db_type(connection=connection)
2809class SmallAutoField(AutoFieldMixin, SmallIntegerField):
2810 def get_internal_type(self):
2811 return "SmallAutoField"
2813 def rel_db_type(self, connection):
2814 return SmallIntegerField().db_type(connection=connection)