2018-02-06 00:42:47 +08:00
|
|
|
import collections.abc
|
2011-03-28 10:11:19 +08:00
|
|
|
import copy
|
2007-09-08 13:11:17 +08:00
|
|
|
import datetime
|
2009-12-18 06:06:41 +08:00
|
|
|
import decimal
|
2021-08-21 23:27:15 +08:00
|
|
|
import math
|
2017-11-12 08:38:29 +08:00
|
|
|
import operator
|
2014-07-15 17:35:29 +08:00
|
|
|
import uuid
|
2011-11-20 07:27:20 +08:00
|
|
|
import warnings
|
2012-12-15 07:26:08 +08:00
|
|
|
from base64 import b64decode, b64encode
|
2017-09-07 01:11:18 +08:00
|
|
|
from functools import partialmethod, total_ordering
|
2009-12-18 06:06:41 +08:00
|
|
|
|
2015-06-16 02:07:31 +08:00
|
|
|
from django import forms
|
2013-12-24 19:25:17 +08:00
|
|
|
from django.apps import apps
|
2015-06-16 02:07:31 +08:00
|
|
|
from django.conf import settings
|
|
|
|
from django.core import checks, exceptions, validators
|
2015-08-01 22:46:25 +08:00
|
|
|
from django.db import connection, connections, router
|
2016-06-09 23:56:12 +08:00
|
|
|
from django.db.models.constants import LOOKUP_SEP
|
2016-02-02 17:33:09 +08:00
|
|
|
from django.db.models.query_utils import DeferredAttribute, RegisterLookupMixin
|
2016-12-29 23:27:49 +08:00
|
|
|
from django.utils import timezone
|
2008-06-26 11:11:32 +08:00
|
|
|
from django.utils.datastructures import DictWrapper
|
2015-06-16 02:07:31 +08:00
|
|
|
from django.utils.dateparse import (
|
|
|
|
parse_date,
|
|
|
|
parse_datetime,
|
|
|
|
parse_duration,
|
|
|
|
parse_time,
|
|
|
|
)
|
2017-12-29 06:35:41 +08:00
|
|
|
from django.utils.duration import duration_microseconds, duration_string
|
2017-09-07 01:11:18 +08:00
|
|
|
from django.utils.functional import Promise, cached_property
|
2011-07-13 17:35:51 +08:00
|
|
|
from django.utils.ipv6 import clean_ipv6_address
|
2014-01-20 10:45:21 +08:00
|
|
|
from django.utils.itercompat import is_iterable
|
2015-06-16 02:07:31 +08:00
|
|
|
from django.utils.text import capfirst
|
2017-01-27 03:58:33 +08:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2015-01-02 23:14:23 +08:00
|
|
|
|
2017-01-20 17:20:53 +08:00
|
|
|
__all__ = [
|
2015-07-02 16:43:15 +08:00
|
|
|
"AutoField",
|
|
|
|
"BLANK_CHOICE_DASH",
|
|
|
|
"BigAutoField",
|
|
|
|
"BigIntegerField",
|
|
|
|
"BinaryField",
|
|
|
|
"BooleanField",
|
|
|
|
"CharField",
|
|
|
|
"CommaSeparatedIntegerField",
|
|
|
|
"DateField",
|
|
|
|
"DateTimeField",
|
|
|
|
"DecimalField",
|
|
|
|
"DurationField",
|
2019-07-18 14:13:01 +08:00
|
|
|
"EmailField",
|
|
|
|
"Empty",
|
|
|
|
"Field",
|
|
|
|
"FilePathField",
|
|
|
|
"FloatField",
|
|
|
|
"GenericIPAddressField",
|
|
|
|
"IPAddressField",
|
|
|
|
"IntegerField",
|
|
|
|
"NOT_PROVIDED",
|
2019-10-16 20:32:12 +08:00
|
|
|
"NullBooleanField",
|
|
|
|
"PositiveBigIntegerField",
|
|
|
|
"PositiveIntegerField",
|
|
|
|
"PositiveSmallIntegerField",
|
|
|
|
"SlugField",
|
|
|
|
"SmallAutoField",
|
|
|
|
"SmallIntegerField",
|
|
|
|
"TextField",
|
|
|
|
"TimeField",
|
|
|
|
"URLField",
|
|
|
|
"UUIDField",
|
2017-01-20 17:20:53 +08:00
|
|
|
]
|
2013-10-18 19:25:30 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Empty:
|
2013-01-19 20:09:46 +08:00
|
|
|
pass
|
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2006-03-01 11:51:55 +08:00
|
|
|
class NOT_PROVIDED:
|
|
|
|
pass
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2016-11-13 01:11:23 +08:00
|
|
|
|
2011-10-13 16:11:00 +08:00
|
|
|
# The values to use for "blank" in SelectFields. Will be appended to the start
|
|
|
|
# of most "choices" lists.
|
2005-08-02 05:29:52 +08:00
|
|
|
BLANK_CHOICE_DASH = [("", "---------")]
|
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2013-01-19 20:09:46 +08:00
|
|
|
def _load_field(app_label, model_name, field_name):
|
2015-01-07 08:16:35 +08:00
|
|
|
return apps.get_model(app_label, model_name)._meta.get_field(field_name)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2005-11-10 07:37:41 +08:00
|
|
|
# A guide to Field parameters:
|
|
|
|
#
|
2014-03-02 22:25:53 +08:00
|
|
|
# * name: The name of the field specified in the model.
|
2005-11-10 07:37:41 +08:00
|
|
|
# * attname: The attribute to use on the model object. This is the same as
|
|
|
|
# "name", except in the case of ForeignKeys, where "_id" is
|
|
|
|
# appended.
|
|
|
|
# * db_column: The db_column specified in the model (or None).
|
|
|
|
# * column: The database column for this field. This is the same as
|
|
|
|
# "attname", except if db_column is specified.
|
|
|
|
#
|
|
|
|
# Code that introspects values, or does other dynamic things, should use
|
|
|
|
# attname. For example, this gets the primary key value of object "obj":
|
|
|
|
#
|
|
|
|
# getattr(obj, opts.pk.attname)
|
|
|
|
|
2022-02-04 03:24:19 +08:00
|
|
|
|
2013-01-19 20:09:46 +08:00
|
|
|
def _empty(of_cls):
|
|
|
|
new = Empty()
|
|
|
|
new.__class__ = of_cls
|
|
|
|
return new
|
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2016-12-16 02:42:44 +08:00
|
|
|
def return_None():
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2012-05-08 01:08:20 +08:00
|
|
|
@total_ordering
|
2014-01-18 17:09:43 +08:00
|
|
|
class Field(RegisterLookupMixin):
|
2009-12-22 23:18:51 +08:00
|
|
|
"""Base class for all field types"""
|
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
# Designates whether empty strings fundamentally are allowed at the
|
|
|
|
# database level.
|
|
|
|
empty_strings_allowed = True
|
2013-03-06 15:28:12 +08:00
|
|
|
empty_values = list(validators.EMPTY_VALUES)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
# These track each time a Field instance is created. Used to retain order.
|
|
|
|
# The auto_creation_counter is used for fields that Django implicitly
|
|
|
|
# creates, creation_counter is used for all user-specified fields.
|
2005-08-26 06:51:30 +08:00
|
|
|
creation_counter = 0
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
auto_creation_counter = -1
|
2013-11-03 05:02:56 +08:00
|
|
|
default_validators = [] # Default set of validators
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2013-06-06 02:55:05 +08:00
|
|
|
"invalid_choice": _("Value %(value)r is not a valid choice."),
|
2012-06-08 00:08:47 +08:00
|
|
|
"null": _("This field cannot be null."),
|
|
|
|
"blank": _("This field cannot be blank."),
|
|
|
|
"unique": _("%(model_name)s with this %(field_label)s already exists."),
|
2014-07-26 18:06:19 +08:00
|
|
|
# Translators: The 'lookup_type' is one of 'date', 'year' or 'month'.
|
|
|
|
# Eg: "Title must be unique for pub_date year"
|
2014-02-04 02:31:27 +08:00
|
|
|
"unique_for_date": _(
|
|
|
|
"%(field_label)s must be unique for "
|
|
|
|
"%(date_field_label)s %(lookup_type)s."
|
|
|
|
),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
2015-01-01 23:31:36 +08:00
|
|
|
system_check_deprecated_details = None
|
|
|
|
system_check_removed_details = None
|
2005-08-26 06:51:30 +08:00
|
|
|
|
2015-01-07 08:16:35 +08:00
|
|
|
# Field flags
|
|
|
|
hidden = False
|
|
|
|
|
|
|
|
many_to_many = None
|
|
|
|
many_to_one = None
|
|
|
|
one_to_many = None
|
|
|
|
one_to_one = None
|
|
|
|
related_model = None
|
|
|
|
|
2019-07-23 20:04:06 +08:00
|
|
|
descriptor_class = DeferredAttribute
|
|
|
|
|
2013-07-28 09:45:25 +08:00
|
|
|
# Generic field type description, usually overridden by subclasses
|
2009-12-17 02:13:34 +08:00
|
|
|
def _description(self):
|
2012-06-08 00:08:47 +08:00
|
|
|
return _("Field of type: %(field_type)s") % {
|
2009-12-17 02:13:34 +08:00
|
|
|
"field_type": self.__class__.__name__
|
|
|
|
}
|
2022-02-04 03:24:19 +08:00
|
|
|
|
2009-12-17 02:13:34 +08:00
|
|
|
description = property(_description)
|
|
|
|
|
2005-08-26 06:51:30 +08:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
verbose_name=None,
|
|
|
|
name=None,
|
|
|
|
primary_key=False,
|
2016-03-29 06:33:29 +08:00
|
|
|
max_length=None,
|
|
|
|
unique=False,
|
|
|
|
blank=False,
|
|
|
|
null=False,
|
|
|
|
db_index=False,
|
|
|
|
rel=None,
|
|
|
|
default=NOT_PROVIDED,
|
|
|
|
editable=True,
|
|
|
|
serialize=True,
|
|
|
|
unique_for_date=None,
|
|
|
|
unique_for_month=None,
|
|
|
|
unique_for_year=None,
|
|
|
|
choices=None,
|
|
|
|
help_text="",
|
|
|
|
db_column=None,
|
2016-09-16 17:14:15 +08:00
|
|
|
db_tablespace=None,
|
|
|
|
auto_created=False,
|
|
|
|
validators=(),
|
2016-03-29 06:33:29 +08:00
|
|
|
error_messages=None,
|
|
|
|
):
|
2005-08-02 05:29:52 +08:00
|
|
|
self.name = name
|
2013-05-18 19:48:57 +08:00
|
|
|
self.verbose_name = verbose_name # May be set by set_attributes_from_name
|
|
|
|
self._verbose_name = verbose_name # Store original for deconstruction
|
2005-08-02 05:29:52 +08:00
|
|
|
self.primary_key = primary_key
|
2008-06-30 12:46:59 +08:00
|
|
|
self.max_length, self._unique = max_length, unique
|
2005-08-02 05:29:52 +08:00
|
|
|
self.blank, self.null = blank, null
|
2015-02-26 22:19:17 +08:00
|
|
|
self.remote_field = rel
|
|
|
|
self.is_relation = self.remote_field is not None
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
self.default = default
|
2005-08-02 05:29:52 +08:00
|
|
|
self.editable = editable
|
2007-03-19 19:57:53 +08:00
|
|
|
self.serialize = serialize
|
2013-09-08 02:48:24 +08:00
|
|
|
self.unique_for_date = unique_for_date
|
|
|
|
self.unique_for_month = unique_for_month
|
2005-08-02 05:29:52 +08:00
|
|
|
self.unique_for_year = unique_for_year
|
2018-02-06 00:42:47 +08:00
|
|
|
if isinstance(choices, collections.abc.Iterator):
|
2015-03-16 03:07:39 +08:00
|
|
|
choices = list(choices)
|
2019-01-05 04:03:53 +08:00
|
|
|
self.choices = choices
|
2005-08-02 05:29:52 +08:00
|
|
|
self.help_text = help_text
|
2015-01-27 22:40:01 +08:00
|
|
|
self.db_index = db_index
|
2005-08-26 06:51:30 +08:00
|
|
|
self.db_column = db_column
|
2017-08-09 01:24:25 +08:00
|
|
|
self._db_tablespace = db_tablespace
|
2008-08-25 11:51:25 +08:00
|
|
|
self.auto_created = auto_created
|
2005-08-02 05:29:52 +08:00
|
|
|
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
# Adjust the appropriate creation counter, and save our local copy.
|
|
|
|
if auto_created:
|
|
|
|
self.creation_counter = Field.auto_creation_counter
|
|
|
|
Field.auto_creation_counter -= 1
|
|
|
|
else:
|
|
|
|
self.creation_counter = Field.creation_counter
|
|
|
|
Field.creation_counter += 1
|
2005-08-26 06:51:30 +08:00
|
|
|
|
2016-09-16 17:14:15 +08:00
|
|
|
self._validators = list(validators) # Store for deconstruction later
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2013-05-18 19:48:57 +08:00
|
|
|
self._error_messages = error_messages # Store for deconstruction later
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2014-01-20 10:45:21 +08:00
|
|
|
def __str__(self):
|
2016-12-15 03:04:26 +08:00
|
|
|
"""
|
|
|
|
Return "app_label.model_label.field_name" for fields attached to
|
|
|
|
models.
|
|
|
|
"""
|
|
|
|
if not hasattr(self, "model"):
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().__str__()
|
2014-01-20 10:45:21 +08:00
|
|
|
model = self.model
|
2020-12-29 15:56:39 +08:00
|
|
|
return "%s.%s" % (model._meta.label, self.name)
|
2014-01-20 10:45:21 +08:00
|
|
|
|
|
|
|
def __repr__(self):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Display the module, class, and name of the field."""
|
2017-06-14 20:41:02 +08:00
|
|
|
path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__)
|
2014-01-20 10:45:21 +08:00
|
|
|
name = getattr(self, "name", None)
|
|
|
|
if name is not None:
|
|
|
|
return "<%s: %s>" % (path, name)
|
|
|
|
return "<%s>" % path
|
|
|
|
|
|
|
|
def check(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return [
|
|
|
|
*self._check_field_name(),
|
|
|
|
*self._check_choices(),
|
|
|
|
*self._check_db_index(),
|
|
|
|
*self._check_null_allowed_for_primary_keys(),
|
|
|
|
*self._check_backend_specific_checks(**kwargs),
|
|
|
|
*self._check_validators(),
|
|
|
|
*self._check_deprecation_details(),
|
|
|
|
]
|
2014-01-20 10:45:21 +08:00
|
|
|
|
|
|
|
def _check_field_name(self):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""
|
|
|
|
Check if field name is valid, i.e. 1) does not end with an
|
|
|
|
underscore, 2) does not contain "__" and 3) is not "pk".
|
|
|
|
"""
|
2014-01-20 10:45:21 +08:00
|
|
|
if self.name.endswith("_"):
|
|
|
|
return [
|
|
|
|
checks.Error(
|
2014-03-03 18:18:39 +08:00
|
|
|
"Field names must not end with an underscore.",
|
2014-01-20 10:45:21 +08:00
|
|
|
obj=self,
|
2014-03-03 18:18:39 +08:00
|
|
|
id="fields.E001",
|
2014-01-20 10:45:21 +08:00
|
|
|
)
|
|
|
|
]
|
2016-06-09 23:56:12 +08:00
|
|
|
elif LOOKUP_SEP in self.name:
|
2014-02-08 05:34:56 +08:00
|
|
|
return [
|
|
|
|
checks.Error(
|
2020-04-25 21:53:30 +08:00
|
|
|
'Field names must not contain "%s".' % LOOKUP_SEP,
|
2014-02-08 05:34:56 +08:00
|
|
|
obj=self,
|
2014-03-03 18:18:39 +08:00
|
|
|
id="fields.E002",
|
2014-02-08 05:34:56 +08:00
|
|
|
)
|
|
|
|
]
|
|
|
|
elif self.name == "pk":
|
|
|
|
return [
|
|
|
|
checks.Error(
|
2014-03-03 18:18:39 +08:00
|
|
|
"'pk' is a reserved word that cannot be used as a field name.",
|
2014-02-08 05:34:56 +08:00
|
|
|
obj=self,
|
2014-03-03 18:18:39 +08:00
|
|
|
id="fields.E003",
|
2014-02-08 05:34:56 +08:00
|
|
|
)
|
|
|
|
]
|
2014-01-20 10:45:21 +08:00
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
2019-11-01 03:31:14 +08:00
|
|
|
@classmethod
|
|
|
|
def _choices_is_value(cls, value):
|
|
|
|
return isinstance(value, (str, Promise)) or not is_iterable(value)
|
|
|
|
|
2014-01-20 10:45:21 +08:00
|
|
|
def _check_choices(self):
|
2017-11-30 14:33:24 +08:00
|
|
|
if not self.choices:
|
|
|
|
return []
|
|
|
|
|
2019-11-01 03:04:47 +08:00
|
|
|
if not is_iterable(self.choices) or isinstance(self.choices, str):
|
2017-11-30 14:33:24 +08:00
|
|
|
return [
|
|
|
|
checks.Error(
|
|
|
|
"'choices' must be an iterable (e.g., a list or tuple).",
|
|
|
|
obj=self,
|
|
|
|
id="fields.E004",
|
|
|
|
)
|
|
|
|
]
|
|
|
|
|
2019-09-04 16:21:08 +08:00
|
|
|
choice_max_length = 0
|
2017-11-30 14:33:24 +08:00
|
|
|
# Expect [group_name, [value, display]]
|
|
|
|
for choices_group in self.choices:
|
|
|
|
try:
|
|
|
|
group_name, group_choices = choices_group
|
2018-08-22 04:35:25 +08:00
|
|
|
except (TypeError, ValueError):
|
2017-11-30 14:33:24 +08:00
|
|
|
# Containing non-pairs
|
|
|
|
break
|
|
|
|
try:
|
|
|
|
if not all(
|
2019-11-01 03:31:14 +08:00
|
|
|
self._choices_is_value(value) and self._choices_is_value(human_name)
|
2017-11-30 14:33:24 +08:00
|
|
|
for value, human_name in group_choices
|
|
|
|
):
|
|
|
|
break
|
2019-09-04 16:21:08 +08:00
|
|
|
if self.max_length is not None and group_choices:
|
2020-01-12 02:47:36 +08:00
|
|
|
choice_max_length = max(
|
|
|
|
[
|
2019-09-04 16:21:08 +08:00
|
|
|
choice_max_length,
|
|
|
|
*(
|
|
|
|
len(value)
|
|
|
|
for value, _ in group_choices
|
|
|
|
if isinstance(value, str)
|
|
|
|
),
|
2020-01-12 02:47:36 +08:00
|
|
|
]
|
|
|
|
)
|
2017-11-30 14:33:24 +08:00
|
|
|
except (TypeError, ValueError):
|
|
|
|
# No groups, choices in the form [value, display]
|
|
|
|
value, human_name = group_name, group_choices
|
2019-11-01 03:31:14 +08:00
|
|
|
if not self._choices_is_value(value) or not self._choices_is_value(
|
|
|
|
human_name
|
|
|
|
):
|
2017-11-30 14:33:24 +08:00
|
|
|
break
|
2019-09-04 16:21:08 +08:00
|
|
|
if self.max_length is not None and isinstance(value, str):
|
|
|
|
choice_max_length = max(choice_max_length, len(value))
|
2017-11-30 14:33:24 +08:00
|
|
|
|
|
|
|
# Special case: choices=['ab']
|
|
|
|
if isinstance(choices_group, str):
|
|
|
|
break
|
2014-01-20 10:45:21 +08:00
|
|
|
else:
|
2019-09-04 16:21:08 +08:00
|
|
|
if self.max_length is not None and choice_max_length > self.max_length:
|
|
|
|
return [
|
|
|
|
checks.Error(
|
|
|
|
"'max_length' is too small to fit the longest value "
|
|
|
|
"in 'choices' (%d characters)." % choice_max_length,
|
|
|
|
obj=self,
|
|
|
|
id="fields.E009",
|
|
|
|
),
|
|
|
|
]
|
2014-01-20 10:45:21 +08:00
|
|
|
return []
|
|
|
|
|
2017-11-30 14:33:24 +08:00
|
|
|
return [
|
|
|
|
checks.Error(
|
|
|
|
"'choices' must be an iterable containing "
|
|
|
|
"(actual value, human readable name) tuples.",
|
|
|
|
obj=self,
|
|
|
|
id="fields.E005",
|
|
|
|
)
|
|
|
|
]
|
|
|
|
|
2014-01-20 10:45:21 +08:00
|
|
|
def _check_db_index(self):
|
|
|
|
if self.db_index not in (None, True, False):
|
|
|
|
return [
|
|
|
|
checks.Error(
|
2014-03-03 18:18:39 +08:00
|
|
|
"'db_index' must be None, True or False.",
|
2014-01-20 10:45:21 +08:00
|
|
|
obj=self,
|
2014-03-03 18:18:39 +08:00
|
|
|
id="fields.E006",
|
2014-01-20 10:45:21 +08:00
|
|
|
)
|
|
|
|
]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
|
|
|
def _check_null_allowed_for_primary_keys(self):
|
|
|
|
if (
|
|
|
|
self.primary_key
|
|
|
|
and self.null
|
|
|
|
and not connection.features.interprets_empty_strings_as_nulls
|
|
|
|
):
|
|
|
|
# We cannot reliably check this for backends like Oracle which
|
|
|
|
# consider NULL and '' to be equal (and thus set up
|
|
|
|
# character-based fields a little differently).
|
|
|
|
return [
|
|
|
|
checks.Error(
|
|
|
|
"Primary keys must not have null=True.",
|
2014-03-03 18:18:39 +08:00
|
|
|
hint=(
|
|
|
|
"Set null=False on the field, or "
|
2014-01-20 10:45:21 +08:00
|
|
|
"remove primary_key=True argument."
|
|
|
|
),
|
|
|
|
obj=self,
|
2014-03-03 18:18:39 +08:00
|
|
|
id="fields.E007",
|
2014-01-20 10:45:21 +08:00
|
|
|
)
|
|
|
|
]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
2020-02-19 19:14:54 +08:00
|
|
|
def _check_backend_specific_checks(self, databases=None, **kwargs):
|
|
|
|
if databases is None:
|
|
|
|
return []
|
2015-08-01 22:46:25 +08:00
|
|
|
app_label = self.model._meta.app_label
|
2020-02-19 19:14:54 +08:00
|
|
|
errors = []
|
|
|
|
for alias in databases:
|
|
|
|
if router.allow_migrate(
|
|
|
|
alias, app_label, model_name=self.model._meta.model_name
|
|
|
|
):
|
|
|
|
errors.extend(connections[alias].validation.check_field(self, **kwargs))
|
|
|
|
return errors
|
2014-01-20 10:45:21 +08:00
|
|
|
|
2017-03-06 00:50:33 +08:00
|
|
|
def _check_validators(self):
|
|
|
|
errors = []
|
|
|
|
for i, validator in enumerate(self.validators):
|
|
|
|
if not callable(validator):
|
|
|
|
errors.append(
|
|
|
|
checks.Error(
|
|
|
|
"All 'validators' must be callable.",
|
|
|
|
hint=(
|
|
|
|
"validators[{i}] ({repr}) isn't a function or "
|
|
|
|
"instance of a validator class.".format(
|
|
|
|
i=i,
|
|
|
|
repr=repr(validator),
|
|
|
|
)
|
|
|
|
),
|
|
|
|
obj=self,
|
|
|
|
id="fields.E008",
|
|
|
|
)
|
|
|
|
)
|
|
|
|
return errors
|
|
|
|
|
2015-01-01 23:31:36 +08:00
|
|
|
def _check_deprecation_details(self):
|
|
|
|
if self.system_check_removed_details is not None:
|
|
|
|
return [
|
|
|
|
checks.Error(
|
|
|
|
self.system_check_removed_details.get(
|
|
|
|
"msg",
|
|
|
|
"%s has been removed except for support in historical "
|
|
|
|
"migrations." % self.__class__.__name__,
|
|
|
|
),
|
|
|
|
hint=self.system_check_removed_details.get("hint"),
|
|
|
|
obj=self,
|
|
|
|
id=self.system_check_removed_details.get("id", "fields.EXXX"),
|
|
|
|
)
|
|
|
|
]
|
|
|
|
elif self.system_check_deprecated_details is not None:
|
|
|
|
return [
|
|
|
|
checks.Warning(
|
|
|
|
self.system_check_deprecated_details.get(
|
|
|
|
"msg", "%s has been deprecated." % self.__class__.__name__
|
|
|
|
),
|
|
|
|
hint=self.system_check_deprecated_details.get("hint"),
|
|
|
|
obj=self,
|
|
|
|
id=self.system_check_deprecated_details.get("id", "fields.WXXX"),
|
|
|
|
)
|
|
|
|
]
|
|
|
|
return []
|
|
|
|
|
2015-02-15 03:37:12 +08:00
|
|
|
def get_col(self, alias, output_field=None):
|
2021-07-08 02:32:57 +08:00
|
|
|
if alias == self.model._meta.db_table and (
|
|
|
|
output_field is None or output_field == self
|
|
|
|
):
|
2014-12-01 15:28:01 +08:00
|
|
|
return self.cached_col
|
2021-07-08 02:32:57 +08:00
|
|
|
from django.db.models.expressions import Col
|
2022-02-04 03:24:19 +08:00
|
|
|
|
2021-07-08 02:32:57 +08:00
|
|
|
return Col(alias, self, output_field)
|
2014-12-01 15:28:01 +08:00
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def cached_col(self):
|
|
|
|
from django.db.models.expressions import Col
|
2022-02-04 03:24:19 +08:00
|
|
|
|
2014-12-01 15:28:01 +08:00
|
|
|
return Col(self.model._meta.db_table, self)
|
|
|
|
|
|
|
|
def select_format(self, compiler, sql, params):
|
|
|
|
"""
|
|
|
|
Custom format for select clauses. For example, GIS columns need to be
|
2017-01-25 07:04:12 +08:00
|
|
|
selected as AsText(table.col) on MySQL as the table.col data can't be
|
|
|
|
used by Django.
|
2014-12-01 15:28:01 +08:00
|
|
|
"""
|
|
|
|
return sql, params
|
|
|
|
|
2013-05-18 19:48:57 +08:00
|
|
|
def deconstruct(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return enough information to recreate the field as a 4-tuple:
|
2013-05-18 19:48:57 +08:00
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
* The name of the field on the model, if contribute_to_class() has
|
|
|
|
been run.
|
2021-04-10 00:55:08 +08:00
|
|
|
* The import path of the field, including the class, e.g.
|
|
|
|
django.db.models.IntegerField. This should be the most portable
|
2017-01-25 07:04:12 +08:00
|
|
|
version, so less specific may be better.
|
|
|
|
* A list of positional arguments.
|
|
|
|
* A dict of keyword arguments.
|
2013-05-18 19:48:57 +08:00
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
Note that the positional or keyword arguments must contain values of
|
|
|
|
the following types (including inner values of collection types):
|
2013-05-18 19:48:57 +08:00
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
* None, bool, str, int, float, complex, set, frozenset, list, tuple,
|
|
|
|
dict
|
2013-05-18 19:48:57 +08:00
|
|
|
* UUID
|
|
|
|
* datetime.datetime (naive), datetime.date
|
2017-01-25 07:04:12 +08:00
|
|
|
* top-level classes, top-level functions - will be referenced by their
|
|
|
|
full import path
|
2013-05-18 19:48:57 +08:00
|
|
|
* Storage instances - these have their own deconstruct() method
|
|
|
|
|
2014-03-02 22:25:53 +08:00
|
|
|
This is because the values here must be serialized into a text format
|
2013-05-18 19:48:57 +08:00
|
|
|
(possibly new Python code, possibly JSON) and these are the only types
|
|
|
|
with encoding handlers defined.
|
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
There's no need to return the exact way the field was instantiated this
|
|
|
|
time, just ensure that the resulting field is the same - prefer keyword
|
|
|
|
arguments over positional ones, and omit parameters with their default
|
|
|
|
values.
|
2013-05-18 19:48:57 +08:00
|
|
|
"""
|
|
|
|
# Short-form way of fetching all the default parameters
|
|
|
|
keywords = {}
|
|
|
|
possibles = {
|
|
|
|
"verbose_name": None,
|
|
|
|
"primary_key": False,
|
|
|
|
"max_length": None,
|
|
|
|
"unique": False,
|
|
|
|
"blank": False,
|
|
|
|
"null": False,
|
|
|
|
"db_index": False,
|
|
|
|
"default": NOT_PROVIDED,
|
|
|
|
"editable": True,
|
|
|
|
"serialize": True,
|
|
|
|
"unique_for_date": None,
|
|
|
|
"unique_for_month": None,
|
|
|
|
"unique_for_year": None,
|
2019-01-05 04:03:53 +08:00
|
|
|
"choices": None,
|
2013-05-18 19:48:57 +08:00
|
|
|
"help_text": "",
|
|
|
|
"db_column": None,
|
2017-08-09 01:24:25 +08:00
|
|
|
"db_tablespace": None,
|
2013-05-18 19:48:57 +08:00
|
|
|
"auto_created": False,
|
|
|
|
"validators": [],
|
|
|
|
"error_messages": None,
|
|
|
|
}
|
|
|
|
attr_overrides = {
|
|
|
|
"unique": "_unique",
|
|
|
|
"error_messages": "_error_messages",
|
|
|
|
"validators": "_validators",
|
|
|
|
"verbose_name": "_verbose_name",
|
2017-08-09 01:24:25 +08:00
|
|
|
"db_tablespace": "_db_tablespace",
|
2013-05-18 19:48:57 +08:00
|
|
|
}
|
2017-08-09 01:24:25 +08:00
|
|
|
equals_comparison = {"choices", "validators"}
|
2013-05-18 19:48:57 +08:00
|
|
|
for name, default in possibles.items():
|
|
|
|
value = getattr(self, attr_overrides.get(name, name))
|
2014-01-25 08:23:28 +08:00
|
|
|
# Unroll anything iterable for choices into a concrete list
|
2018-02-06 00:42:47 +08:00
|
|
|
if name == "choices" and isinstance(value, collections.abc.Iterable):
|
2014-01-25 08:23:28 +08:00
|
|
|
value = list(value)
|
|
|
|
# Do correct kind of comparison
|
2013-05-18 19:48:57 +08:00
|
|
|
if name in equals_comparison:
|
|
|
|
if value != default:
|
|
|
|
keywords[name] = value
|
|
|
|
else:
|
|
|
|
if value is not default:
|
|
|
|
keywords[name] = value
|
|
|
|
# Work out path - we shorten it for known Django core fields
|
2017-06-14 20:41:02 +08:00
|
|
|
path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__)
|
2013-05-18 19:48:57 +08:00
|
|
|
if path.startswith("django.db.models.fields.related"):
|
|
|
|
path = path.replace("django.db.models.fields.related", "django.db.models")
|
2019-08-14 16:50:31 +08:00
|
|
|
elif path.startswith("django.db.models.fields.files"):
|
2013-05-18 19:48:57 +08:00
|
|
|
path = path.replace("django.db.models.fields.files", "django.db.models")
|
2019-06-09 08:56:37 +08:00
|
|
|
elif path.startswith("django.db.models.fields.json"):
|
|
|
|
path = path.replace("django.db.models.fields.json", "django.db.models")
|
2019-08-14 16:50:31 +08:00
|
|
|
elif path.startswith("django.db.models.fields.proxy"):
|
2013-12-06 22:21:13 +08:00
|
|
|
path = path.replace("django.db.models.fields.proxy", "django.db.models")
|
2019-08-14 16:50:31 +08:00
|
|
|
elif path.startswith("django.db.models.fields"):
|
2013-05-18 19:48:57 +08:00
|
|
|
path = path.replace("django.db.models.fields", "django.db.models")
|
|
|
|
# Return basic info - other fields should override this.
|
2017-03-04 22:47:49 +08:00
|
|
|
return (self.name, path, [], keywords)
|
2013-05-18 19:48:57 +08:00
|
|
|
|
2013-12-04 21:55:45 +08:00
|
|
|
def clone(self):
|
|
|
|
"""
|
|
|
|
Uses deconstruct() to clone a new copy of this Field.
|
|
|
|
Will not preserve any class attachments/attribute names.
|
|
|
|
"""
|
|
|
|
name, path, args, kwargs = self.deconstruct()
|
|
|
|
return self.__class__(*args, **kwargs)
|
|
|
|
|
2012-05-08 01:08:20 +08:00
|
|
|
def __eq__(self, other):
|
|
|
|
# Needed for @total_ordering
|
|
|
|
if isinstance(other, Field):
|
2020-06-30 12:16:05 +08:00
|
|
|
return self.creation_counter == other.creation_counter and getattr(
|
|
|
|
self, "model", None
|
|
|
|
) == getattr(other, "model", None)
|
2012-05-08 01:08:20 +08:00
|
|
|
return NotImplemented
|
|
|
|
|
|
|
|
def __lt__(self, other):
|
2006-05-02 09:31:56 +08:00
|
|
|
# This is needed because bisect does not take a comparison function.
|
2020-06-30 12:16:05 +08:00
|
|
|
# Order by creation_counter first for backward compatibility.
|
2012-05-08 01:08:20 +08:00
|
|
|
if isinstance(other, Field):
|
2020-06-30 12:16:05 +08:00
|
|
|
if (
|
|
|
|
self.creation_counter != other.creation_counter
|
|
|
|
or not hasattr(self, "model")
|
|
|
|
and not hasattr(other, "model")
|
|
|
|
):
|
|
|
|
return self.creation_counter < other.creation_counter
|
|
|
|
elif hasattr(self, "model") != hasattr(other, "model"):
|
|
|
|
return not hasattr(self, "model") # Order no-model fields first
|
|
|
|
else:
|
|
|
|
# creation_counter's are equal, compare only models.
|
|
|
|
return (self.model._meta.app_label, self.model._meta.model_name) < (
|
|
|
|
other.model._meta.app_label,
|
|
|
|
other.model._meta.model_name,
|
|
|
|
)
|
2012-05-08 01:08:20 +08:00
|
|
|
return NotImplemented
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2013-02-26 05:53:08 +08:00
|
|
|
def __hash__(self):
|
2022-01-14 02:51:18 +08:00
|
|
|
return hash(self.creation_counter)
|
2012-07-21 16:01:46 +08:00
|
|
|
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
def __deepcopy__(self, memodict):
|
|
|
|
# We don't have to deepcopy very much here, since most things are not
|
|
|
|
# intended to be altered after initial creation.
|
|
|
|
obj = copy.copy(self)
|
2015-02-26 22:19:17 +08:00
|
|
|
if self.remote_field:
|
|
|
|
obj.remote_field = copy.copy(self.remote_field)
|
|
|
|
if hasattr(self.remote_field, "field") and self.remote_field.field is self:
|
|
|
|
obj.remote_field.field = obj
|
Merged the queryset-refactor branch into trunk.
This is a big internal change, but mostly backwards compatible with existing
code. Also adds a couple of new features.
Fixed #245, #1050, #1656, #1801, #2076, #2091, #2150, #2253, #2306, #2400, #2430, #2482, #2496, #2676, #2737, #2874, #2902, #2939, #3037, #3141, #3288, #3440, #3592, #3739, #4088, #4260, #4289, #4306, #4358, #4464, #4510, #4858, #5012, #5020, #5261, #5295, #5321, #5324, #5325, #5555, #5707, #5796, #5817, #5987, #6018, #6074, #6088, #6154, #6177, #6180, #6203, #6658
git-svn-id: http://code.djangoproject.com/svn/django/trunk@7477 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-04-27 10:50:16 +08:00
|
|
|
memodict[id(self)] = obj
|
|
|
|
return obj
|
|
|
|
|
2013-01-19 20:09:46 +08:00
|
|
|
def __copy__(self):
|
|
|
|
# We need to avoid hitting __reduce__, so define this
|
|
|
|
# slightly weird copy construct.
|
|
|
|
obj = Empty()
|
|
|
|
obj.__class__ = self.__class__
|
|
|
|
obj.__dict__ = self.__dict__.copy()
|
|
|
|
return obj
|
|
|
|
|
|
|
|
def __reduce__(self):
|
|
|
|
"""
|
|
|
|
Pickling should return the model._meta.fields instance of the field,
|
2017-01-25 07:04:12 +08:00
|
|
|
not a new copy of that field. So, use the app registry to load the
|
2013-01-19 20:09:46 +08:00
|
|
|
model and then the field back.
|
|
|
|
"""
|
|
|
|
if not hasattr(self, "model"):
|
|
|
|
# Fields are sometimes used without attaching them to models (for
|
|
|
|
# example in aggregation). In this case give back a plain field
|
|
|
|
# instance. The code below will create a new empty instance of
|
|
|
|
# class self.__class__, then update its dict with self.__dict__
|
|
|
|
# values - so, this is very close to normal pickle.
|
2017-05-12 09:04:52 +08:00
|
|
|
state = self.__dict__.copy()
|
|
|
|
# The _get_default cached_property can't be pickled due to lambda
|
|
|
|
# usage.
|
|
|
|
state.pop("_get_default", None)
|
|
|
|
return _empty, (self.__class__,), state
|
2013-01-19 20:09:46 +08:00
|
|
|
return _load_field, (
|
|
|
|
self.model._meta.app_label,
|
|
|
|
self.model._meta.object_name,
|
|
|
|
self.name,
|
|
|
|
)
|
|
|
|
|
2015-01-28 19:40:48 +08:00
|
|
|
def get_pk_value_on_save(self, instance):
|
|
|
|
"""
|
|
|
|
Hook to generate new PK values on save. This method is called when
|
|
|
|
saving instances with no primary key value set. If this method returns
|
|
|
|
something else than None, then the returned value is used when saving
|
|
|
|
the new instance.
|
|
|
|
"""
|
|
|
|
if self.default:
|
|
|
|
return self.get_default()
|
|
|
|
return None
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Convert the input value into the expected Python data type, raising
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
django.core.exceptions.ValidationError if the data can't be converted.
|
2017-01-25 07:04:12 +08:00
|
|
|
Return the converted value. Subclasses should override this.
|
2006-05-02 09:31:56 +08:00
|
|
|
"""
|
|
|
|
return value
|
|
|
|
|
2022-02-17 03:30:04 +08:00
|
|
|
@cached_property
|
|
|
|
def error_messages(self):
|
|
|
|
messages = {}
|
|
|
|
for c in reversed(self.__class__.__mro__):
|
|
|
|
messages.update(getattr(c, "default_error_messages", {}))
|
|
|
|
messages.update(self._error_messages or {})
|
|
|
|
return messages
|
|
|
|
|
2014-03-26 09:40:56 +08:00
|
|
|
@cached_property
|
|
|
|
def validators(self):
|
2016-04-22 08:18:43 +08:00
|
|
|
"""
|
|
|
|
Some validators can't be created at field initialization time.
|
|
|
|
This method provides a way to delay their creation until required.
|
|
|
|
"""
|
2017-12-11 20:08:45 +08:00
|
|
|
return [*self.default_validators, *self._validators]
|
2014-03-26 09:40:56 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def run_validators(self, value):
|
2013-03-06 15:28:12 +08:00
|
|
|
if value in self.empty_values:
|
2010-01-05 11:56:19 +08:00
|
|
|
return
|
|
|
|
|
|
|
|
errors = []
|
|
|
|
for v in self.validators:
|
|
|
|
try:
|
|
|
|
v(value)
|
2012-04-29 00:09:37 +08:00
|
|
|
except exceptions.ValidationError as e:
|
2010-01-05 11:56:19 +08:00
|
|
|
if hasattr(e, "code") and e.code in self.error_messages:
|
2013-04-05 03:21:57 +08:00
|
|
|
e.message = self.error_messages[e.code]
|
|
|
|
errors.extend(e.error_list)
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
if errors:
|
|
|
|
raise exceptions.ValidationError(errors)
|
|
|
|
|
|
|
|
def validate(self, value, model_instance):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Validate value and raise ValidationError if necessary. Subclasses
|
|
|
|
should override this to provide validation logic.
|
2010-01-05 11:56:19 +08:00
|
|
|
"""
|
|
|
|
if not self.editable:
|
|
|
|
# Skip validation for non-editable fields.
|
|
|
|
return
|
2012-08-06 16:42:21 +08:00
|
|
|
|
2019-01-05 04:03:53 +08:00
|
|
|
if self.choices is not None and value not in self.empty_values:
|
2010-02-02 08:41:28 +08:00
|
|
|
for option_key, option_value in self.choices:
|
2010-02-24 02:27:51 +08:00
|
|
|
if isinstance(option_value, (list, tuple)):
|
2011-10-13 16:11:00 +08:00
|
|
|
# This is an optgroup, so look inside the group for
|
|
|
|
# options.
|
2010-02-02 08:41:28 +08:00
|
|
|
for optgroup_key, optgroup_value in option_value:
|
|
|
|
if value == optgroup_key:
|
|
|
|
return
|
|
|
|
elif value == option_key:
|
|
|
|
return
|
2013-06-06 02:55:05 +08:00
|
|
|
raise exceptions.ValidationError(
|
|
|
|
self.error_messages["invalid_choice"],
|
|
|
|
code="invalid_choice",
|
|
|
|
params={"value": value},
|
|
|
|
)
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
if value is None and not self.null:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise exceptions.ValidationError(self.error_messages["null"], code="null")
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2013-03-06 15:28:12 +08:00
|
|
|
if not self.blank and value in self.empty_values:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise exceptions.ValidationError(self.error_messages["blank"], code="blank")
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
def clean(self, value, model_instance):
|
|
|
|
"""
|
2011-10-13 16:11:00 +08:00
|
|
|
Convert the value's type and run validation. Validation errors
|
2017-01-25 07:04:12 +08:00
|
|
|
from to_python() and validate() are propagated. Return the correct
|
|
|
|
value if no error is raised.
|
2010-01-05 11:56:19 +08:00
|
|
|
"""
|
|
|
|
value = self.to_python(value)
|
|
|
|
self.validate(value, model_instance)
|
|
|
|
self.run_validators(value)
|
|
|
|
return value
|
|
|
|
|
2017-07-18 03:12:27 +08:00
|
|
|
def db_type_parameters(self, connection):
|
|
|
|
return DictWrapper(self.__dict__, connection.ops.quote_name, "qn_")
|
|
|
|
|
2016-01-18 19:59:28 +08:00
|
|
|
def db_check(self, connection):
|
|
|
|
"""
|
|
|
|
Return the database column check constraint for this field, for the
|
|
|
|
provided connection. Works the same way as db_type() for the case that
|
|
|
|
get_internal_type() does not map to a preexisting model field.
|
|
|
|
"""
|
2017-07-18 03:12:27 +08:00
|
|
|
data = self.db_type_parameters(connection)
|
2016-01-18 19:59:28 +08:00
|
|
|
try:
|
|
|
|
return (
|
|
|
|
connection.data_type_check_constraints[self.get_internal_type()] % data
|
2022-02-04 03:24:19 +08:00
|
|
|
)
|
2016-01-18 19:59:28 +08:00
|
|
|
except KeyError:
|
|
|
|
return None
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def db_type(self, connection):
|
2007-07-20 14:28:56 +08:00
|
|
|
"""
|
2016-01-18 19:59:28 +08:00
|
|
|
Return the database column data type for this field, for the provided
|
2009-12-22 23:18:51 +08:00
|
|
|
connection.
|
2007-07-20 14:28:56 +08:00
|
|
|
"""
|
|
|
|
# The default implementation of this method looks at the
|
2014-03-15 06:18:20 +08:00
|
|
|
# backend-specific data_types dictionary, looking up the field by its
|
2007-07-20 14:28:56 +08:00
|
|
|
# "internal type".
|
|
|
|
#
|
|
|
|
# A Field class can implement the get_internal_type() method to specify
|
|
|
|
# which *preexisting* Django Field class it's most similar to -- i.e.,
|
2011-10-13 16:11:00 +08:00
|
|
|
# a custom field might be represented by a TEXT column type, which is
|
|
|
|
# the same as the TextField Django field type, which means the custom
|
|
|
|
# field's get_internal_type() returns 'TextField'.
|
2007-07-20 14:28:56 +08:00
|
|
|
#
|
2008-08-11 20:11:25 +08:00
|
|
|
# But the limitation of the get_internal_type() / data_types approach
|
2007-07-20 14:28:56 +08:00
|
|
|
# is that it cannot handle database column types that aren't already
|
|
|
|
# mapped to one of the built-in Django field types. In this case, you
|
|
|
|
# can implement db_type() instead of get_internal_type() to specify
|
|
|
|
# exactly which wacky database column type you want to use.
|
2017-07-18 03:12:27 +08:00
|
|
|
data = self.db_type_parameters(connection)
|
2014-03-15 06:18:20 +08:00
|
|
|
try:
|
2014-12-30 04:14:40 +08:00
|
|
|
return connection.data_types[self.get_internal_type()] % data
|
2014-03-15 06:18:20 +08:00
|
|
|
except KeyError:
|
|
|
|
return None
|
2012-09-08 03:40:59 +08:00
|
|
|
|
2015-11-13 15:56:10 +08:00
|
|
|
def rel_db_type(self, connection):
|
|
|
|
"""
|
|
|
|
Return the data type that a related field pointing to this field should
|
|
|
|
use. For example, this method is called by ForeignKey and OneToOneField
|
|
|
|
to determine its data type.
|
|
|
|
"""
|
|
|
|
return self.db_type(connection)
|
|
|
|
|
2017-07-27 08:26:58 +08:00
|
|
|
def cast_db_type(self, connection):
|
|
|
|
"""Return the data type to use in the Cast() function."""
|
|
|
|
db_type = connection.ops.cast_data_types.get(self.get_internal_type())
|
|
|
|
if db_type:
|
|
|
|
return db_type % self.db_type_parameters(connection)
|
|
|
|
return self.db_type(connection)
|
|
|
|
|
2012-09-08 03:40:59 +08:00
|
|
|
def db_parameters(self, connection):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Extension of db_type(), providing a range of different return values
|
|
|
|
(type, checks). This will look at db_type(), allowing custom model
|
|
|
|
fields to override it.
|
2012-09-08 03:40:59 +08:00
|
|
|
"""
|
2014-03-15 06:18:20 +08:00
|
|
|
type_string = self.db_type(connection)
|
2016-01-18 19:59:28 +08:00
|
|
|
check_string = self.db_check(connection)
|
2012-09-08 03:40:59 +08:00
|
|
|
return {
|
|
|
|
"type": type_string,
|
|
|
|
"check": check_string,
|
|
|
|
}
|
2007-07-20 14:28:56 +08:00
|
|
|
|
2013-09-07 00:18:16 +08:00
|
|
|
def db_type_suffix(self, connection):
|
2014-12-30 04:14:40 +08:00
|
|
|
return connection.data_types_suffix.get(self.get_internal_type())
|
2013-09-07 00:18:16 +08:00
|
|
|
|
2014-08-12 20:08:40 +08:00
|
|
|
def get_db_converters(self, connection):
|
|
|
|
if hasattr(self, "from_db_value"):
|
|
|
|
return [self.from_db_value]
|
|
|
|
return []
|
|
|
|
|
2011-08-13 19:53:42 +08:00
|
|
|
@property
|
2008-06-30 12:46:59 +08:00
|
|
|
def unique(self):
|
|
|
|
return self._unique or self.primary_key
|
|
|
|
|
2017-08-09 01:24:25 +08:00
|
|
|
@property
|
|
|
|
def db_tablespace(self):
|
|
|
|
return self._db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
|
|
|
|
|
2019-07-24 14:42:41 +08:00
|
|
|
@property
|
|
|
|
def db_returning(self):
|
|
|
|
"""
|
|
|
|
Private API intended only to be used by Django itself. Currently only
|
|
|
|
the PostgreSQL backend supports returning multiple fields on a model.
|
|
|
|
"""
|
|
|
|
return False
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def set_attributes_from_name(self, name):
|
2018-01-04 07:52:12 +08:00
|
|
|
self.name = self.name or name
|
2005-11-10 07:37:41 +08:00
|
|
|
self.attname, self.column = self.get_attname_column()
|
2015-01-07 08:16:35 +08:00
|
|
|
self.concrete = self.column is not None
|
2011-08-13 19:53:42 +08:00
|
|
|
if self.verbose_name is None and self.name:
|
|
|
|
self.verbose_name = self.name.replace("_", " ")
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2017-01-01 00:54:49 +08:00
|
|
|
def contribute_to_class(self, cls, name, private_only=False):
|
2016-03-21 01:10:55 +08:00
|
|
|
"""
|
|
|
|
Register the field with the model class it belongs to.
|
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
If private_only is True, create a separate instance of this field
|
|
|
|
for every subclass of cls, even if cls is not an abstract model.
|
2016-03-21 01:10:55 +08:00
|
|
|
"""
|
2006-05-02 09:31:56 +08:00
|
|
|
self.set_attributes_from_name(name)
|
2010-04-15 20:41:08 +08:00
|
|
|
self.model = cls
|
2019-04-29 13:54:32 +08:00
|
|
|
cls._meta.add_field(self, private=private_only)
|
2016-02-02 17:33:09 +08:00
|
|
|
if self.column:
|
2021-06-09 22:55:22 +08:00
|
|
|
setattr(cls, self.attname, self.descriptor_class(self))
|
2019-01-05 04:03:53 +08:00
|
|
|
if self.choices is not None:
|
2020-01-07 18:52:09 +08:00
|
|
|
# Don't override a get_FOO_display() method defined explicitly on
|
|
|
|
# this class, but don't check methods derived from inheritance, to
|
|
|
|
# allow overriding inherited choices. For more complex inheritance
|
|
|
|
# structures users should override contribute_to_class().
|
|
|
|
if "get_%s_display" % self.name not in cls.__dict__:
|
2019-10-31 18:34:56 +08:00
|
|
|
setattr(
|
|
|
|
cls,
|
|
|
|
"get_%s_display" % self.name,
|
|
|
|
partialmethod(cls._get_FIELD_display, field=self),
|
|
|
|
)
|
2005-08-26 06:51:30 +08:00
|
|
|
|
2015-03-27 00:52:11 +08:00
|
|
|
def get_filter_kwargs_for_object(self, obj):
|
|
|
|
"""
|
|
|
|
Return a dict that when passed as kwargs to self.model.filter(), would
|
|
|
|
yield all instances having the same value for this field as obj has.
|
|
|
|
"""
|
|
|
|
return {self.name: getattr(obj, self.attname)}
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def get_attname(self):
|
|
|
|
return self.name
|
|
|
|
|
2005-11-10 07:37:41 +08:00
|
|
|
def get_attname_column(self):
|
2006-05-02 09:31:56 +08:00
|
|
|
attname = self.get_attname()
|
2005-11-10 07:37:41 +08:00
|
|
|
column = self.db_column or attname
|
|
|
|
return attname, column
|
2005-08-26 06:51:30 +08:00
|
|
|
|
2005-09-29 07:08:47 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return self.__class__.__name__
|
|
|
|
|
2006-05-30 01:08:58 +08:00
|
|
|
def pre_save(self, model_instance, add):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Return field's value just before saving."""
|
2006-05-30 01:08:58 +08:00
|
|
|
return getattr(model_instance, self.attname)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Perform preliminary non-db specific value checks and conversions."""
|
2013-05-03 22:02:10 +08:00
|
|
|
if isinstance(value, Promise):
|
|
|
|
value = value._proxy____cast()
|
2009-12-22 23:18:51 +08:00
|
|
|
return value
|
|
|
|
|
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""
|
|
|
|
Return field's value prepared for interacting with the database backend.
|
2008-07-29 13:09:29 +08:00
|
|
|
|
2016-04-24 01:13:31 +08:00
|
|
|
Used by the default implementations of get_db_prep_save().
|
2008-07-29 13:09:29 +08:00
|
|
|
"""
|
2009-12-22 23:18:51 +08:00
|
|
|
if not prepared:
|
|
|
|
value = self.get_prep_value(value)
|
2008-07-29 13:09:29 +08:00
|
|
|
return value
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_db_prep_save(self, value, connection):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Return field's value prepared for saving into a database."""
|
|
|
|
return self.get_db_prep_value(value, connection=connection, prepared=False)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
def has_default(self):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Return a boolean of whether this field has a default value."""
|
2006-03-01 11:51:55 +08:00
|
|
|
return self.default is not NOT_PROVIDED
|
2005-08-02 05:29:52 +08:00
|
|
|
|
|
|
|
def get_default(self):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Return the default value for this field."""
|
2016-12-16 02:42:44 +08:00
|
|
|
return self._get_default()
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def _get_default(self):
|
2008-09-02 05:28:32 +08:00
|
|
|
if self.has_default():
|
2006-05-02 09:31:56 +08:00
|
|
|
if callable(self.default):
|
2016-12-16 02:42:44 +08:00
|
|
|
return self.default
|
|
|
|
return lambda: self.default
|
|
|
|
|
2016-03-29 06:33:29 +08:00
|
|
|
if (
|
|
|
|
not self.empty_strings_allowed
|
|
|
|
or self.null
|
|
|
|
and not connection.features.interprets_empty_strings_as_nulls
|
|
|
|
):
|
2016-12-16 02:42:44 +08:00
|
|
|
return return_None
|
2017-01-25 07:04:12 +08:00
|
|
|
return str # return empty string
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2018-10-19 21:41:29 +08:00
|
|
|
def get_choices(
|
|
|
|
self,
|
|
|
|
include_blank=True,
|
|
|
|
blank_choice=BLANK_CHOICE_DASH,
|
|
|
|
limit_choices_to=None,
|
|
|
|
ordering=(),
|
|
|
|
):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""
|
|
|
|
Return choices with a default blank choices included, for use
|
|
|
|
as <select> choices for this field.
|
|
|
|
"""
|
2019-01-05 04:03:53 +08:00
|
|
|
if self.choices is not None:
|
2017-11-12 08:38:29 +08:00
|
|
|
choices = list(self.choices)
|
|
|
|
if include_blank:
|
2018-03-22 21:05:31 +08:00
|
|
|
blank_defined = any(
|
|
|
|
choice in ("", None) for choice, _ in self.flatchoices
|
|
|
|
)
|
2017-11-12 08:38:29 +08:00
|
|
|
if not blank_defined:
|
|
|
|
choices = blank_choice + choices
|
|
|
|
return choices
|
2015-02-26 22:19:17 +08:00
|
|
|
rel_model = self.remote_field.model
|
2014-05-21 18:32:19 +08:00
|
|
|
limit_choices_to = limit_choices_to or self.get_limit_choices_to()
|
2017-11-12 08:38:29 +08:00
|
|
|
choice_func = operator.attrgetter(
|
|
|
|
self.remote_field.get_related_field().attname
|
|
|
|
if hasattr(self.remote_field, "get_related_field")
|
|
|
|
else "pk"
|
|
|
|
)
|
2019-08-15 12:54:41 +08:00
|
|
|
qs = rel_model._default_manager.complex_filter(limit_choices_to)
|
|
|
|
if ordering:
|
|
|
|
qs = qs.order_by(*ordering)
|
2017-11-12 08:38:29 +08:00
|
|
|
return (blank_choice if include_blank else []) + [
|
2019-08-15 12:54:41 +08:00
|
|
|
(choice_func(x), str(x)) for x in qs
|
2017-11-12 08:38:29 +08:00
|
|
|
]
|
2005-11-26 05:20:09 +08:00
|
|
|
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
def value_to_string(self, obj):
|
2005-11-26 05:20:09 +08:00
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Return a string value of this field from the passed obj.
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
This is used by the serialization framework.
|
2005-11-26 05:20:09 +08:00
|
|
|
"""
|
2017-04-22 01:52:26 +08:00
|
|
|
return str(self.value_from_object(obj))
|
2005-11-26 05:20:09 +08:00
|
|
|
|
2008-07-19 15:53:02 +08:00
|
|
|
def _get_flatchoices(self):
|
2008-07-27 15:22:39 +08:00
|
|
|
"""Flattened version of choices tuple."""
|
2019-01-05 04:03:53 +08:00
|
|
|
if self.choices is None:
|
|
|
|
return []
|
2008-07-19 15:53:02 +08:00
|
|
|
flat = []
|
2008-07-27 15:22:39 +08:00
|
|
|
for choice, value in self.choices:
|
2010-02-24 02:27:51 +08:00
|
|
|
if isinstance(value, (list, tuple)):
|
2008-07-19 15:53:02 +08:00
|
|
|
flat.extend(value)
|
|
|
|
else:
|
2013-07-08 08:39:54 +08:00
|
|
|
flat.append((choice, value))
|
2008-07-19 15:53:02 +08:00
|
|
|
return flat
|
2022-02-04 03:24:19 +08:00
|
|
|
|
2008-07-19 15:53:02 +08:00
|
|
|
flatchoices = property(_get_flatchoices)
|
2008-07-27 15:22:39 +08:00
|
|
|
|
2007-08-06 21:58:56 +08:00
|
|
|
def save_form_data(self, instance, data):
|
|
|
|
setattr(instance, self.name, data)
|
2007-09-08 13:11:17 +08:00
|
|
|
|
2013-08-30 11:44:37 +08:00
|
|
|
def formfield(self, form_class=None, choices_form_class=None, **kwargs):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Return a django.forms.Field instance for this field."""
|
2019-01-03 07:18:19 +08:00
|
|
|
defaults = {
|
|
|
|
"required": not self.blank,
|
|
|
|
"label": capfirst(self.verbose_name),
|
|
|
|
"help_text": self.help_text,
|
|
|
|
}
|
2008-09-02 03:20:03 +08:00
|
|
|
if self.has_default():
|
2008-09-02 05:28:32 +08:00
|
|
|
if callable(self.default):
|
2010-03-08 23:03:30 +08:00
|
|
|
defaults["initial"] = self.default
|
2008-09-02 05:28:32 +08:00
|
|
|
defaults["show_hidden_initial"] = True
|
2010-03-08 23:03:30 +08:00
|
|
|
else:
|
|
|
|
defaults["initial"] = self.get_default()
|
2019-01-05 04:03:53 +08:00
|
|
|
if self.choices is not None:
|
2009-01-29 18:46:36 +08:00
|
|
|
# Fields with choices get special treatment.
|
2011-10-13 16:11:00 +08:00
|
|
|
include_blank = self.blank or not (
|
|
|
|
self.has_default() or "initial" in kwargs
|
|
|
|
)
|
2008-09-01 04:11:11 +08:00
|
|
|
defaults["choices"] = self.get_choices(include_blank=include_blank)
|
|
|
|
defaults["coerce"] = self.to_python
|
|
|
|
if self.null:
|
|
|
|
defaults["empty_value"] = None
|
2013-08-30 11:44:37 +08:00
|
|
|
if choices_form_class is not None:
|
|
|
|
form_class = choices_form_class
|
|
|
|
else:
|
2013-02-24 02:01:38 +08:00
|
|
|
form_class = forms.TypedChoiceField
|
2008-09-02 03:20:03 +08:00
|
|
|
# Many of the subclass-specific formfield arguments (min_value,
|
|
|
|
# max_value) don't apply for choice fields, so be sure to only pass
|
|
|
|
# the values that TypedChoiceField will understand.
|
2012-08-08 22:33:15 +08:00
|
|
|
for k in list(kwargs):
|
2008-09-02 03:20:03 +08:00
|
|
|
if k not in (
|
|
|
|
"coerce",
|
|
|
|
"empty_value",
|
|
|
|
"choices",
|
|
|
|
"required",
|
|
|
|
"widget",
|
|
|
|
"label",
|
|
|
|
"initial",
|
|
|
|
"help_text",
|
2017-03-22 07:29:14 +08:00
|
|
|
"error_messages",
|
|
|
|
"show_hidden_initial",
|
|
|
|
"disabled",
|
|
|
|
):
|
2008-09-02 03:20:03 +08:00
|
|
|
del kwargs[k]
|
2007-01-22 14:32:14 +08:00
|
|
|
defaults.update(kwargs)
|
2013-02-24 02:01:38 +08:00
|
|
|
if form_class is None:
|
|
|
|
form_class = forms.CharField
|
2007-04-28 21:55:24 +08:00
|
|
|
return form_class(**defaults)
|
2006-12-15 13:46:11 +08:00
|
|
|
|
2006-12-28 10:27:14 +08:00
|
|
|
def value_from_object(self, obj):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""Return the value of this field in the given model instance."""
|
2006-12-28 10:27:14 +08:00
|
|
|
return getattr(obj, self.attname)
|
|
|
|
|
2013-05-18 19:48:57 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class BooleanField(Field):
|
2009-04-11 08:06:53 +08:00
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2019-06-28 00:39:47 +08:00
|
|
|
"invalid": _("“%(value)s” value must be either True or False."),
|
|
|
|
"invalid_nullable": _("“%(value)s” value must be either True, False, or None."),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
|
|
|
description = _("Boolean (Either True or False)")
|
2012-02-10 02:57:54 +08:00
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "BooleanField"
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def to_python(self, value):
|
2017-05-06 22:56:28 +08:00
|
|
|
if self.null and value in self.empty_values:
|
|
|
|
return None
|
2010-02-25 01:36:18 +08:00
|
|
|
if value in (True, False):
|
2018-08-01 23:48:21 +08:00
|
|
|
# 1/0 are equal to True/False. bool() converts former to latter.
|
2010-02-25 01:36:18 +08:00
|
|
|
return bool(value)
|
|
|
|
if value in ("t", "True", "1"):
|
|
|
|
return True
|
|
|
|
if value in ("f", "False", "0"):
|
|
|
|
return False
|
2013-06-06 02:55:05 +08:00
|
|
|
raise exceptions.ValidationError(
|
2017-05-06 22:56:28 +08:00
|
|
|
self.error_messages["invalid_nullable" if self.null else "invalid"],
|
2013-06-06 02:55:05 +08:00
|
|
|
code="invalid",
|
|
|
|
params={"value": value},
|
|
|
|
)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().get_prep_value(value)
|
2008-07-29 13:09:29 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
2016-04-24 01:13:31 +08:00
|
|
|
return self.to_python(value)
|
2008-07-29 13:09:29 +08:00
|
|
|
|
2007-01-22 14:32:14 +08:00
|
|
|
def formfield(self, **kwargs):
|
2019-01-05 04:03:53 +08:00
|
|
|
if self.choices is not None:
|
2014-08-05 07:54:44 +08:00
|
|
|
include_blank = not (self.has_default() or "initial" in kwargs)
|
2013-07-08 08:39:54 +08:00
|
|
|
defaults = {"choices": self.get_choices(include_blank=include_blank)}
|
2009-04-11 03:54:31 +08:00
|
|
|
else:
|
2017-05-06 22:56:28 +08:00
|
|
|
form_class = forms.NullBooleanField if self.null else forms.BooleanField
|
|
|
|
# In HTML checkboxes, 'required' means "must be checked" which is
|
|
|
|
# different from the choices case ("must select some value").
|
|
|
|
# required=False allows unchecked checkboxes.
|
|
|
|
defaults = {"form_class": form_class, "required": False}
|
|
|
|
return super().formfield(**{**defaults, **kwargs})
|
2006-12-16 02:32:42 +08:00
|
|
|
|
2021-12-19 18:22:30 +08:00
|
|
|
def select_format(self, compiler, sql, params):
|
|
|
|
sql, params = super().select_format(compiler, sql, params)
|
|
|
|
# Filters that match everything are handled as empty strings in the
|
|
|
|
# WHERE clause, but in SELECT or GROUP BY list they must use a
|
|
|
|
# predicate that's always True.
|
|
|
|
if sql == "":
|
|
|
|
sql = "1"
|
|
|
|
return sql, params
|
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class CharField(Field):
|
2010-01-05 11:56:19 +08:00
|
|
|
description = _("String (up to %(max_length)s)")
|
|
|
|
|
2020-07-18 19:17:39 +08:00
|
|
|
def __init__(self, *args, db_collation=None, **kwargs):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(*args, **kwargs)
|
2020-07-18 19:17:39 +08:00
|
|
|
self.db_collation = db_collation
|
2022-01-03 19:29:24 +08:00
|
|
|
if self.max_length is not None:
|
|
|
|
self.validators.append(validators.MaxLengthValidator(self.max_length))
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2014-01-20 10:45:21 +08:00
|
|
|
def check(self, **kwargs):
|
2020-07-18 19:17:39 +08:00
|
|
|
databases = kwargs.get("databases") or []
|
2017-12-11 20:08:45 +08:00
|
|
|
return [
|
|
|
|
*super().check(**kwargs),
|
2020-07-18 19:17:39 +08:00
|
|
|
*self._check_db_collation(databases),
|
2017-12-11 20:08:45 +08:00
|
|
|
*self._check_max_length_attribute(**kwargs),
|
|
|
|
]
|
2014-01-20 10:45:21 +08:00
|
|
|
|
2014-03-05 03:32:21 +08:00
|
|
|
def _check_max_length_attribute(self, **kwargs):
|
2015-05-19 17:43:06 +08:00
|
|
|
if self.max_length is None:
|
2014-01-20 10:45:21 +08:00
|
|
|
return [
|
|
|
|
checks.Error(
|
2014-03-03 18:18:39 +08:00
|
|
|
"CharFields must define a 'max_length' attribute.",
|
2014-01-20 10:45:21 +08:00
|
|
|
obj=self,
|
2014-03-03 18:18:39 +08:00
|
|
|
id="fields.E120",
|
2014-01-20 10:45:21 +08:00
|
|
|
)
|
|
|
|
]
|
2017-04-25 06:49:31 +08:00
|
|
|
elif (
|
|
|
|
not isinstance(self.max_length, int)
|
|
|
|
or isinstance(self.max_length, bool)
|
|
|
|
or self.max_length <= 0
|
|
|
|
):
|
2014-01-20 10:45:21 +08:00
|
|
|
return [
|
|
|
|
checks.Error(
|
2014-03-03 18:18:39 +08:00
|
|
|
"'max_length' must be a positive integer.",
|
2014-01-20 10:45:21 +08:00
|
|
|
obj=self,
|
2014-03-03 18:18:39 +08:00
|
|
|
id="fields.E121",
|
2014-01-20 10:45:21 +08:00
|
|
|
)
|
|
|
|
]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
2020-07-18 19:17:39 +08:00
|
|
|
def _check_db_collation(self, databases):
|
|
|
|
errors = []
|
|
|
|
for db in databases:
|
|
|
|
if not router.allow_migrate_model(db, self.model):
|
|
|
|
continue
|
|
|
|
connection = connections[db]
|
|
|
|
if not (
|
|
|
|
self.db_collation is None
|
|
|
|
or "supports_collation_on_charfield"
|
|
|
|
in self.model._meta.required_db_features
|
|
|
|
or connection.features.supports_collation_on_charfield
|
|
|
|
):
|
|
|
|
errors.append(
|
|
|
|
checks.Error(
|
|
|
|
"%s does not support a database collation on "
|
|
|
|
"CharFields." % connection.display_name,
|
|
|
|
obj=self,
|
|
|
|
id="fields.E190",
|
|
|
|
),
|
|
|
|
)
|
|
|
|
return errors
|
|
|
|
|
2017-07-28 01:36:47 +08:00
|
|
|
def cast_db_type(self, connection):
|
|
|
|
if self.max_length is None:
|
|
|
|
return connection.ops.cast_char_field_without_max_length
|
|
|
|
return super().cast_db_type(connection)
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "CharField"
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def to_python(self, value):
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(value, str) or value is None:
|
2006-05-02 09:31:56 +08:00
|
|
|
return value
|
2017-04-22 01:52:26 +08:00
|
|
|
return str(value)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2010-01-10 06:05:10 +08:00
|
|
|
def get_prep_value(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().get_prep_value(value)
|
2010-01-10 06:05:10 +08:00
|
|
|
return self.to_python(value)
|
2010-03-21 04:01:06 +08:00
|
|
|
|
2007-01-22 14:32:14 +08:00
|
|
|
def formfield(self, **kwargs):
|
2010-01-05 11:56:19 +08:00
|
|
|
# Passing max_length to forms.CharField means that the value's length
|
|
|
|
# will be validated twice. This is considered acceptable since we want
|
|
|
|
# the value in the form field (to pass into widget for example).
|
2007-08-05 13:14:46 +08:00
|
|
|
defaults = {"max_length": self.max_length}
|
2016-05-18 22:30:42 +08:00
|
|
|
# TODO: Handle multiple backends with different feature flags.
|
|
|
|
if self.null and not connection.features.interprets_empty_strings_as_nulls:
|
|
|
|
defaults["empty_value"] = None
|
2007-01-22 14:32:14 +08:00
|
|
|
defaults.update(kwargs)
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().formfield(**defaults)
|
2006-12-16 02:32:42 +08:00
|
|
|
|
2020-07-18 19:17:39 +08:00
|
|
|
def deconstruct(self):
|
|
|
|
name, path, args, kwargs = super().deconstruct()
|
|
|
|
if self.db_collation:
|
|
|
|
kwargs["db_collation"] = self.db_collation
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class CommaSeparatedIntegerField(CharField):
|
2010-01-05 11:56:19 +08:00
|
|
|
default_validators = [validators.validate_comma_separated_integer_list]
|
|
|
|
description = _("Comma-separated integers")
|
2016-12-31 23:30:41 +08:00
|
|
|
system_check_removed_details = {
|
2016-02-08 07:22:48 +08:00
|
|
|
"msg": (
|
2016-12-31 23:30:41 +08:00
|
|
|
"CommaSeparatedIntegerField is removed except for support in "
|
|
|
|
"historical migrations."
|
2016-02-08 07:22:48 +08:00
|
|
|
),
|
|
|
|
"hint": (
|
2016-12-31 23:30:41 +08:00
|
|
|
"Use CharField(validators=[validate_comma_separated_integer_list]) "
|
|
|
|
"instead."
|
2016-02-08 07:22:48 +08:00
|
|
|
),
|
2016-12-31 23:30:41 +08:00
|
|
|
"id": "fields.E901",
|
2016-02-08 07:22:48 +08:00
|
|
|
}
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2021-07-28 14:50:49 +08:00
|
|
|
def _to_naive(value):
|
|
|
|
if timezone.is_aware(value):
|
2022-03-23 19:15:36 +08:00
|
|
|
value = timezone.make_naive(value, datetime.timezone.utc)
|
2021-07-28 14:50:49 +08:00
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
def _get_naive_now():
|
|
|
|
return _to_naive(timezone.now())
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class DateTimeCheckMixin:
|
2014-03-13 19:32:20 +08:00
|
|
|
def check(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return [
|
|
|
|
*super().check(**kwargs),
|
|
|
|
*self._check_mutually_exclusive_options(),
|
|
|
|
*self._check_fix_default_value(),
|
|
|
|
]
|
2014-03-13 19:32:20 +08:00
|
|
|
|
|
|
|
def _check_mutually_exclusive_options(self):
|
|
|
|
# auto_now, auto_now_add, and default are mutually exclusive
|
|
|
|
# options. The use of more than one of these options together
|
|
|
|
# will trigger an Error
|
2016-03-29 06:33:29 +08:00
|
|
|
mutually_exclusive_options = [
|
|
|
|
self.auto_now_add,
|
|
|
|
self.auto_now,
|
|
|
|
self.has_default(),
|
|
|
|
]
|
|
|
|
enabled_options = [
|
|
|
|
option not in (None, False) for option in mutually_exclusive_options
|
|
|
|
].count(True)
|
2014-03-13 19:32:20 +08:00
|
|
|
if enabled_options > 1:
|
|
|
|
return [
|
|
|
|
checks.Error(
|
|
|
|
"The options auto_now, auto_now_add, and default "
|
|
|
|
"are mutually exclusive. Only one of these options "
|
|
|
|
"may be present.",
|
|
|
|
obj=self,
|
2014-05-16 21:41:17 +08:00
|
|
|
id="fields.E160",
|
2014-03-13 19:32:20 +08:00
|
|
|
)
|
|
|
|
]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
2014-02-22 21:29:43 +08:00
|
|
|
def _check_fix_default_value(self):
|
|
|
|
return []
|
|
|
|
|
2021-07-29 13:47:24 +08:00
|
|
|
# Concrete subclasses use this in their implementations of
|
|
|
|
# _check_fix_default_value().
|
|
|
|
def _check_if_value_fixed(self, value, now=None):
|
|
|
|
"""
|
|
|
|
Check if the given value appears to have been provided as a "fixed"
|
|
|
|
time value, and include a warning in the returned list if it does. The
|
|
|
|
value argument must be a date object or aware/naive datetime object. If
|
|
|
|
now is provided, it must be a naive datetime object.
|
|
|
|
"""
|
|
|
|
if now is None:
|
|
|
|
now = _get_naive_now()
|
|
|
|
offset = datetime.timedelta(seconds=10)
|
|
|
|
lower = now - offset
|
|
|
|
upper = now + offset
|
|
|
|
if isinstance(value, datetime.datetime):
|
|
|
|
value = _to_naive(value)
|
|
|
|
else:
|
|
|
|
assert isinstance(value, datetime.date)
|
|
|
|
lower = lower.date()
|
|
|
|
upper = upper.date()
|
|
|
|
if lower <= value <= upper:
|
|
|
|
return [
|
|
|
|
checks.Warning(
|
|
|
|
"Fixed default value provided.",
|
|
|
|
hint=(
|
|
|
|
"It seems you set a fixed date / time / datetime "
|
|
|
|
"value as default for this field. This may not be "
|
|
|
|
"what you want. If you want to have the current date "
|
|
|
|
"as default, use `django.utils.timezone.now`"
|
|
|
|
),
|
|
|
|
obj=self,
|
|
|
|
id="fields.W161",
|
|
|
|
)
|
|
|
|
]
|
|
|
|
return []
|
|
|
|
|
2014-03-13 19:32:20 +08:00
|
|
|
|
|
|
|
class DateField(DateTimeCheckMixin, Field):
|
2005-08-02 05:29:52 +08:00
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2019-06-28 00:39:47 +08:00
|
|
|
"invalid": _(
|
|
|
|
"“%(value)s” value has an invalid date format. It must be "
|
|
|
|
"in YYYY-MM-DD format."
|
|
|
|
),
|
|
|
|
"invalid_date": _(
|
|
|
|
"“%(value)s” value has the correct format (YYYY-MM-DD) "
|
|
|
|
"but it is an invalid date."
|
|
|
|
),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
2011-11-18 21:01:06 +08:00
|
|
|
description = _("Date (without time)")
|
|
|
|
|
2011-10-13 16:11:00 +08:00
|
|
|
def __init__(
|
|
|
|
self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs
|
|
|
|
):
|
2005-08-02 05:29:52 +08:00
|
|
|
self.auto_now, self.auto_now_add = auto_now, auto_now_add
|
|
|
|
if auto_now or auto_now_add:
|
|
|
|
kwargs["editable"] = False
|
2005-11-26 05:20:09 +08:00
|
|
|
kwargs["blank"] = True
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(verbose_name, name, **kwargs)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2014-02-22 21:29:43 +08:00
|
|
|
def _check_fix_default_value(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Warn that using an actual date or datetime value is probably wrong;
|
|
|
|
it's only evaluated on server startup.
|
2014-02-22 21:29:43 +08:00
|
|
|
"""
|
|
|
|
if not self.has_default():
|
|
|
|
return []
|
|
|
|
|
|
|
|
value = self.default
|
|
|
|
if isinstance(value, datetime.datetime):
|
2021-07-28 15:11:13 +08:00
|
|
|
value = _to_naive(value).date()
|
2014-02-22 21:29:43 +08:00
|
|
|
elif isinstance(value, datetime.date):
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
# No explicit date / datetime value -- no checks necessary
|
|
|
|
return []
|
2021-07-28 15:11:13 +08:00
|
|
|
# At this point, value is a date object.
|
2021-07-29 13:47:24 +08:00
|
|
|
return self._check_if_value_fixed(value)
|
2014-02-22 21:29:43 +08:00
|
|
|
|
2013-05-18 19:48:57 +08:00
|
|
|
def deconstruct(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2013-05-18 19:48:57 +08:00
|
|
|
if self.auto_now:
|
|
|
|
kwargs["auto_now"] = True
|
|
|
|
if self.auto_now_add:
|
|
|
|
kwargs["auto_now_add"] = True
|
2014-01-17 18:45:31 +08:00
|
|
|
if self.auto_now or self.auto_now_add:
|
2013-05-18 19:48:57 +08:00
|
|
|
del kwargs["editable"]
|
|
|
|
del kwargs["blank"]
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "DateField"
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def to_python(self, value):
|
2007-02-26 13:07:12 +08:00
|
|
|
if value is None:
|
|
|
|
return value
|
2006-05-02 09:31:56 +08:00
|
|
|
if isinstance(value, datetime.datetime):
|
2012-05-01 16:40:25 +08:00
|
|
|
if settings.USE_TZ and timezone.is_aware(value):
|
2012-06-01 14:09:58 +08:00
|
|
|
# Convert aware datetimes to the default time zone
|
2012-05-01 16:40:25 +08:00
|
|
|
# before casting them to dates (#17742).
|
|
|
|
default_timezone = timezone.get_default_timezone()
|
|
|
|
value = timezone.make_naive(value, default_timezone)
|
2006-05-02 09:31:56 +08:00
|
|
|
return value.date()
|
|
|
|
if isinstance(value, datetime.date):
|
|
|
|
return value
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
|
2006-07-01 02:57:23 +08:00
|
|
|
try:
|
2011-11-18 21:01:06 +08:00
|
|
|
parsed = parse_date(value)
|
|
|
|
if parsed is not None:
|
|
|
|
return parsed
|
|
|
|
except ValueError:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise exceptions.ValidationError(
|
|
|
|
self.error_messages["invalid_date"],
|
|
|
|
code="invalid_date",
|
|
|
|
params={"value": value},
|
|
|
|
)
|
|
|
|
|
|
|
|
raise exceptions.ValidationError(
|
|
|
|
self.error_messages["invalid"],
|
|
|
|
code="invalid",
|
|
|
|
params={"value": value},
|
|
|
|
)
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2006-05-30 01:08:58 +08:00
|
|
|
def pre_save(self, model_instance, add):
|
2005-08-10 11:50:46 +08:00
|
|
|
if self.auto_now or (self.auto_now_add and add):
|
2010-10-09 00:14:10 +08:00
|
|
|
value = datetime.date.today()
|
2006-05-30 01:08:58 +08:00
|
|
|
setattr(model_instance, self.attname, value)
|
|
|
|
return value
|
|
|
|
else:
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().pre_save(model_instance, add)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2014-07-23 17:41:06 +08:00
|
|
|
def contribute_to_class(self, cls, name, **kwargs):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().contribute_to_class(cls, name, **kwargs)
|
2006-05-02 09:31:56 +08:00
|
|
|
if not self.null:
|
2016-03-29 06:33:29 +08:00
|
|
|
setattr(
|
|
|
|
cls,
|
|
|
|
"get_next_by_%s" % self.name,
|
2017-09-07 01:11:18 +08:00
|
|
|
partialmethod(
|
|
|
|
cls._get_next_or_previous_by_FIELD, field=self, is_next=True
|
2022-02-04 03:24:19 +08:00
|
|
|
),
|
2016-03-29 06:33:29 +08:00
|
|
|
)
|
|
|
|
setattr(
|
|
|
|
cls,
|
|
|
|
"get_previous_by_%s" % self.name,
|
2017-09-07 01:11:18 +08:00
|
|
|
partialmethod(
|
|
|
|
cls._get_next_or_previous_by_FIELD, field=self, is_next=False
|
2022-02-04 03:24:19 +08:00
|
|
|
),
|
2016-03-29 06:33:29 +08:00
|
|
|
)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().get_prep_value(value)
|
2009-12-22 23:18:51 +08:00
|
|
|
return self.to_python(value)
|
2008-08-25 11:17:06 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
2008-07-29 13:09:29 +08:00
|
|
|
# Casts dates into the format expected by the backend
|
2009-12-22 23:18:51 +08:00
|
|
|
if not prepared:
|
|
|
|
value = self.get_prep_value(value)
|
2015-05-03 03:27:44 +08:00
|
|
|
return connection.ops.adapt_datefield_value(value)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
def value_to_string(self, obj):
|
2015-04-26 14:30:46 +08:00
|
|
|
val = self.value_from_object(obj)
|
2011-11-18 21:01:06 +08:00
|
|
|
return "" if val is None else val.isoformat()
|
2005-11-26 05:20:09 +08:00
|
|
|
|
2007-01-22 14:32:14 +08:00
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
|
|
|
"form_class": forms.DateField,
|
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2006-12-16 02:32:42 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class DateTimeField(DateField):
|
2011-11-18 21:01:06 +08:00
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2019-06-28 00:39:47 +08:00
|
|
|
"invalid": _(
|
|
|
|
"“%(value)s” value has an invalid format. It must be in "
|
|
|
|
"YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."
|
|
|
|
),
|
|
|
|
"invalid_date": _(
|
|
|
|
"“%(value)s” value has the correct format "
|
2012-06-08 00:08:47 +08:00
|
|
|
"(YYYY-MM-DD) but it is an invalid date."
|
|
|
|
),
|
2019-06-28 00:39:47 +08:00
|
|
|
"invalid_datetime": _(
|
|
|
|
"“%(value)s” value has the correct format "
|
|
|
|
"(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
|
|
|
|
"but it is an invalid date/time."
|
|
|
|
),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
|
|
|
description = _("Date (with time)")
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
# __init__ is inherited from DateField
|
|
|
|
|
2014-02-22 21:29:43 +08:00
|
|
|
def _check_fix_default_value(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Warn that using an actual date or datetime value is probably wrong;
|
|
|
|
it's only evaluated on server startup.
|
2014-02-22 21:29:43 +08:00
|
|
|
"""
|
|
|
|
if not self.has_default():
|
|
|
|
return []
|
|
|
|
|
|
|
|
value = self.default
|
2021-07-29 13:47:24 +08:00
|
|
|
if isinstance(value, (datetime.datetime, datetime.date)):
|
|
|
|
return self._check_if_value_fixed(value)
|
|
|
|
# No explicit date / datetime value -- no checks necessary.
|
2014-02-22 21:29:43 +08:00
|
|
|
return []
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "DateTimeField"
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def to_python(self, value):
|
2007-02-26 13:07:12 +08:00
|
|
|
if value is None:
|
|
|
|
return value
|
2006-05-02 09:31:56 +08:00
|
|
|
if isinstance(value, datetime.datetime):
|
|
|
|
return value
|
|
|
|
if isinstance(value, datetime.date):
|
2012-01-24 18:00:39 +08:00
|
|
|
value = datetime.datetime(value.year, value.month, value.day)
|
|
|
|
if settings.USE_TZ:
|
2012-01-24 18:32:28 +08:00
|
|
|
# For backwards compatibility, interpret naive datetimes in
|
|
|
|
# local time. This won't work during DST change, but we can't
|
|
|
|
# do much about it, so we let the exceptions percolate up the
|
|
|
|
# call stack.
|
2013-10-13 17:54:11 +08:00
|
|
|
warnings.warn(
|
|
|
|
"DateTimeField %s.%s received a naive datetime "
|
|
|
|
"(%s) while time zone support is active."
|
|
|
|
% (self.model.__name__, self.name, value),
|
2012-01-24 18:32:28 +08:00
|
|
|
RuntimeWarning,
|
|
|
|
)
|
2012-01-24 18:00:39 +08:00
|
|
|
default_timezone = timezone.get_default_timezone()
|
|
|
|
value = timezone.make_aware(value, default_timezone)
|
|
|
|
return value
|
2008-07-29 13:09:29 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
try:
|
|
|
|
parsed = parse_datetime(value)
|
|
|
|
if parsed is not None:
|
|
|
|
return parsed
|
|
|
|
except ValueError:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise exceptions.ValidationError(
|
|
|
|
self.error_messages["invalid_datetime"],
|
|
|
|
code="invalid_datetime",
|
|
|
|
params={"value": value},
|
|
|
|
)
|
2011-11-18 21:01:06 +08:00
|
|
|
|
|
|
|
try:
|
|
|
|
parsed = parse_date(value)
|
|
|
|
if parsed is not None:
|
|
|
|
return datetime.datetime(parsed.year, parsed.month, parsed.day)
|
2006-05-02 09:31:56 +08:00
|
|
|
except ValueError:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise exceptions.ValidationError(
|
|
|
|
self.error_messages["invalid_date"],
|
|
|
|
code="invalid_date",
|
|
|
|
params={"value": value},
|
|
|
|
)
|
|
|
|
|
|
|
|
raise exceptions.ValidationError(
|
|
|
|
self.error_messages["invalid"],
|
|
|
|
code="invalid",
|
|
|
|
params={"value": value},
|
|
|
|
)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
2010-10-09 00:14:10 +08:00
|
|
|
def pre_save(self, model_instance, add):
|
|
|
|
if self.auto_now or (self.auto_now_add and add):
|
2011-11-18 21:01:06 +08:00
|
|
|
value = timezone.now()
|
2010-10-09 00:14:10 +08:00
|
|
|
setattr(model_instance, self.attname, value)
|
|
|
|
return value
|
|
|
|
else:
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().pre_save(model_instance, add)
|
2010-10-09 00:14:10 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
# contribute_to_class is inherited from DateField, it registers
|
|
|
|
# get_next_by_FOO and get_prev_by_FOO
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().get_prep_value(value)
|
2011-11-18 21:01:06 +08:00
|
|
|
value = self.to_python(value)
|
2011-11-25 17:25:43 +08:00
|
|
|
if value is not None and settings.USE_TZ and timezone.is_naive(value):
|
2011-11-18 21:01:06 +08:00
|
|
|
# For backwards compatibility, interpret naive datetimes in local
|
|
|
|
# time. This won't work during DST change, but we can't do much
|
|
|
|
# about it, so we let the exceptions percolate up the call stack.
|
2014-10-09 03:12:42 +08:00
|
|
|
try:
|
|
|
|
name = "%s.%s" % (self.model.__name__, self.name)
|
|
|
|
except AttributeError:
|
|
|
|
name = "(unbound)"
|
|
|
|
warnings.warn(
|
|
|
|
"DateTimeField %s received a naive datetime (%s)"
|
2013-10-13 17:54:11 +08:00
|
|
|
" while time zone support is active." % (name, value),
|
2011-11-20 07:27:20 +08:00
|
|
|
RuntimeWarning,
|
|
|
|
)
|
2011-11-18 21:01:06 +08:00
|
|
|
default_timezone = timezone.get_default_timezone()
|
|
|
|
value = timezone.make_aware(value, default_timezone)
|
|
|
|
return value
|
2009-12-22 23:18:51 +08:00
|
|
|
|
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
2011-11-18 21:01:06 +08:00
|
|
|
# Casts datetimes into the format expected by the backend
|
2009-12-22 23:18:51 +08:00
|
|
|
if not prepared:
|
|
|
|
value = self.get_prep_value(value)
|
2015-05-03 03:27:44 +08:00
|
|
|
return connection.ops.adapt_datetimefield_value(value)
|
2006-05-02 09:31:56 +08:00
|
|
|
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
def value_to_string(self, obj):
|
2015-04-26 14:30:46 +08:00
|
|
|
val = self.value_from_object(obj)
|
2011-11-18 21:01:06 +08:00
|
|
|
return "" if val is None else val.isoformat()
|
2005-11-26 05:20:09 +08:00
|
|
|
|
2007-01-22 14:32:14 +08:00
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
|
|
|
"form_class": forms.DateTimeField,
|
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2006-12-16 02:32:42 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2007-05-21 09:29:58 +08:00
|
|
|
class DecimalField(Field):
|
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2019-06-28 00:39:47 +08:00
|
|
|
"invalid": _("“%(value)s” value must be a decimal number."),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
|
|
|
description = _("Decimal number")
|
|
|
|
|
2011-10-13 16:11:00 +08:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
verbose_name=None,
|
|
|
|
name=None,
|
|
|
|
max_digits=None,
|
|
|
|
decimal_places=None,
|
|
|
|
**kwargs,
|
|
|
|
):
|
2007-05-21 09:29:58 +08:00
|
|
|
self.max_digits, self.decimal_places = max_digits, decimal_places
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(verbose_name, name, **kwargs)
|
2007-05-21 09:29:58 +08:00
|
|
|
|
2014-01-20 10:45:21 +08:00
|
|
|
def check(self, **kwargs):
|
2017-01-21 21:13:44 +08:00
|
|
|
errors = super().check(**kwargs)
|
2014-01-20 10:45:21 +08:00
|
|
|
|
2017-12-11 20:08:45 +08:00
|
|
|
digits_errors = [
|
|
|
|
*self._check_decimal_places(),
|
|
|
|
*self._check_max_digits(),
|
|
|
|
]
|
2014-03-03 18:18:39 +08:00
|
|
|
if not digits_errors:
|
|
|
|
errors.extend(self._check_decimal_places_and_max_digits(**kwargs))
|
|
|
|
else:
|
|
|
|
errors.extend(digits_errors)
|
2014-01-20 10:45:21 +08:00
|
|
|
return errors
|
|
|
|
|
2014-03-03 18:18:39 +08:00
|
|
|
def _check_decimal_places(self):
|
2014-01-20 10:45:21 +08:00
|
|
|
try:
|
|
|
|
decimal_places = int(self.decimal_places)
|
|
|
|
if decimal_places < 0:
|
|
|
|
raise ValueError()
|
|
|
|
except TypeError:
|
|
|
|
return [
|
|
|
|
checks.Error(
|
2014-03-03 18:18:39 +08:00
|
|
|
"DecimalFields must define a 'decimal_places' attribute.",
|
2014-01-20 10:45:21 +08:00
|
|
|
obj=self,
|
2014-03-03 18:18:39 +08:00
|
|
|
id="fields.E130",
|
2014-01-20 10:45:21 +08:00
|
|
|
)
|
|
|
|
]
|
|
|
|
except ValueError:
|
|
|
|
return [
|
|
|
|
checks.Error(
|
2014-03-03 18:18:39 +08:00
|
|
|
"'decimal_places' must be a non-negative integer.",
|
2014-01-20 10:45:21 +08:00
|
|
|
obj=self,
|
2014-03-03 18:18:39 +08:00
|
|
|
id="fields.E131",
|
2014-01-20 10:45:21 +08:00
|
|
|
)
|
|
|
|
]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
2014-03-03 18:18:39 +08:00
|
|
|
def _check_max_digits(self):
|
2014-01-20 10:45:21 +08:00
|
|
|
try:
|
|
|
|
max_digits = int(self.max_digits)
|
|
|
|
if max_digits <= 0:
|
|
|
|
raise ValueError()
|
|
|
|
except TypeError:
|
|
|
|
return [
|
|
|
|
checks.Error(
|
2014-03-03 18:18:39 +08:00
|
|
|
"DecimalFields must define a 'max_digits' attribute.",
|
2014-01-20 10:45:21 +08:00
|
|
|
obj=self,
|
2014-03-03 18:18:39 +08:00
|
|
|
id="fields.E132",
|
2014-01-20 10:45:21 +08:00
|
|
|
)
|
|
|
|
]
|
|
|
|
except ValueError:
|
|
|
|
return [
|
|
|
|
checks.Error(
|
2014-03-03 18:18:39 +08:00
|
|
|
"'max_digits' must be a positive integer.",
|
2014-01-20 10:45:21 +08:00
|
|
|
obj=self,
|
2014-03-03 18:18:39 +08:00
|
|
|
id="fields.E133",
|
2014-01-20 10:45:21 +08:00
|
|
|
)
|
|
|
|
]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
2014-03-03 18:18:39 +08:00
|
|
|
def _check_decimal_places_and_max_digits(self, **kwargs):
|
|
|
|
if int(self.decimal_places) > int(self.max_digits):
|
|
|
|
return [
|
|
|
|
checks.Error(
|
|
|
|
"'max_digits' must be greater or equal to 'decimal_places'.",
|
|
|
|
obj=self,
|
|
|
|
id="fields.E134",
|
|
|
|
)
|
|
|
|
]
|
|
|
|
return []
|
|
|
|
|
2015-04-15 06:11:12 +08:00
|
|
|
@cached_property
|
|
|
|
def validators(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().validators + [
|
2015-04-15 06:11:12 +08:00
|
|
|
validators.DecimalValidator(self.max_digits, self.decimal_places)
|
|
|
|
]
|
|
|
|
|
2017-05-03 17:40:09 +08:00
|
|
|
@cached_property
|
|
|
|
def context(self):
|
|
|
|
return decimal.Context(prec=self.max_digits)
|
|
|
|
|
2013-05-18 19:48:57 +08:00
|
|
|
def deconstruct(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2014-03-15 00:20:31 +08:00
|
|
|
if self.max_digits is not None:
|
2013-05-18 19:48:57 +08:00
|
|
|
kwargs["max_digits"] = self.max_digits
|
2014-03-15 00:20:31 +08:00
|
|
|
if self.decimal_places is not None:
|
2013-05-18 19:48:57 +08:00
|
|
|
kwargs["decimal_places"] = self.decimal_places
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "DecimalField"
|
|
|
|
|
2007-05-21 09:29:58 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
if value is None:
|
|
|
|
return value
|
2017-05-03 17:40:09 +08:00
|
|
|
if isinstance(value, float):
|
2021-08-21 23:27:15 +08:00
|
|
|
if math.isnan(value):
|
|
|
|
raise exceptions.ValidationError(
|
|
|
|
self.error_messages["invalid"],
|
|
|
|
code="invalid",
|
|
|
|
params={"value": value},
|
|
|
|
)
|
2017-05-03 17:40:09 +08:00
|
|
|
return self.context.create_decimal_from_float(value)
|
2007-05-21 09:29:58 +08:00
|
|
|
try:
|
|
|
|
return decimal.Decimal(value)
|
2020-06-06 03:13:36 +08:00
|
|
|
except (decimal.InvalidOperation, TypeError, ValueError):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise exceptions.ValidationError(
|
|
|
|
self.error_messages["invalid"],
|
|
|
|
code="invalid",
|
|
|
|
params={"value": value},
|
|
|
|
)
|
2007-05-21 09:29:58 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_db_prep_save(self, value, connection):
|
2016-03-29 06:33:29 +08:00
|
|
|
return connection.ops.adapt_decimalfield_value(
|
|
|
|
self.to_python(value), self.max_digits, self.decimal_places
|
|
|
|
)
|
2007-05-21 09:29:58 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().get_prep_value(value)
|
2009-04-12 13:32:23 +08:00
|
|
|
return self.to_python(value)
|
|
|
|
|
2007-05-21 09:29:58 +08:00
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
2007-05-21 09:29:58 +08:00
|
|
|
"max_digits": self.max_digits,
|
|
|
|
"decimal_places": self.decimal_places,
|
|
|
|
"form_class": forms.DecimalField,
|
2017-12-11 20:08:45 +08:00
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2007-05-21 09:29:58 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2014-07-24 20:57:24 +08:00
|
|
|
class DurationField(Field):
|
2017-01-25 07:04:12 +08:00
|
|
|
"""
|
|
|
|
Store timedelta objects.
|
2014-07-24 20:57:24 +08:00
|
|
|
|
2017-01-25 07:04:12 +08:00
|
|
|
Use interval on PostgreSQL, INTERVAL DAY TO SECOND on Oracle, and bigint
|
2017-02-20 14:35:48 +08:00
|
|
|
of microseconds on other databases.
|
2014-07-24 20:57:24 +08:00
|
|
|
"""
|
2022-02-04 03:24:19 +08:00
|
|
|
|
2014-07-24 20:57:24 +08:00
|
|
|
empty_strings_allowed = False
|
|
|
|
default_error_messages = {
|
2019-06-28 00:39:47 +08:00
|
|
|
"invalid": _(
|
|
|
|
"“%(value)s” value has an invalid format. It must be in "
|
|
|
|
"[DD] [[HH:]MM:]ss[.uuuuuu] format."
|
|
|
|
)
|
2014-07-24 20:57:24 +08:00
|
|
|
}
|
|
|
|
description = _("Duration")
|
|
|
|
|
|
|
|
def get_internal_type(self):
|
|
|
|
return "DurationField"
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
if value is None:
|
|
|
|
return value
|
|
|
|
if isinstance(value, datetime.timedelta):
|
|
|
|
return value
|
|
|
|
try:
|
|
|
|
parsed = parse_duration(value)
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
if parsed is not None:
|
|
|
|
return parsed
|
|
|
|
|
|
|
|
raise exceptions.ValidationError(
|
|
|
|
self.error_messages["invalid"],
|
|
|
|
code="invalid",
|
|
|
|
params={"value": value},
|
|
|
|
)
|
|
|
|
|
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
|
|
|
if connection.features.has_native_duration_field:
|
|
|
|
return value
|
2015-01-02 09:47:49 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
2017-12-29 06:35:41 +08:00
|
|
|
return duration_microseconds(value)
|
2014-07-24 20:57:24 +08:00
|
|
|
|
2014-12-23 18:11:28 +08:00
|
|
|
def get_db_converters(self, connection):
|
|
|
|
converters = []
|
|
|
|
if not connection.features.has_native_duration_field:
|
|
|
|
converters.append(connection.ops.convert_durationfield_value)
|
2017-01-21 21:13:44 +08:00
|
|
|
return converters + super().get_db_converters(connection)
|
2014-12-23 18:11:28 +08:00
|
|
|
|
2014-07-24 20:57:24 +08:00
|
|
|
def value_to_string(self, obj):
|
2015-04-26 14:30:46 +08:00
|
|
|
val = self.value_from_object(obj)
|
2014-07-24 20:57:24 +08:00
|
|
|
return "" if val is None else duration_string(val)
|
|
|
|
|
2015-02-09 21:15:26 +08:00
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
2015-02-09 21:15:26 +08:00
|
|
|
"form_class": forms.DurationField,
|
2017-12-11 20:08:45 +08:00
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2015-02-09 21:15:26 +08:00
|
|
|
|
2014-07-24 20:57:24 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
class EmailField(CharField):
|
2010-01-05 11:56:19 +08:00
|
|
|
default_validators = [validators.validate_email]
|
2012-09-26 20:14:51 +08:00
|
|
|
description = _("Email address")
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2005-11-21 06:41:41 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
2014-07-01 02:34:45 +08:00
|
|
|
# max_length=254 to be compliant with RFCs 3696 and 5321
|
2017-12-04 23:52:27 +08:00
|
|
|
kwargs.setdefault("max_length", 254)
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(*args, **kwargs)
|
2005-11-21 06:41:41 +08:00
|
|
|
|
2013-05-18 19:48:57 +08:00
|
|
|
def deconstruct(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2013-06-22 19:56:37 +08:00
|
|
|
# We do not exclude max_length if it matches default as we want to change
|
|
|
|
# the default in future.
|
2013-05-18 19:48:57 +08:00
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2010-08-05 11:59:20 +08:00
|
|
|
def formfield(self, **kwargs):
|
2011-10-13 16:11:00 +08:00
|
|
|
# As with CharField, this will cause email validation to be performed
|
|
|
|
# twice.
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
2010-08-05 11:59:20 +08:00
|
|
|
"form_class": forms.EmailField,
|
2017-12-11 20:08:45 +08:00
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2010-08-05 11:59:20 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2005-10-12 12:14:21 +08:00
|
|
|
class FilePathField(Field):
|
2010-01-05 11:56:19 +08:00
|
|
|
description = _("File path")
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2011-10-13 16:11:00 +08:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
verbose_name=None,
|
|
|
|
name=None,
|
|
|
|
path="",
|
|
|
|
match=None,
|
2012-04-22 22:44:08 +08:00
|
|
|
recursive=False,
|
|
|
|
allow_files=True,
|
|
|
|
allow_folders=False,
|
|
|
|
**kwargs,
|
|
|
|
):
|
2005-10-12 12:14:21 +08:00
|
|
|
self.path, self.match, self.recursive = path, match, recursive
|
2013-07-08 08:39:54 +08:00
|
|
|
self.allow_files, self.allow_folders = allow_files, allow_folders
|
2017-12-04 23:52:27 +08:00
|
|
|
kwargs.setdefault("max_length", 100)
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(verbose_name, name, **kwargs)
|
2008-06-16 11:15:04 +08:00
|
|
|
|
2014-01-20 10:45:21 +08:00
|
|
|
def check(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return [
|
|
|
|
*super().check(**kwargs),
|
|
|
|
*self._check_allowing_files_or_folders(**kwargs),
|
|
|
|
]
|
2014-01-20 10:45:21 +08:00
|
|
|
|
|
|
|
def _check_allowing_files_or_folders(self, **kwargs):
|
|
|
|
if not self.allow_files and not self.allow_folders:
|
|
|
|
return [
|
|
|
|
checks.Error(
|
2014-03-03 18:18:39 +08:00
|
|
|
"FilePathFields must have either 'allow_files' or 'allow_folders' "
|
|
|
|
"set to True.",
|
2014-01-20 10:45:21 +08:00
|
|
|
obj=self,
|
2014-03-03 18:18:39 +08:00
|
|
|
id="fields.E140",
|
2014-01-20 10:45:21 +08:00
|
|
|
)
|
|
|
|
]
|
|
|
|
return []
|
|
|
|
|
2013-05-18 19:48:57 +08:00
|
|
|
def deconstruct(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2013-05-18 19:48:57 +08:00
|
|
|
if self.path != "":
|
|
|
|
kwargs["path"] = self.path
|
|
|
|
if self.match is not None:
|
|
|
|
kwargs["match"] = self.match
|
|
|
|
if self.recursive is not False:
|
|
|
|
kwargs["recursive"] = self.recursive
|
|
|
|
if self.allow_files is not True:
|
|
|
|
kwargs["allow_files"] = self.allow_files
|
|
|
|
if self.allow_folders is not False:
|
|
|
|
kwargs["allow_folders"] = self.allow_folders
|
2015-05-14 02:51:18 +08:00
|
|
|
if kwargs.get("max_length") == 100:
|
2013-05-18 19:48:57 +08:00
|
|
|
del kwargs["max_length"]
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2014-04-21 04:13:41 +08:00
|
|
|
def get_prep_value(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().get_prep_value(value)
|
2014-04-21 04:13:41 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
2016-12-29 23:27:49 +08:00
|
|
|
return str(value)
|
2014-04-21 04:13:41 +08:00
|
|
|
|
2008-03-20 06:29:11 +08:00
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
2019-05-02 16:42:10 +08:00
|
|
|
"path": self.path() if callable(self.path) else self.path,
|
2008-03-20 06:29:11 +08:00
|
|
|
"match": self.match,
|
|
|
|
"recursive": self.recursive,
|
|
|
|
"form_class": forms.FilePathField,
|
2012-04-22 22:44:08 +08:00
|
|
|
"allow_files": self.allow_files,
|
|
|
|
"allow_folders": self.allow_folders,
|
2017-12-11 20:08:45 +08:00
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2005-10-12 12:14:21 +08:00
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "FilePathField"
|
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class FloatField(Field):
|
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2019-06-28 00:39:47 +08:00
|
|
|
"invalid": _("“%(value)s” value must be a float."),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
|
|
|
description = _("Floating point number")
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().get_prep_value(value)
|
2008-07-29 13:09:29 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
2017-07-13 19:55:23 +08:00
|
|
|
try:
|
|
|
|
return float(value)
|
|
|
|
except (TypeError, ValueError) as e:
|
|
|
|
raise e.__class__(
|
|
|
|
"Field '%s' expected a number but got %r." % (self.name, value),
|
|
|
|
) from e
|
2008-07-29 13:09:29 +08:00
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "FloatField"
|
|
|
|
|
2009-01-03 12:43:58 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
if value is None:
|
|
|
|
return value
|
|
|
|
try:
|
|
|
|
return float(value)
|
|
|
|
except (TypeError, ValueError):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise exceptions.ValidationError(
|
|
|
|
self.error_messages["invalid"],
|
|
|
|
code="invalid",
|
|
|
|
params={"value": value},
|
|
|
|
)
|
2009-01-03 12:43:58 +08:00
|
|
|
|
2007-05-21 09:29:58 +08:00
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
|
|
|
"form_class": forms.FloatField,
|
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class IntegerField(Field):
|
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2019-06-28 00:39:47 +08:00
|
|
|
"invalid": _("“%(value)s” value must be an integer."),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
|
|
|
description = _("Integer")
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2014-11-18 22:03:13 +08:00
|
|
|
def check(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return [
|
|
|
|
*super().check(**kwargs),
|
|
|
|
*self._check_max_length_warning(),
|
|
|
|
]
|
2014-11-18 22:03:13 +08:00
|
|
|
|
|
|
|
def _check_max_length_warning(self):
|
|
|
|
if self.max_length is not None:
|
|
|
|
return [
|
|
|
|
checks.Warning(
|
2017-12-11 23:35:19 +08:00
|
|
|
"'max_length' is ignored when used with %s."
|
|
|
|
% self.__class__.__name__,
|
2014-11-18 22:03:13 +08:00
|
|
|
hint="Remove 'max_length' from field",
|
|
|
|
obj=self,
|
|
|
|
id="fields.W122",
|
|
|
|
)
|
|
|
|
]
|
|
|
|
return []
|
|
|
|
|
2014-03-26 09:40:56 +08:00
|
|
|
@cached_property
|
|
|
|
def validators(self):
|
|
|
|
# These validators can't be added at field initialization time since
|
|
|
|
# they're based on values retrieved from `connection`.
|
2017-01-21 21:13:44 +08:00
|
|
|
validators_ = super().validators
|
2014-03-04 09:12:42 +08:00
|
|
|
internal_type = self.get_internal_type()
|
|
|
|
min_value, max_value = connection.ops.integer_field_range(internal_type)
|
2019-04-06 12:40:46 +08:00
|
|
|
if min_value is not None and not any(
|
|
|
|
(
|
|
|
|
isinstance(validator, validators.MinValueValidator)
|
|
|
|
and (
|
|
|
|
validator.limit_value()
|
|
|
|
if callable(validator.limit_value)
|
|
|
|
else validator.limit_value
|
|
|
|
)
|
|
|
|
>= min_value
|
|
|
|
)
|
|
|
|
for validator in validators_
|
|
|
|
):
|
2017-12-27 02:44:12 +08:00
|
|
|
validators_.append(validators.MinValueValidator(min_value))
|
2019-04-06 12:40:46 +08:00
|
|
|
if max_value is not None and not any(
|
|
|
|
(
|
|
|
|
isinstance(validator, validators.MaxValueValidator)
|
|
|
|
and (
|
|
|
|
validator.limit_value()
|
|
|
|
if callable(validator.limit_value)
|
|
|
|
else validator.limit_value
|
|
|
|
)
|
|
|
|
<= max_value
|
|
|
|
)
|
|
|
|
for validator in validators_
|
|
|
|
):
|
2017-12-27 02:44:12 +08:00
|
|
|
validators_.append(validators.MaxValueValidator(max_value))
|
2016-06-23 17:22:19 +08:00
|
|
|
return validators_
|
2014-03-04 09:12:42 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().get_prep_value(value)
|
2008-07-29 13:09:29 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
2017-07-13 19:55:23 +08:00
|
|
|
try:
|
|
|
|
return int(value)
|
|
|
|
except (TypeError, ValueError) as e:
|
|
|
|
raise e.__class__(
|
|
|
|
"Field '%s' expected a number but got %r." % (self.name, value),
|
|
|
|
) from e
|
2008-07-29 13:09:29 +08:00
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "IntegerField"
|
|
|
|
|
2008-08-24 16:12:13 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
if value is None:
|
|
|
|
return value
|
|
|
|
try:
|
|
|
|
return int(value)
|
|
|
|
except (TypeError, ValueError):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise exceptions.ValidationError(
|
|
|
|
self.error_messages["invalid"],
|
|
|
|
code="invalid",
|
|
|
|
params={"value": value},
|
|
|
|
)
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
|
2007-01-22 14:32:14 +08:00
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
|
|
|
"form_class": forms.IntegerField,
|
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2006-12-16 02:32:42 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2009-12-17 23:10:38 +08:00
|
|
|
class BigIntegerField(IntegerField):
|
2010-01-05 11:56:19 +08:00
|
|
|
description = _("Big (8 byte) integer")
|
2009-12-17 23:10:38 +08:00
|
|
|
MAX_BIGINT = 9223372036854775807
|
2011-06-14 04:15:13 +08:00
|
|
|
|
2009-12-17 23:10:38 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "BigIntegerField"
|
|
|
|
|
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
|
|
|
"min_value": -BigIntegerField.MAX_BIGINT - 1,
|
|
|
|
"max_value": BigIntegerField.MAX_BIGINT,
|
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2009-12-17 23:10:38 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2020-10-24 05:56:12 +08:00
|
|
|
class SmallIntegerField(IntegerField):
|
|
|
|
description = _("Small integer")
|
|
|
|
|
|
|
|
def get_internal_type(self):
|
|
|
|
return "SmallIntegerField"
|
|
|
|
|
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class IPAddressField(Field):
|
2007-06-26 20:59:49 +08:00
|
|
|
empty_strings_allowed = False
|
2011-06-11 21:48:24 +08:00
|
|
|
description = _("IPv4 address")
|
2015-01-18 09:42:41 +08:00
|
|
|
system_check_removed_details = {
|
2015-01-01 23:31:36 +08:00
|
|
|
"msg": (
|
2015-01-18 09:42:41 +08:00
|
|
|
"IPAddressField has been removed except for support in "
|
|
|
|
"historical migrations."
|
2015-01-01 23:31:36 +08:00
|
|
|
),
|
|
|
|
"hint": "Use GenericIPAddressField instead.",
|
2015-01-18 09:42:41 +08:00
|
|
|
"id": "fields.E900",
|
2015-01-01 23:31:36 +08:00
|
|
|
}
|
2011-06-14 04:15:13 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
2007-08-05 13:14:46 +08:00
|
|
|
kwargs["max_length"] = 15
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(*args, **kwargs)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2013-05-18 19:48:57 +08:00
|
|
|
def deconstruct(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2013-05-18 19:48:57 +08:00
|
|
|
del kwargs["max_length"]
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2014-04-21 04:13:41 +08:00
|
|
|
def get_prep_value(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().get_prep_value(value)
|
2014-04-21 04:13:41 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
2016-12-29 23:27:49 +08:00
|
|
|
return str(value)
|
2014-04-21 04:13:41 +08:00
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "IPAddressField"
|
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2011-06-11 21:48:24 +08:00
|
|
|
class GenericIPAddressField(Field):
|
2015-01-05 18:32:25 +08:00
|
|
|
empty_strings_allowed = False
|
2011-06-11 21:48:24 +08:00
|
|
|
description = _("IP address")
|
2011-06-13 12:31:56 +08:00
|
|
|
default_error_messages = {}
|
2011-06-11 21:48:24 +08:00
|
|
|
|
2012-09-02 00:32:27 +08:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
verbose_name=None,
|
|
|
|
name=None,
|
|
|
|
protocol="both",
|
|
|
|
unpack_ipv4=False,
|
|
|
|
*args,
|
|
|
|
**kwargs,
|
|
|
|
):
|
2011-06-11 21:48:24 +08:00
|
|
|
self.unpack_ipv4 = unpack_ipv4
|
2013-05-18 19:48:57 +08:00
|
|
|
self.protocol = protocol
|
2022-02-04 03:24:19 +08:00
|
|
|
(
|
2011-06-11 21:48:24 +08:00
|
|
|
self.default_validators,
|
|
|
|
invalid_error_message,
|
|
|
|
) = validators.ip_address_validators(protocol, unpack_ipv4)
|
|
|
|
self.default_error_messages["invalid"] = invalid_error_message
|
|
|
|
kwargs["max_length"] = 39
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(verbose_name, name, *args, **kwargs)
|
2011-06-11 21:48:24 +08:00
|
|
|
|
2014-01-20 10:45:21 +08:00
|
|
|
def check(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return [
|
|
|
|
*super().check(**kwargs),
|
|
|
|
*self._check_blank_and_null_values(**kwargs),
|
|
|
|
]
|
2014-01-20 10:45:21 +08:00
|
|
|
|
|
|
|
def _check_blank_and_null_values(self, **kwargs):
|
|
|
|
if not getattr(self, "null", False) and getattr(self, "blank", False):
|
|
|
|
return [
|
|
|
|
checks.Error(
|
2016-02-13 00:36:46 +08:00
|
|
|
"GenericIPAddressFields cannot have blank=True if null=False, "
|
|
|
|
"as blank values are stored as nulls.",
|
2014-01-20 10:45:21 +08:00
|
|
|
obj=self,
|
2014-03-03 18:18:39 +08:00
|
|
|
id="fields.E150",
|
2014-01-20 10:45:21 +08:00
|
|
|
)
|
|
|
|
]
|
|
|
|
return []
|
|
|
|
|
2013-05-18 19:48:57 +08:00
|
|
|
def deconstruct(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2013-05-18 19:48:57 +08:00
|
|
|
if self.unpack_ipv4 is not False:
|
|
|
|
kwargs["unpack_ipv4"] = self.unpack_ipv4
|
|
|
|
if self.protocol != "both":
|
|
|
|
kwargs["protocol"] = self.protocol
|
2015-05-14 02:51:18 +08:00
|
|
|
if kwargs.get("max_length") == 39:
|
2013-05-18 19:48:57 +08:00
|
|
|
del kwargs["max_length"]
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2011-06-11 21:48:24 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "GenericIPAddressField"
|
|
|
|
|
|
|
|
def to_python(self, value):
|
2015-04-28 00:22:48 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
2016-12-29 23:27:49 +08:00
|
|
|
if not isinstance(value, str):
|
2017-04-22 01:52:26 +08:00
|
|
|
value = str(value)
|
2015-04-28 00:22:48 +08:00
|
|
|
value = value.strip()
|
|
|
|
if ":" in value:
|
2016-03-29 06:33:29 +08:00
|
|
|
return clean_ipv6_address(
|
|
|
|
value, self.unpack_ipv4, self.error_messages["invalid"]
|
|
|
|
)
|
2011-06-11 21:48:24 +08:00
|
|
|
return value
|
|
|
|
|
2011-06-14 04:15:13 +08:00
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
|
|
|
if not prepared:
|
|
|
|
value = self.get_prep_value(value)
|
2015-05-03 03:27:44 +08:00
|
|
|
return connection.ops.adapt_ipaddressfield_value(value)
|
2011-06-14 04:15:13 +08:00
|
|
|
|
2011-06-11 21:48:24 +08:00
|
|
|
def get_prep_value(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().get_prep_value(value)
|
2014-04-21 04:13:41 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
2011-06-11 21:48:24 +08:00
|
|
|
if value and ":" in value:
|
|
|
|
try:
|
|
|
|
return clean_ipv6_address(value, self.unpack_ipv4)
|
2011-07-29 17:39:35 +08:00
|
|
|
except exceptions.ValidationError:
|
2011-06-11 21:48:24 +08:00
|
|
|
pass
|
2016-12-29 23:27:49 +08:00
|
|
|
return str(value)
|
2011-06-11 21:48:24 +08:00
|
|
|
|
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
2013-07-13 04:05:14 +08:00
|
|
|
"protocol": self.protocol,
|
|
|
|
"form_class": forms.GenericIPAddressField,
|
2017-12-11 20:08:45 +08:00
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2011-06-11 21:48:24 +08:00
|
|
|
|
|
|
|
|
2018-03-20 09:41:04 +08:00
|
|
|
class NullBooleanField(BooleanField):
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2019-06-28 00:39:47 +08:00
|
|
|
"invalid": _("“%(value)s” value must be either None, True or False."),
|
|
|
|
"invalid_nullable": _("“%(value)s” value must be either None, True or False."),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
|
|
|
description = _("Boolean (Either True, False or None)")
|
2021-01-14 04:28:09 +08:00
|
|
|
system_check_removed_details = {
|
2020-03-31 10:16:33 +08:00
|
|
|
"msg": (
|
2021-01-14 04:28:09 +08:00
|
|
|
"NullBooleanField is removed except for support in historical "
|
|
|
|
"migrations."
|
2020-03-31 10:16:33 +08:00
|
|
|
),
|
|
|
|
"hint": "Use BooleanField(null=True) instead.",
|
2021-01-14 04:28:09 +08:00
|
|
|
"id": "fields.E903",
|
2020-03-31 10:16:33 +08:00
|
|
|
}
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
kwargs["null"] = True
|
2010-03-10 15:41:37 +08:00
|
|
|
kwargs["blank"] = True
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(*args, **kwargs)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2013-05-18 19:48:57 +08:00
|
|
|
def deconstruct(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2013-05-18 19:48:57 +08:00
|
|
|
del kwargs["null"]
|
|
|
|
del kwargs["blank"]
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class PositiveIntegerRelDbTypeMixin:
|
2020-10-24 05:56:12 +08:00
|
|
|
def __init_subclass__(cls, **kwargs):
|
|
|
|
super().__init_subclass__(**kwargs)
|
|
|
|
if not hasattr(cls, "integer_field_class"):
|
|
|
|
cls.integer_field_class = next(
|
|
|
|
(
|
|
|
|
parent
|
|
|
|
for parent in cls.__mro__[1:]
|
|
|
|
if issubclass(parent, IntegerField)
|
|
|
|
),
|
|
|
|
None,
|
|
|
|
)
|
2015-11-13 15:56:10 +08:00
|
|
|
|
|
|
|
def rel_db_type(self, connection):
|
|
|
|
"""
|
|
|
|
Return the data type that a related field pointing to this field should
|
|
|
|
use. In most cases, a foreign key pointing to a positive integer
|
|
|
|
primary key will have an integer column data type but some databases
|
|
|
|
(e.g. MySQL) have an unsigned integer type. In that case
|
|
|
|
(related_fields_match_type=True), the primary key should return its
|
|
|
|
db_type.
|
|
|
|
"""
|
|
|
|
if connection.features.related_fields_match_type:
|
|
|
|
return self.db_type(connection)
|
|
|
|
else:
|
2020-10-24 05:56:12 +08:00
|
|
|
return self.integer_field_class().db_type(connection=connection)
|
2015-11-13 15:56:10 +08:00
|
|
|
|
|
|
|
|
2020-10-24 05:56:12 +08:00
|
|
|
class PositiveBigIntegerField(PositiveIntegerRelDbTypeMixin, BigIntegerField):
|
2019-10-16 20:32:12 +08:00
|
|
|
description = _("Positive big integer")
|
|
|
|
|
|
|
|
def get_internal_type(self):
|
|
|
|
return "PositiveBigIntegerField"
|
|
|
|
|
|
|
|
def formfield(self, **kwargs):
|
|
|
|
return super().formfield(
|
|
|
|
**{
|
|
|
|
"min_value": 0,
|
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2015-11-13 15:56:10 +08:00
|
|
|
class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField):
|
2012-02-10 02:57:54 +08:00
|
|
|
description = _("Positive integer")
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "PositiveIntegerField"
|
|
|
|
|
2007-09-15 10:37:07 +08:00
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
|
|
|
"min_value": 0,
|
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2020-10-24 05:56:12 +08:00
|
|
|
class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, SmallIntegerField):
|
2012-02-10 02:57:54 +08:00
|
|
|
description = _("Positive small integer")
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "PositiveSmallIntegerField"
|
|
|
|
|
2007-09-15 10:37:07 +08:00
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
|
|
|
"min_value": 0,
|
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2007-09-15 10:37:07 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2007-09-08 13:09:39 +08:00
|
|
|
class SlugField(CharField):
|
2013-06-14 00:37:08 +08:00
|
|
|
default_validators = [validators.validate_slug]
|
2012-02-10 02:57:54 +08:00
|
|
|
description = _("Slug (up to %(max_length)s)")
|
|
|
|
|
2017-02-02 00:41:56 +08:00
|
|
|
def __init__(
|
|
|
|
self, *args, max_length=50, db_index=True, allow_unicode=False, **kwargs
|
|
|
|
):
|
|
|
|
self.allow_unicode = allow_unicode
|
2015-04-16 06:28:49 +08:00
|
|
|
if self.allow_unicode:
|
|
|
|
self.default_validators = [validators.validate_unicode_slug]
|
2017-02-02 00:41:56 +08:00
|
|
|
super().__init__(*args, max_length=max_length, db_index=db_index, **kwargs)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2013-05-18 19:48:57 +08:00
|
|
|
def deconstruct(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2015-05-14 02:51:18 +08:00
|
|
|
if kwargs.get("max_length") == 50:
|
2013-05-18 19:48:57 +08:00
|
|
|
del kwargs["max_length"]
|
|
|
|
if self.db_index is False:
|
|
|
|
kwargs["db_index"] = False
|
|
|
|
else:
|
|
|
|
del kwargs["db_index"]
|
2015-04-16 06:28:49 +08:00
|
|
|
if self.allow_unicode is not False:
|
|
|
|
kwargs["allow_unicode"] = self.allow_unicode
|
2013-05-18 19:48:57 +08:00
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "SlugField"
|
|
|
|
|
2008-08-23 12:59:25 +08:00
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
|
|
|
"form_class": forms.SlugField,
|
|
|
|
"allow_unicode": self.allow_unicode,
|
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2008-08-23 12:59:25 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2005-08-02 05:29:52 +08:00
|
|
|
class TextField(Field):
|
2010-01-05 11:56:19 +08:00
|
|
|
description = _("Text")
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2020-07-18 19:17:39 +08:00
|
|
|
def __init__(self, *args, db_collation=None, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
self.db_collation = db_collation
|
|
|
|
|
|
|
|
def check(self, **kwargs):
|
|
|
|
databases = kwargs.get("databases") or []
|
|
|
|
return [
|
|
|
|
*super().check(**kwargs),
|
|
|
|
*self._check_db_collation(databases),
|
|
|
|
]
|
|
|
|
|
|
|
|
def _check_db_collation(self, databases):
|
|
|
|
errors = []
|
|
|
|
for db in databases:
|
|
|
|
if not router.allow_migrate_model(db, self.model):
|
|
|
|
continue
|
|
|
|
connection = connections[db]
|
|
|
|
if not (
|
|
|
|
self.db_collation is None
|
|
|
|
or "supports_collation_on_textfield"
|
|
|
|
in self.model._meta.required_db_features
|
|
|
|
or connection.features.supports_collation_on_textfield
|
|
|
|
):
|
|
|
|
errors.append(
|
|
|
|
checks.Error(
|
|
|
|
"%s does not support a database collation on "
|
|
|
|
"TextFields." % connection.display_name,
|
|
|
|
obj=self,
|
|
|
|
id="fields.E190",
|
|
|
|
),
|
|
|
|
)
|
|
|
|
return errors
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "TextField"
|
|
|
|
|
2015-06-04 18:24:53 +08:00
|
|
|
def to_python(self, value):
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(value, str) or value is None:
|
2010-01-10 06:05:10 +08:00
|
|
|
return value
|
2017-04-22 01:52:26 +08:00
|
|
|
return str(value)
|
2010-01-10 06:05:10 +08:00
|
|
|
|
2015-06-04 18:24:53 +08:00
|
|
|
def get_prep_value(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().get_prep_value(value)
|
2015-06-04 18:24:53 +08:00
|
|
|
return self.to_python(value)
|
|
|
|
|
2007-01-22 14:32:14 +08:00
|
|
|
def formfield(self, **kwargs):
|
2014-03-04 22:12:13 +08:00
|
|
|
# Passing max_length to forms.CharField means that the value's length
|
|
|
|
# will be validated twice. This is considered acceptable since we want
|
|
|
|
# the value in the form field (to pass into widget for example).
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
|
|
|
"max_length": self.max_length,
|
2019-01-05 04:03:53 +08:00
|
|
|
**({} if self.choices is not None else {"widget": forms.Textarea}),
|
2017-12-11 20:08:45 +08:00
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2007-01-11 07:34:37 +08:00
|
|
|
|
2020-07-18 19:17:39 +08:00
|
|
|
def deconstruct(self):
|
|
|
|
name, path, args, kwargs = super().deconstruct()
|
|
|
|
if self.db_collation:
|
|
|
|
kwargs["db_collation"] = self.db_collation
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2014-03-13 19:32:20 +08:00
|
|
|
class TimeField(DateTimeCheckMixin, Field):
|
2005-08-02 05:29:52 +08:00
|
|
|
empty_strings_allowed = False
|
2010-01-05 11:56:19 +08:00
|
|
|
default_error_messages = {
|
2019-06-28 00:39:47 +08:00
|
|
|
"invalid": _(
|
|
|
|
"“%(value)s” value has an invalid format. It must be in "
|
|
|
|
"HH:MM[:ss[.uuuuuu]] format."
|
|
|
|
),
|
|
|
|
"invalid_time": _(
|
|
|
|
"“%(value)s” value has the correct format "
|
|
|
|
"(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."
|
|
|
|
),
|
2010-01-05 11:56:19 +08:00
|
|
|
}
|
2011-11-18 21:01:06 +08:00
|
|
|
description = _("Time")
|
|
|
|
|
2011-10-13 16:11:00 +08:00
|
|
|
def __init__(
|
|
|
|
self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs
|
|
|
|
):
|
2006-05-02 09:31:56 +08:00
|
|
|
self.auto_now, self.auto_now_add = auto_now, auto_now_add
|
2005-08-02 05:29:52 +08:00
|
|
|
if auto_now or auto_now_add:
|
|
|
|
kwargs["editable"] = False
|
2011-11-18 21:01:06 +08:00
|
|
|
kwargs["blank"] = True
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(verbose_name, name, **kwargs)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2014-02-22 21:29:43 +08:00
|
|
|
def _check_fix_default_value(self):
|
|
|
|
"""
|
2017-01-25 07:04:12 +08:00
|
|
|
Warn that using an actual date or datetime value is probably wrong;
|
|
|
|
it's only evaluated on server startup.
|
2014-02-22 21:29:43 +08:00
|
|
|
"""
|
|
|
|
if not self.has_default():
|
|
|
|
return []
|
|
|
|
|
|
|
|
value = self.default
|
|
|
|
if isinstance(value, datetime.datetime):
|
2021-07-29 13:47:24 +08:00
|
|
|
now = None
|
2014-02-22 21:29:43 +08:00
|
|
|
elif isinstance(value, datetime.time):
|
2021-07-28 15:11:13 +08:00
|
|
|
now = _get_naive_now()
|
|
|
|
# This will not use the right date in the race condition where now
|
|
|
|
# is just before the date change and value is just past 0:00.
|
2014-02-22 21:29:43 +08:00
|
|
|
value = datetime.datetime.combine(now.date(), value)
|
|
|
|
else:
|
|
|
|
# No explicit time / datetime value -- no checks necessary
|
|
|
|
return []
|
2021-07-28 15:11:13 +08:00
|
|
|
# At this point, value is a datetime object.
|
2021-07-29 13:47:24 +08:00
|
|
|
return self._check_if_value_fixed(value, now=now)
|
2014-02-22 21:29:43 +08:00
|
|
|
|
2013-05-18 19:48:57 +08:00
|
|
|
def deconstruct(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2013-05-18 19:48:57 +08:00
|
|
|
if self.auto_now is not False:
|
|
|
|
kwargs["auto_now"] = self.auto_now
|
|
|
|
if self.auto_now_add is not False:
|
|
|
|
kwargs["auto_now_add"] = self.auto_now_add
|
2014-08-03 20:02:21 +08:00
|
|
|
if self.auto_now or self.auto_now_add:
|
|
|
|
del kwargs["blank"]
|
|
|
|
del kwargs["editable"]
|
2013-05-18 19:48:57 +08:00
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2008-02-19 10:58:41 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "TimeField"
|
|
|
|
|
2008-07-29 13:09:29 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
if isinstance(value, datetime.time):
|
|
|
|
return value
|
2009-03-10 13:24:19 +08:00
|
|
|
if isinstance(value, datetime.datetime):
|
|
|
|
# Not usually a good idea to pass in a datetime here (it loses
|
|
|
|
# information), but this can be a side-effect of interacting with a
|
|
|
|
# database backend (e.g. Oracle), so we'll be accommodating.
|
2010-01-10 04:02:41 +08:00
|
|
|
return value.time()
|
2008-07-29 13:09:29 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
try:
|
|
|
|
parsed = parse_time(value)
|
|
|
|
if parsed is not None:
|
|
|
|
return parsed
|
2008-07-29 13:09:29 +08:00
|
|
|
except ValueError:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise exceptions.ValidationError(
|
|
|
|
self.error_messages["invalid_time"],
|
|
|
|
code="invalid_time",
|
|
|
|
params={"value": value},
|
|
|
|
)
|
|
|
|
|
|
|
|
raise exceptions.ValidationError(
|
|
|
|
self.error_messages["invalid"],
|
|
|
|
code="invalid",
|
|
|
|
params={"value": value},
|
|
|
|
)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2006-05-30 01:08:58 +08:00
|
|
|
def pre_save(self, model_instance, add):
|
2005-08-10 11:50:46 +08:00
|
|
|
if self.auto_now or (self.auto_now_add and add):
|
2006-05-30 01:08:58 +08:00
|
|
|
value = datetime.datetime.now().time()
|
|
|
|
setattr(model_instance, self.attname, value)
|
|
|
|
return value
|
|
|
|
else:
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().pre_save(model_instance, add)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def get_prep_value(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().get_prep_value(value)
|
2009-12-22 23:18:51 +08:00
|
|
|
return self.to_python(value)
|
|
|
|
|
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
2008-07-29 13:09:29 +08:00
|
|
|
# Casts times into the format expected by the backend
|
2009-12-22 23:18:51 +08:00
|
|
|
if not prepared:
|
|
|
|
value = self.get_prep_value(value)
|
2015-05-03 03:27:44 +08:00
|
|
|
return connection.ops.adapt_timefield_value(value)
|
2005-08-02 05:29:52 +08:00
|
|
|
|
Removed oldforms, validators, and related code:
* Removed `Manipulator`, `AutomaticManipulator`, and related classes.
* Removed oldforms specific bits from model fields:
* Removed `validator_list` and `core` arguments from constructors.
* Removed the methods:
* `get_manipulator_field_names`
* `get_manipulator_field_objs`
* `get_manipulator_fields`
* `get_manipulator_new_data`
* `prepare_field_objs_and_params`
* `get_follow`
* Renamed `flatten_data` method to `value_to_string` for better alignment with its use by the serialization framework, which was the only remaining code using `flatten_data`.
* Removed oldforms methods from `django.db.models.Options` class: `get_followed_related_objects`, `get_data_holders`, `get_follow`, and `has_field_type`.
* Removed oldforms-admin specific options from `django.db.models.fields.related` classes: `num_in_admin`, `min_num_in_admin`, `max_num_in_admin`, `num_extra_on_change`, and `edit_inline`.
* Serialization framework
* `Serializer.get_string_value` now calls the model fields' renamed `value_to_string` methods.
* Removed a special-casing of `models.DateTimeField` in `core.serializers.base.Serializer.get_string_value` that's handled by `django.db.models.fields.DateTimeField.value_to_string`.
* Removed `django.core.validators`:
* Moved `ValidationError` exception to `django.core.exceptions`.
* For the couple places that were using validators, brought over the necessary code to maintain the same functionality.
* Introduced a SlugField form field for validation and to compliment the SlugField model field (refs #8040).
* Removed an oldforms-style model creation hack (refs #2160).
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8616 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-27 15:19:44 +08:00
|
|
|
def value_to_string(self, obj):
|
2015-04-26 14:30:46 +08:00
|
|
|
val = self.value_from_object(obj)
|
2011-11-18 21:01:06 +08:00
|
|
|
return "" if val is None else val.isoformat()
|
2005-11-26 05:20:09 +08:00
|
|
|
|
2007-01-22 14:32:14 +08:00
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
|
|
|
"form_class": forms.TimeField,
|
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2006-12-16 02:32:42 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2007-01-09 04:28:31 +08:00
|
|
|
class URLField(CharField):
|
2013-06-14 00:37:08 +08:00
|
|
|
default_validators = [validators.URLValidator()]
|
2010-01-05 11:56:19 +08:00
|
|
|
description = _("URL")
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2012-03-31 21:55:03 +08:00
|
|
|
def __init__(self, verbose_name=None, name=None, **kwargs):
|
2017-12-04 23:52:27 +08:00
|
|
|
kwargs.setdefault("max_length", 200)
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(verbose_name, name, **kwargs)
|
2006-12-16 02:32:42 +08:00
|
|
|
|
2013-05-18 19:48:57 +08:00
|
|
|
def deconstruct(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2015-05-14 02:51:18 +08:00
|
|
|
if kwargs.get("max_length") == 200:
|
2013-05-18 19:48:57 +08:00
|
|
|
del kwargs["max_length"]
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2010-08-05 11:59:20 +08:00
|
|
|
def formfield(self, **kwargs):
|
2011-10-13 16:11:00 +08:00
|
|
|
# As with CharField, this will cause URL validation to be performed
|
|
|
|
# twice.
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
2010-08-05 11:59:20 +08:00
|
|
|
"form_class": forms.URLField,
|
2017-12-11 20:08:45 +08:00
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2012-12-14 05:11:06 +08:00
|
|
|
|
2013-07-08 08:39:54 +08:00
|
|
|
|
2012-12-14 05:11:06 +08:00
|
|
|
class BinaryField(Field):
|
|
|
|
description = _("Raw binary data")
|
2013-03-06 15:28:12 +08:00
|
|
|
empty_values = [None, b""]
|
2012-12-14 05:11:06 +08:00
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
2017-12-19 04:19:57 +08:00
|
|
|
kwargs.setdefault("editable", False)
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(*args, **kwargs)
|
2012-12-14 05:11:06 +08:00
|
|
|
if self.max_length is not None:
|
|
|
|
self.validators.append(validators.MaxLengthValidator(self.max_length))
|
|
|
|
|
2019-03-18 04:47:21 +08:00
|
|
|
def check(self, **kwargs):
|
|
|
|
return [*super().check(**kwargs), *self._check_str_default_value()]
|
|
|
|
|
|
|
|
def _check_str_default_value(self):
|
|
|
|
if self.has_default() and isinstance(self.default, str):
|
|
|
|
return [
|
|
|
|
checks.Error(
|
|
|
|
"BinaryField's default cannot be a string. Use bytes "
|
|
|
|
"content instead.",
|
|
|
|
obj=self,
|
|
|
|
id="fields.E170",
|
|
|
|
)
|
|
|
|
]
|
|
|
|
return []
|
|
|
|
|
2014-08-03 18:59:21 +08:00
|
|
|
def deconstruct(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2017-12-19 04:19:57 +08:00
|
|
|
if self.editable:
|
|
|
|
kwargs["editable"] = True
|
|
|
|
else:
|
|
|
|
del kwargs["editable"]
|
2014-08-03 18:59:21 +08:00
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2012-12-14 05:11:06 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "BinaryField"
|
|
|
|
|
2016-02-14 02:07:58 +08:00
|
|
|
def get_placeholder(self, value, compiler, connection):
|
|
|
|
return connection.ops.binary_placeholder_sql(value)
|
|
|
|
|
2012-12-14 05:11:06 +08:00
|
|
|
def get_default(self):
|
|
|
|
if self.has_default() and not callable(self.default):
|
|
|
|
return self.default
|
2017-01-21 21:13:44 +08:00
|
|
|
default = super().get_default()
|
2012-12-14 05:11:06 +08:00
|
|
|
if default == "":
|
|
|
|
return b""
|
|
|
|
return default
|
|
|
|
|
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().get_db_prep_value(value, connection, prepared)
|
2012-12-14 05:11:06 +08:00
|
|
|
if value is not None:
|
|
|
|
return connection.Database.Binary(value)
|
|
|
|
return value
|
2012-12-15 07:26:08 +08:00
|
|
|
|
|
|
|
def value_to_string(self, obj):
|
|
|
|
"""Binary data is serialized as base64"""
|
2018-08-28 19:56:18 +08:00
|
|
|
return b64encode(self.value_from_object(obj)).decode("ascii")
|
2012-12-15 07:26:08 +08:00
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
# If it's a string, it should be base64-encoded data
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(value, str):
|
2018-08-28 19:56:18 +08:00
|
|
|
return memoryview(b64decode(value.encode("ascii")))
|
2012-12-15 07:26:08 +08:00
|
|
|
return value
|
2014-07-15 17:35:29 +08:00
|
|
|
|
|
|
|
|
|
|
|
class UUIDField(Field):
|
|
|
|
default_error_messages = {
|
2019-06-28 00:39:47 +08:00
|
|
|
"invalid": _("“%(value)s” is not a valid UUID."),
|
2014-07-15 17:35:29 +08:00
|
|
|
}
|
2018-12-01 00:23:17 +08:00
|
|
|
description = _("Universally unique identifier")
|
2014-07-15 17:35:29 +08:00
|
|
|
empty_strings_allowed = False
|
|
|
|
|
2015-02-22 02:27:49 +08:00
|
|
|
def __init__(self, verbose_name=None, **kwargs):
|
2014-07-15 17:35:29 +08:00
|
|
|
kwargs["max_length"] = 32
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(verbose_name, **kwargs)
|
2014-07-15 17:35:29 +08:00
|
|
|
|
2015-02-06 05:13:57 +08:00
|
|
|
def deconstruct(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
name, path, args, kwargs = super().deconstruct()
|
2015-02-06 05:13:57 +08:00
|
|
|
del kwargs["max_length"]
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
2014-07-15 17:35:29 +08:00
|
|
|
def get_internal_type(self):
|
|
|
|
return "UUIDField"
|
|
|
|
|
2019-04-14 16:02:59 +08:00
|
|
|
def get_prep_value(self, value):
|
|
|
|
value = super().get_prep_value(value)
|
|
|
|
return self.to_python(value)
|
|
|
|
|
2015-01-11 02:13:28 +08:00
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
2015-06-04 21:42:26 +08:00
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
if not isinstance(value, uuid.UUID):
|
2016-11-01 03:21:05 +08:00
|
|
|
value = self.to_python(value)
|
2015-06-04 21:42:26 +08:00
|
|
|
|
|
|
|
if connection.features.has_native_uuid_field:
|
|
|
|
return value
|
|
|
|
return value.hex
|
2014-07-15 17:35:29 +08:00
|
|
|
|
|
|
|
def to_python(self, value):
|
2017-02-11 01:28:16 +08:00
|
|
|
if value is not None and not isinstance(value, uuid.UUID):
|
2018-10-25 05:43:41 +08:00
|
|
|
input_form = "int" if isinstance(value, int) else "hex"
|
2014-07-15 17:35:29 +08:00
|
|
|
try:
|
2018-10-25 05:43:41 +08:00
|
|
|
return uuid.UUID(**{input_form: value})
|
2016-11-01 03:21:05 +08:00
|
|
|
except (AttributeError, ValueError):
|
2014-07-15 17:35:29 +08:00
|
|
|
raise exceptions.ValidationError(
|
|
|
|
self.error_messages["invalid"],
|
|
|
|
code="invalid",
|
|
|
|
params={"value": value},
|
|
|
|
)
|
|
|
|
return value
|
|
|
|
|
|
|
|
def formfield(self, **kwargs):
|
2017-12-11 20:08:45 +08:00
|
|
|
return super().formfield(
|
|
|
|
**{
|
2014-07-15 17:35:29 +08:00
|
|
|
"form_class": forms.UUIDField,
|
2017-12-11 20:08:45 +08:00
|
|
|
**kwargs,
|
|
|
|
}
|
|
|
|
)
|
2017-12-11 23:36:33 +08:00
|
|
|
|
|
|
|
|
|
|
|
class AutoFieldMixin:
|
2019-07-24 14:42:41 +08:00
|
|
|
db_returning = True
|
2017-12-11 23:36:33 +08:00
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
kwargs["blank"] = True
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
def check(self, **kwargs):
|
|
|
|
return [
|
|
|
|
*super().check(**kwargs),
|
|
|
|
*self._check_primary_key(),
|
|
|
|
]
|
|
|
|
|
|
|
|
def _check_primary_key(self):
|
|
|
|
if not self.primary_key:
|
|
|
|
return [
|
|
|
|
checks.Error(
|
|
|
|
"AutoFields must set primary_key=True.",
|
|
|
|
obj=self,
|
|
|
|
id="fields.E100",
|
|
|
|
),
|
|
|
|
]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
|
|
|
|
def deconstruct(self):
|
|
|
|
name, path, args, kwargs = super().deconstruct()
|
|
|
|
del kwargs["blank"]
|
|
|
|
kwargs["primary_key"] = True
|
|
|
|
return name, path, args, kwargs
|
|
|
|
|
|
|
|
def validate(self, value, model_instance):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def get_db_prep_value(self, value, connection, prepared=False):
|
|
|
|
if not prepared:
|
|
|
|
value = self.get_prep_value(value)
|
|
|
|
value = connection.ops.validate_autopk_value(value)
|
|
|
|
return value
|
|
|
|
|
|
|
|
def contribute_to_class(self, cls, name, **kwargs):
|
2021-03-24 13:45:08 +08:00
|
|
|
if cls._meta.auto_field:
|
|
|
|
raise ValueError(
|
|
|
|
"Model %s can't have more than one auto-generated field."
|
|
|
|
% cls._meta.label
|
|
|
|
)
|
2017-12-11 23:36:33 +08:00
|
|
|
super().contribute_to_class(cls, name, **kwargs)
|
|
|
|
cls._meta.auto_field = self
|
|
|
|
|
|
|
|
def formfield(self, **kwargs):
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
class AutoFieldMeta(type):
|
|
|
|
"""
|
|
|
|
Metaclass to maintain backward inheritance compatibility for AutoField.
|
|
|
|
|
|
|
|
It is intended that AutoFieldMixin become public API when it is possible to
|
|
|
|
create a non-integer automatically-generated field using column defaults
|
|
|
|
stored in the database.
|
|
|
|
|
|
|
|
In many areas Django also relies on using isinstance() to check for an
|
|
|
|
automatically-generated field as a subclass of AutoField. A new flag needs
|
|
|
|
to be implemented on Field to be used instead.
|
|
|
|
|
|
|
|
When these issues have been addressed, this metaclass could be used to
|
|
|
|
deprecate inheritance from AutoField and use of isinstance() with AutoField
|
|
|
|
for detecting automatically-generated fields.
|
|
|
|
"""
|
|
|
|
|
|
|
|
@property
|
|
|
|
def _subclasses(self):
|
|
|
|
return (BigAutoField, SmallAutoField)
|
|
|
|
|
|
|
|
def __instancecheck__(self, instance):
|
|
|
|
return isinstance(instance, self._subclasses) or super().__instancecheck__(
|
|
|
|
instance
|
|
|
|
)
|
|
|
|
|
|
|
|
def __subclasscheck__(self, subclass):
|
2021-04-08 18:40:16 +08:00
|
|
|
return issubclass(subclass, self._subclasses) or super().__subclasscheck__(
|
|
|
|
subclass
|
|
|
|
)
|
2017-12-11 23:36:33 +08:00
|
|
|
|
|
|
|
|
|
|
|
class AutoField(AutoFieldMixin, IntegerField, metaclass=AutoFieldMeta):
|
|
|
|
def get_internal_type(self):
|
|
|
|
return "AutoField"
|
|
|
|
|
|
|
|
def rel_db_type(self, connection):
|
|
|
|
return IntegerField().db_type(connection=connection)
|
|
|
|
|
|
|
|
|
|
|
|
class BigAutoField(AutoFieldMixin, BigIntegerField):
|
|
|
|
def get_internal_type(self):
|
|
|
|
return "BigAutoField"
|
|
|
|
|
|
|
|
def rel_db_type(self, connection):
|
|
|
|
return BigIntegerField().db_type(connection=connection)
|
|
|
|
|
|
|
|
|
|
|
|
class SmallAutoField(AutoFieldMixin, SmallIntegerField):
|
|
|
|
def get_internal_type(self):
|
|
|
|
return "SmallAutoField"
|
|
|
|
|
|
|
|
def rel_db_type(self, connection):
|
|
|
|
return SmallIntegerField().db_type(connection=connection)
|