__init__.py 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356
  1. import collections
  2. import copy
  3. import datetime
  4. import decimal
  5. import itertools
  6. import uuid
  7. import warnings
  8. from base64 import b64decode, b64encode
  9. from functools import total_ordering
  10. from django import forms
  11. from django.apps import apps
  12. from django.conf import settings
  13. from django.core import checks, exceptions, validators
  14. # When the _meta object was formalized, this exception was moved to
  15. # django.core.exceptions. It is retained here for backwards compatibility
  16. # purposes.
  17. from django.core.exceptions import FieldDoesNotExist # NOQA
  18. from django.db import connection, connections, router
  19. from django.db.models.constants import LOOKUP_SEP
  20. from django.db.models.query_utils import DeferredAttribute, RegisterLookupMixin
  21. from django.utils import timezone
  22. from django.utils.datastructures import DictWrapper
  23. from django.utils.dateparse import (
  24. parse_date, parse_datetime, parse_duration, parse_time,
  25. )
  26. from django.utils.duration import duration_string
  27. from django.utils.encoding import force_bytes, force_text, smart_text
  28. from django.utils.functional import Promise, cached_property, curry
  29. from django.utils.ipv6 import clean_ipv6_address
  30. from django.utils.itercompat import is_iterable
  31. from django.utils.text import capfirst
  32. from django.utils.translation import gettext_lazy as _
  33. __all__ = [
  34. 'AutoField', 'BLANK_CHOICE_DASH', 'BigAutoField', 'BigIntegerField',
  35. 'BinaryField', 'BooleanField', 'CharField', 'CommaSeparatedIntegerField',
  36. 'DateField', 'DateTimeField', 'DecimalField', 'DurationField',
  37. 'EmailField', 'Empty', 'Field', 'FieldDoesNotExist', 'FilePathField',
  38. 'FloatField', 'GenericIPAddressField', 'IPAddressField', 'IntegerField',
  39. 'NOT_PROVIDED', 'NullBooleanField', 'PositiveIntegerField',
  40. 'PositiveSmallIntegerField', 'SlugField', 'SmallIntegerField', 'TextField',
  41. 'TimeField', 'URLField', 'UUIDField',
  42. ]
  43. class Empty:
  44. pass
  45. class NOT_PROVIDED:
  46. pass
  47. # The values to use for "blank" in SelectFields. Will be appended to the start
  48. # of most "choices" lists.
  49. BLANK_CHOICE_DASH = [("", "---------")]
  50. def _load_field(app_label, model_name, field_name):
  51. return apps.get_model(app_label, model_name)._meta.get_field(field_name)
  52. # A guide to Field parameters:
  53. #
  54. # * name: The name of the field specified in the model.
  55. # * attname: The attribute to use on the model object. This is the same as
  56. # "name", except in the case of ForeignKeys, where "_id" is
  57. # appended.
  58. # * db_column: The db_column specified in the model (or None).
  59. # * column: The database column for this field. This is the same as
  60. # "attname", except if db_column is specified.
  61. #
  62. # Code that introspects values, or does other dynamic things, should use
  63. # attname. For example, this gets the primary key value of object "obj":
  64. #
  65. # getattr(obj, opts.pk.attname)
  66. def _empty(of_cls):
  67. new = Empty()
  68. new.__class__ = of_cls
  69. return new
  70. def return_None():
  71. return None
  72. @total_ordering
  73. class Field(RegisterLookupMixin):
  74. """Base class for all field types"""
  75. # Designates whether empty strings fundamentally are allowed at the
  76. # database level.
  77. empty_strings_allowed = True
  78. empty_values = list(validators.EMPTY_VALUES)
  79. # These track each time a Field instance is created. Used to retain order.
  80. # The auto_creation_counter is used for fields that Django implicitly
  81. # creates, creation_counter is used for all user-specified fields.
  82. creation_counter = 0
  83. auto_creation_counter = -1
  84. default_validators = [] # Default set of validators
  85. default_error_messages = {
  86. 'invalid_choice': _('Value %(value)r is not a valid choice.'),
  87. 'null': _('This field cannot be null.'),
  88. 'blank': _('This field cannot be blank.'),
  89. 'unique': _('%(model_name)s with this %(field_label)s '
  90. 'already exists.'),
  91. # Translators: The 'lookup_type' is one of 'date', 'year' or 'month'.
  92. # Eg: "Title must be unique for pub_date year"
  93. 'unique_for_date': _("%(field_label)s must be unique for "
  94. "%(date_field_label)s %(lookup_type)s."),
  95. }
  96. system_check_deprecated_details = None
  97. system_check_removed_details = None
  98. # Field flags
  99. hidden = False
  100. many_to_many = None
  101. many_to_one = None
  102. one_to_many = None
  103. one_to_one = None
  104. related_model = None
  105. # Generic field type description, usually overridden by subclasses
  106. def _description(self):
  107. return _('Field of type: %(field_type)s') % {
  108. 'field_type': self.__class__.__name__
  109. }
  110. description = property(_description)
  111. def __init__(self, verbose_name=None, name=None, primary_key=False,
  112. max_length=None, unique=False, blank=False, null=False,
  113. db_index=False, rel=None, default=NOT_PROVIDED, editable=True,
  114. serialize=True, unique_for_date=None, unique_for_month=None,
  115. unique_for_year=None, choices=None, help_text='', db_column=None,
  116. db_tablespace=None, auto_created=False, validators=(),
  117. error_messages=None):
  118. self.name = name
  119. self.verbose_name = verbose_name # May be set by set_attributes_from_name
  120. self._verbose_name = verbose_name # Store original for deconstruction
  121. self.primary_key = primary_key
  122. self.max_length, self._unique = max_length, unique
  123. self.blank, self.null = blank, null
  124. self.remote_field = rel
  125. self.is_relation = self.remote_field is not None
  126. self.default = default
  127. self.editable = editable
  128. self.serialize = serialize
  129. self.unique_for_date = unique_for_date
  130. self.unique_for_month = unique_for_month
  131. self.unique_for_year = unique_for_year
  132. if isinstance(choices, collections.Iterator):
  133. choices = list(choices)
  134. self.choices = choices or []
  135. self.help_text = help_text
  136. self.db_index = db_index
  137. self.db_column = db_column
  138. self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
  139. self.auto_created = auto_created
  140. # Adjust the appropriate creation counter, and save our local copy.
  141. if auto_created:
  142. self.creation_counter = Field.auto_creation_counter
  143. Field.auto_creation_counter -= 1
  144. else:
  145. self.creation_counter = Field.creation_counter
  146. Field.creation_counter += 1
  147. self._validators = list(validators) # Store for deconstruction later
  148. messages = {}
  149. for c in reversed(self.__class__.__mro__):
  150. messages.update(getattr(c, 'default_error_messages', {}))
  151. messages.update(error_messages or {})
  152. self._error_messages = error_messages # Store for deconstruction later
  153. self.error_messages = messages
  154. def __str__(self):
  155. """
  156. Return "app_label.model_label.field_name" for fields attached to
  157. models.
  158. """
  159. if not hasattr(self, 'model'):
  160. return super().__str__()
  161. model = self.model
  162. app = model._meta.app_label
  163. return '%s.%s.%s' % (app, model._meta.object_name, self.name)
  164. def __repr__(self):
  165. """
  166. Displays the module, class and name of the field.
  167. """
  168. path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
  169. name = getattr(self, 'name', None)
  170. if name is not None:
  171. return '<%s: %s>' % (path, name)
  172. return '<%s>' % path
  173. def check(self, **kwargs):
  174. errors = []
  175. errors.extend(self._check_field_name())
  176. errors.extend(self._check_choices())
  177. errors.extend(self._check_db_index())
  178. errors.extend(self._check_null_allowed_for_primary_keys())
  179. errors.extend(self._check_backend_specific_checks(**kwargs))
  180. errors.extend(self._check_deprecation_details())
  181. return errors
  182. def _check_field_name(self):
  183. """ Check if field name is valid, i.e. 1) does not end with an
  184. underscore, 2) does not contain "__" and 3) is not "pk". """
  185. if self.name.endswith('_'):
  186. return [
  187. checks.Error(
  188. 'Field names must not end with an underscore.',
  189. obj=self,
  190. id='fields.E001',
  191. )
  192. ]
  193. elif LOOKUP_SEP in self.name:
  194. return [
  195. checks.Error(
  196. 'Field names must not contain "%s".' % (LOOKUP_SEP,),
  197. obj=self,
  198. id='fields.E002',
  199. )
  200. ]
  201. elif self.name == 'pk':
  202. return [
  203. checks.Error(
  204. "'pk' is a reserved word that cannot be used as a field name.",
  205. obj=self,
  206. id='fields.E003',
  207. )
  208. ]
  209. else:
  210. return []
  211. def _check_choices(self):
  212. if self.choices:
  213. if isinstance(self.choices, str) or not is_iterable(self.choices):
  214. return [
  215. checks.Error(
  216. "'choices' must be an iterable (e.g., a list or tuple).",
  217. obj=self,
  218. id='fields.E004',
  219. )
  220. ]
  221. elif any(isinstance(choice, str) or
  222. not is_iterable(choice) or len(choice) != 2
  223. for choice in self.choices):
  224. return [
  225. checks.Error(
  226. "'choices' must be an iterable containing "
  227. "(actual value, human readable name) tuples.",
  228. obj=self,
  229. id='fields.E005',
  230. )
  231. ]
  232. else:
  233. return []
  234. else:
  235. return []
  236. def _check_db_index(self):
  237. if self.db_index not in (None, True, False):
  238. return [
  239. checks.Error(
  240. "'db_index' must be None, True or False.",
  241. obj=self,
  242. id='fields.E006',
  243. )
  244. ]
  245. else:
  246. return []
  247. def _check_null_allowed_for_primary_keys(self):
  248. if (self.primary_key and self.null and
  249. not connection.features.interprets_empty_strings_as_nulls):
  250. # We cannot reliably check this for backends like Oracle which
  251. # consider NULL and '' to be equal (and thus set up
  252. # character-based fields a little differently).
  253. return [
  254. checks.Error(
  255. 'Primary keys must not have null=True.',
  256. hint=('Set null=False on the field, or '
  257. 'remove primary_key=True argument.'),
  258. obj=self,
  259. id='fields.E007',
  260. )
  261. ]
  262. else:
  263. return []
  264. def _check_backend_specific_checks(self, **kwargs):
  265. app_label = self.model._meta.app_label
  266. for db in connections:
  267. if router.allow_migrate(db, app_label, model_name=self.model._meta.model_name):
  268. return connections[db].validation.check_field(self, **kwargs)
  269. return []
  270. def _check_deprecation_details(self):
  271. if self.system_check_removed_details is not None:
  272. return [
  273. checks.Error(
  274. self.system_check_removed_details.get(
  275. 'msg',
  276. '%s has been removed except for support in historical '
  277. 'migrations.' % self.__class__.__name__
  278. ),
  279. hint=self.system_check_removed_details.get('hint'),
  280. obj=self,
  281. id=self.system_check_removed_details.get('id', 'fields.EXXX'),
  282. )
  283. ]
  284. elif self.system_check_deprecated_details is not None:
  285. return [
  286. checks.Warning(
  287. self.system_check_deprecated_details.get(
  288. 'msg',
  289. '%s has been deprecated.' % self.__class__.__name__
  290. ),
  291. hint=self.system_check_deprecated_details.get('hint'),
  292. obj=self,
  293. id=self.system_check_deprecated_details.get('id', 'fields.WXXX'),
  294. )
  295. ]
  296. return []
  297. def get_col(self, alias, output_field=None):
  298. if output_field is None:
  299. output_field = self
  300. if alias != self.model._meta.db_table or output_field != self:
  301. from django.db.models.expressions import Col
  302. return Col(alias, self, output_field)
  303. else:
  304. return self.cached_col
  305. @cached_property
  306. def cached_col(self):
  307. from django.db.models.expressions import Col
  308. return Col(self.model._meta.db_table, self)
  309. def select_format(self, compiler, sql, params):
  310. """
  311. Custom format for select clauses. For example, GIS columns need to be
  312. selected as AsText(table.col) on MySQL as the table.col data can't be used
  313. by Django.
  314. """
  315. return sql, params
  316. def deconstruct(self):
  317. """
  318. Returns enough information to recreate the field as a 4-tuple:
  319. * The name of the field on the model, if contribute_to_class has been run
  320. * The import path of the field, including the class: django.db.models.IntegerField
  321. This should be the most portable version, so less specific may be better.
  322. * A list of positional arguments
  323. * A dict of keyword arguments
  324. Note that the positional or keyword arguments must contain values of the
  325. following types (including inner values of collection types):
  326. * None, bool, str, int, float, complex, set, frozenset, list, tuple, dict
  327. * UUID
  328. * datetime.datetime (naive), datetime.date
  329. * top-level classes, top-level functions - will be referenced by their full import path
  330. * Storage instances - these have their own deconstruct() method
  331. This is because the values here must be serialized into a text format
  332. (possibly new Python code, possibly JSON) and these are the only types
  333. with encoding handlers defined.
  334. There's no need to return the exact way the field was instantiated this time,
  335. just ensure that the resulting field is the same - prefer keyword arguments
  336. over positional ones, and omit parameters with their default values.
  337. """
  338. # Short-form way of fetching all the default parameters
  339. keywords = {}
  340. possibles = {
  341. "verbose_name": None,
  342. "primary_key": False,
  343. "max_length": None,
  344. "unique": False,
  345. "blank": False,
  346. "null": False,
  347. "db_index": False,
  348. "default": NOT_PROVIDED,
  349. "editable": True,
  350. "serialize": True,
  351. "unique_for_date": None,
  352. "unique_for_month": None,
  353. "unique_for_year": None,
  354. "choices": [],
  355. "help_text": '',
  356. "db_column": None,
  357. "db_tablespace": settings.DEFAULT_INDEX_TABLESPACE,
  358. "auto_created": False,
  359. "validators": [],
  360. "error_messages": None,
  361. }
  362. attr_overrides = {
  363. "unique": "_unique",
  364. "error_messages": "_error_messages",
  365. "validators": "_validators",
  366. "verbose_name": "_verbose_name",
  367. }
  368. equals_comparison = {"choices", "validators", "db_tablespace"}
  369. for name, default in possibles.items():
  370. value = getattr(self, attr_overrides.get(name, name))
  371. # Unroll anything iterable for choices into a concrete list
  372. if name == "choices" and isinstance(value, collections.Iterable):
  373. value = list(value)
  374. # Do correct kind of comparison
  375. if name in equals_comparison:
  376. if value != default:
  377. keywords[name] = value
  378. else:
  379. if value is not default:
  380. keywords[name] = value
  381. # Work out path - we shorten it for known Django core fields
  382. path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
  383. if path.startswith("django.db.models.fields.related"):
  384. path = path.replace("django.db.models.fields.related", "django.db.models")
  385. if path.startswith("django.db.models.fields.files"):
  386. path = path.replace("django.db.models.fields.files", "django.db.models")
  387. if path.startswith("django.db.models.fields.proxy"):
  388. path = path.replace("django.db.models.fields.proxy", "django.db.models")
  389. if path.startswith("django.db.models.fields"):
  390. path = path.replace("django.db.models.fields", "django.db.models")
  391. # Return basic info - other fields should override this.
  392. return (
  393. force_text(self.name, strings_only=True),
  394. path,
  395. [],
  396. keywords,
  397. )
  398. def clone(self):
  399. """
  400. Uses deconstruct() to clone a new copy of this Field.
  401. Will not preserve any class attachments/attribute names.
  402. """
  403. name, path, args, kwargs = self.deconstruct()
  404. return self.__class__(*args, **kwargs)
  405. def __eq__(self, other):
  406. # Needed for @total_ordering
  407. if isinstance(other, Field):
  408. return self.creation_counter == other.creation_counter
  409. return NotImplemented
  410. def __lt__(self, other):
  411. # This is needed because bisect does not take a comparison function.
  412. if isinstance(other, Field):
  413. return self.creation_counter < other.creation_counter
  414. return NotImplemented
  415. def __hash__(self):
  416. return hash(self.creation_counter)
  417. def __deepcopy__(self, memodict):
  418. # We don't have to deepcopy very much here, since most things are not
  419. # intended to be altered after initial creation.
  420. obj = copy.copy(self)
  421. if self.remote_field:
  422. obj.remote_field = copy.copy(self.remote_field)
  423. if hasattr(self.remote_field, 'field') and self.remote_field.field is self:
  424. obj.remote_field.field = obj
  425. memodict[id(self)] = obj
  426. return obj
  427. def __copy__(self):
  428. # We need to avoid hitting __reduce__, so define this
  429. # slightly weird copy construct.
  430. obj = Empty()
  431. obj.__class__ = self.__class__
  432. obj.__dict__ = self.__dict__.copy()
  433. return obj
  434. def __reduce__(self):
  435. """
  436. Pickling should return the model._meta.fields instance of the field,
  437. not a new copy of that field. So, we use the app registry to load the
  438. model and then the field back.
  439. """
  440. if not hasattr(self, 'model'):
  441. # Fields are sometimes used without attaching them to models (for
  442. # example in aggregation). In this case give back a plain field
  443. # instance. The code below will create a new empty instance of
  444. # class self.__class__, then update its dict with self.__dict__
  445. # values - so, this is very close to normal pickle.
  446. return _empty, (self.__class__,), self.__dict__
  447. return _load_field, (self.model._meta.app_label, self.model._meta.object_name,
  448. self.name)
  449. def get_pk_value_on_save(self, instance):
  450. """
  451. Hook to generate new PK values on save. This method is called when
  452. saving instances with no primary key value set. If this method returns
  453. something else than None, then the returned value is used when saving
  454. the new instance.
  455. """
  456. if self.default:
  457. return self.get_default()
  458. return None
  459. def to_python(self, value):
  460. """
  461. Converts the input value into the expected Python data type, raising
  462. django.core.exceptions.ValidationError if the data can't be converted.
  463. Returns the converted value. Subclasses should override this.
  464. """
  465. return value
  466. @cached_property
  467. def validators(self):
  468. """
  469. Some validators can't be created at field initialization time.
  470. This method provides a way to delay their creation until required.
  471. """
  472. return list(itertools.chain(self.default_validators, self._validators))
  473. def run_validators(self, value):
  474. if value in self.empty_values:
  475. return
  476. errors = []
  477. for v in self.validators:
  478. try:
  479. v(value)
  480. except exceptions.ValidationError as e:
  481. if hasattr(e, 'code') and e.code in self.error_messages:
  482. e.message = self.error_messages[e.code]
  483. errors.extend(e.error_list)
  484. if errors:
  485. raise exceptions.ValidationError(errors)
  486. def validate(self, value, model_instance):
  487. """
  488. Validates value and throws ValidationError. Subclasses should override
  489. this to provide validation logic.
  490. """
  491. if not self.editable:
  492. # Skip validation for non-editable fields.
  493. return
  494. if self.choices and value not in self.empty_values:
  495. for option_key, option_value in self.choices:
  496. if isinstance(option_value, (list, tuple)):
  497. # This is an optgroup, so look inside the group for
  498. # options.
  499. for optgroup_key, optgroup_value in option_value:
  500. if value == optgroup_key:
  501. return
  502. elif value == option_key:
  503. return
  504. raise exceptions.ValidationError(
  505. self.error_messages['invalid_choice'],
  506. code='invalid_choice',
  507. params={'value': value},
  508. )
  509. if value is None and not self.null:
  510. raise exceptions.ValidationError(self.error_messages['null'], code='null')
  511. if not self.blank and value in self.empty_values:
  512. raise exceptions.ValidationError(self.error_messages['blank'], code='blank')
  513. def clean(self, value, model_instance):
  514. """
  515. Convert the value's type and run validation. Validation errors
  516. from to_python and validate are propagated. The correct value is
  517. returned if no error is raised.
  518. """
  519. value = self.to_python(value)
  520. self.validate(value, model_instance)
  521. self.run_validators(value)
  522. return value
  523. def db_check(self, connection):
  524. """
  525. Return the database column check constraint for this field, for the
  526. provided connection. Works the same way as db_type() for the case that
  527. get_internal_type() does not map to a preexisting model field.
  528. """
  529. data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_")
  530. try:
  531. return connection.data_type_check_constraints[self.get_internal_type()] % data
  532. except KeyError:
  533. return None
  534. def db_type(self, connection):
  535. """
  536. Return the database column data type for this field, for the provided
  537. connection.
  538. """
  539. # The default implementation of this method looks at the
  540. # backend-specific data_types dictionary, looking up the field by its
  541. # "internal type".
  542. #
  543. # A Field class can implement the get_internal_type() method to specify
  544. # which *preexisting* Django Field class it's most similar to -- i.e.,
  545. # a custom field might be represented by a TEXT column type, which is
  546. # the same as the TextField Django field type, which means the custom
  547. # field's get_internal_type() returns 'TextField'.
  548. #
  549. # But the limitation of the get_internal_type() / data_types approach
  550. # is that it cannot handle database column types that aren't already
  551. # mapped to one of the built-in Django field types. In this case, you
  552. # can implement db_type() instead of get_internal_type() to specify
  553. # exactly which wacky database column type you want to use.
  554. data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_")
  555. try:
  556. return connection.data_types[self.get_internal_type()] % data
  557. except KeyError:
  558. return None
  559. def rel_db_type(self, connection):
  560. """
  561. Return the data type that a related field pointing to this field should
  562. use. For example, this method is called by ForeignKey and OneToOneField
  563. to determine its data type.
  564. """
  565. return self.db_type(connection)
  566. def db_parameters(self, connection):
  567. """
  568. Extension of db_type(), providing a range of different return
  569. values (type, checks).
  570. This will look at db_type(), allowing custom model fields to override it.
  571. """
  572. type_string = self.db_type(connection)
  573. check_string = self.db_check(connection)
  574. return {
  575. "type": type_string,
  576. "check": check_string,
  577. }
  578. def db_type_suffix(self, connection):
  579. return connection.data_types_suffix.get(self.get_internal_type())
  580. def get_db_converters(self, connection):
  581. if hasattr(self, 'from_db_value'):
  582. return [self.from_db_value]
  583. return []
  584. @property
  585. def unique(self):
  586. return self._unique or self.primary_key
  587. def set_attributes_from_name(self, name):
  588. if not self.name:
  589. self.name = name
  590. self.attname, self.column = self.get_attname_column()
  591. self.concrete = self.column is not None
  592. if self.verbose_name is None and self.name:
  593. self.verbose_name = self.name.replace('_', ' ')
  594. def contribute_to_class(self, cls, name, private_only=False):
  595. """
  596. Register the field with the model class it belongs to.
  597. If private_only is True, a separate instance of this field will be
  598. created for every subclass of cls, even if cls is not an abstract
  599. model.
  600. """
  601. self.set_attributes_from_name(name)
  602. self.model = cls
  603. if private_only:
  604. cls._meta.add_field(self, private=True)
  605. else:
  606. cls._meta.add_field(self)
  607. if self.column:
  608. # Don't override classmethods with the descriptor. This means that
  609. # if you have a classmethod and a field with the same name, then
  610. # such fields can't be deferred (we don't have a check for this).
  611. if not getattr(cls, self.attname, None):
  612. setattr(cls, self.attname, DeferredAttribute(self.attname, cls))
  613. if self.choices:
  614. setattr(cls, 'get_%s_display' % self.name,
  615. curry(cls._get_FIELD_display, field=self))
  616. def get_filter_kwargs_for_object(self, obj):
  617. """
  618. Return a dict that when passed as kwargs to self.model.filter(), would
  619. yield all instances having the same value for this field as obj has.
  620. """
  621. return {self.name: getattr(obj, self.attname)}
  622. def get_attname(self):
  623. return self.name
  624. def get_attname_column(self):
  625. attname = self.get_attname()
  626. column = self.db_column or attname
  627. return attname, column
  628. def get_cache_name(self):
  629. return '_%s_cache' % self.name
  630. def get_internal_type(self):
  631. return self.__class__.__name__
  632. def pre_save(self, model_instance, add):
  633. """
  634. Returns field's value just before saving.
  635. """
  636. return getattr(model_instance, self.attname)
  637. def get_prep_value(self, value):
  638. """
  639. Perform preliminary non-db specific value checks and conversions.
  640. """
  641. if isinstance(value, Promise):
  642. value = value._proxy____cast()
  643. return value
  644. def get_db_prep_value(self, value, connection, prepared=False):
  645. """Returns field's value prepared for interacting with the database
  646. backend.
  647. Used by the default implementations of get_db_prep_save().
  648. """
  649. if not prepared:
  650. value = self.get_prep_value(value)
  651. return value
  652. def get_db_prep_save(self, value, connection):
  653. """
  654. Returns field's value prepared for saving into a database.
  655. """
  656. return self.get_db_prep_value(value, connection=connection,
  657. prepared=False)
  658. def has_default(self):
  659. """
  660. Returns a boolean of whether this field has a default value.
  661. """
  662. return self.default is not NOT_PROVIDED
  663. def get_default(self):
  664. """
  665. Returns the default value for this field.
  666. """
  667. return self._get_default()
  668. @cached_property
  669. def _get_default(self):
  670. if self.has_default():
  671. if callable(self.default):
  672. return self.default
  673. return lambda: self.default
  674. if not self.empty_strings_allowed or self.null and not connection.features.interprets_empty_strings_as_nulls:
  675. return return_None
  676. return str # returns empty string
  677. def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH, limit_choices_to=None):
  678. """Returns choices with a default blank choices included, for use
  679. as SelectField choices for this field."""
  680. blank_defined = False
  681. choices = list(self.choices) if self.choices else []
  682. named_groups = choices and isinstance(choices[0][1], (list, tuple))
  683. if not named_groups:
  684. for choice, __ in choices:
  685. if choice in ('', None):
  686. blank_defined = True
  687. break
  688. first_choice = (blank_choice if include_blank and
  689. not blank_defined else [])
  690. if self.choices:
  691. return first_choice + choices
  692. rel_model = self.remote_field.model
  693. limit_choices_to = limit_choices_to or self.get_limit_choices_to()
  694. if hasattr(self.remote_field, 'get_related_field'):
  695. lst = [(getattr(x, self.remote_field.get_related_field().attname),
  696. smart_text(x))
  697. for x in rel_model._default_manager.complex_filter(
  698. limit_choices_to)]
  699. else:
  700. lst = [(x._get_pk_val(), smart_text(x))
  701. for x in rel_model._default_manager.complex_filter(
  702. limit_choices_to)]
  703. return first_choice + lst
  704. def value_to_string(self, obj):
  705. """
  706. Returns a string value of this field from the passed obj.
  707. This is used by the serialization framework.
  708. """
  709. return force_text(self.value_from_object(obj))
  710. def _get_flatchoices(self):
  711. """Flattened version of choices tuple."""
  712. flat = []
  713. for choice, value in self.choices:
  714. if isinstance(value, (list, tuple)):
  715. flat.extend(value)
  716. else:
  717. flat.append((choice, value))
  718. return flat
  719. flatchoices = property(_get_flatchoices)
  720. def save_form_data(self, instance, data):
  721. setattr(instance, self.name, data)
  722. def formfield(self, form_class=None, choices_form_class=None, **kwargs):
  723. """
  724. Returns a django.forms.Field instance for this database Field.
  725. """
  726. defaults = {'required': not self.blank,
  727. 'label': capfirst(self.verbose_name),
  728. 'help_text': self.help_text}
  729. if self.has_default():
  730. if callable(self.default):
  731. defaults['initial'] = self.default
  732. defaults['show_hidden_initial'] = True
  733. else:
  734. defaults['initial'] = self.get_default()
  735. if self.choices:
  736. # Fields with choices get special treatment.
  737. include_blank = (self.blank or
  738. not (self.has_default() or 'initial' in kwargs))
  739. defaults['choices'] = self.get_choices(include_blank=include_blank)
  740. defaults['coerce'] = self.to_python
  741. if self.null:
  742. defaults['empty_value'] = None
  743. if choices_form_class is not None:
  744. form_class = choices_form_class
  745. else:
  746. form_class = forms.TypedChoiceField
  747. # Many of the subclass-specific formfield arguments (min_value,
  748. # max_value) don't apply for choice fields, so be sure to only pass
  749. # the values that TypedChoiceField will understand.
  750. for k in list(kwargs):
  751. if k not in ('coerce', 'empty_value', 'choices', 'required',
  752. 'widget', 'label', 'initial', 'help_text',
  753. 'error_messages', 'show_hidden_initial'):
  754. del kwargs[k]
  755. defaults.update(kwargs)
  756. if form_class is None:
  757. form_class = forms.CharField
  758. return form_class(**defaults)
  759. def value_from_object(self, obj):
  760. """
  761. Returns the value of this field in the given model instance.
  762. """
  763. return getattr(obj, self.attname)
  764. class AutoField(Field):
  765. description = _("Integer")
  766. empty_strings_allowed = False
  767. default_error_messages = {
  768. 'invalid': _("'%(value)s' value must be an integer."),
  769. }
  770. def __init__(self, *args, **kwargs):
  771. kwargs['blank'] = True
  772. super().__init__(*args, **kwargs)
  773. def check(self, **kwargs):
  774. errors = super().check(**kwargs)
  775. errors.extend(self._check_primary_key())
  776. return errors
  777. def _check_primary_key(self):
  778. if not self.primary_key:
  779. return [
  780. checks.Error(
  781. 'AutoFields must set primary_key=True.',
  782. obj=self,
  783. id='fields.E100',
  784. ),
  785. ]
  786. else:
  787. return []
  788. def deconstruct(self):
  789. name, path, args, kwargs = super().deconstruct()
  790. del kwargs['blank']
  791. kwargs['primary_key'] = True
  792. return name, path, args, kwargs
  793. def get_internal_type(self):
  794. return "AutoField"
  795. def to_python(self, value):
  796. if value is None:
  797. return value
  798. try:
  799. return int(value)
  800. except (TypeError, ValueError):
  801. raise exceptions.ValidationError(
  802. self.error_messages['invalid'],
  803. code='invalid',
  804. params={'value': value},
  805. )
  806. def rel_db_type(self, connection):
  807. return IntegerField().db_type(connection=connection)
  808. def validate(self, value, model_instance):
  809. pass
  810. def get_db_prep_value(self, value, connection, prepared=False):
  811. if not prepared:
  812. value = self.get_prep_value(value)
  813. value = connection.ops.validate_autopk_value(value)
  814. return value
  815. def get_prep_value(self, value):
  816. value = super().get_prep_value(value)
  817. if value is None:
  818. return None
  819. return int(value)
  820. def contribute_to_class(self, cls, name, **kwargs):
  821. assert not cls._meta.auto_field, "A model can't have more than one AutoField."
  822. super().contribute_to_class(cls, name, **kwargs)
  823. cls._meta.auto_field = self
  824. def formfield(self, **kwargs):
  825. return None
  826. class BigAutoField(AutoField):
  827. description = _("Big (8 byte) integer")
  828. def get_internal_type(self):
  829. return "BigAutoField"
  830. def rel_db_type(self, connection):
  831. return BigIntegerField().db_type(connection=connection)
  832. class BooleanField(Field):
  833. empty_strings_allowed = False
  834. default_error_messages = {
  835. 'invalid': _("'%(value)s' value must be either True or False."),
  836. }
  837. description = _("Boolean (Either True or False)")
  838. def __init__(self, *args, **kwargs):
  839. kwargs['blank'] = True
  840. super().__init__(*args, **kwargs)
  841. def check(self, **kwargs):
  842. errors = super().check(**kwargs)
  843. errors.extend(self._check_null(**kwargs))
  844. return errors
  845. def _check_null(self, **kwargs):
  846. if getattr(self, 'null', False):
  847. return [
  848. checks.Error(
  849. 'BooleanFields do not accept null values.',
  850. hint='Use a NullBooleanField instead.',
  851. obj=self,
  852. id='fields.E110',
  853. )
  854. ]
  855. else:
  856. return []
  857. def deconstruct(self):
  858. name, path, args, kwargs = super().deconstruct()
  859. del kwargs['blank']
  860. return name, path, args, kwargs
  861. def get_internal_type(self):
  862. return "BooleanField"
  863. def to_python(self, value):
  864. if value in (True, False):
  865. # if value is 1 or 0 than it's equal to True or False, but we want
  866. # to return a true bool for semantic reasons.
  867. return bool(value)
  868. if value in ('t', 'True', '1'):
  869. return True
  870. if value in ('f', 'False', '0'):
  871. return False
  872. raise exceptions.ValidationError(
  873. self.error_messages['invalid'],
  874. code='invalid',
  875. params={'value': value},
  876. )
  877. def get_prep_value(self, value):
  878. value = super().get_prep_value(value)
  879. if value is None:
  880. return None
  881. return self.to_python(value)
  882. def formfield(self, **kwargs):
  883. # Unlike most fields, BooleanField figures out include_blank from
  884. # self.null instead of self.blank.
  885. if self.choices:
  886. include_blank = not (self.has_default() or 'initial' in kwargs)
  887. defaults = {'choices': self.get_choices(include_blank=include_blank)}
  888. else:
  889. defaults = {'form_class': forms.BooleanField}
  890. defaults.update(kwargs)
  891. return super().formfield(**defaults)
  892. class CharField(Field):
  893. description = _("String (up to %(max_length)s)")
  894. def __init__(self, *args, **kwargs):
  895. super().__init__(*args, **kwargs)
  896. self.validators.append(validators.MaxLengthValidator(self.max_length))
  897. def check(self, **kwargs):
  898. errors = super().check(**kwargs)
  899. errors.extend(self._check_max_length_attribute(**kwargs))
  900. return errors
  901. def _check_max_length_attribute(self, **kwargs):
  902. if self.max_length is None:
  903. return [
  904. checks.Error(
  905. "CharFields must define a 'max_length' attribute.",
  906. obj=self,
  907. id='fields.E120',
  908. )
  909. ]
  910. elif not isinstance(self.max_length, int) or self.max_length <= 0:
  911. return [
  912. checks.Error(
  913. "'max_length' must be a positive integer.",
  914. obj=self,
  915. id='fields.E121',
  916. )
  917. ]
  918. else:
  919. return []
  920. def get_internal_type(self):
  921. return "CharField"
  922. def to_python(self, value):
  923. if isinstance(value, str) or value is None:
  924. return value
  925. return force_text(value)
  926. def get_prep_value(self, value):
  927. value = super().get_prep_value(value)
  928. return self.to_python(value)
  929. def formfield(self, **kwargs):
  930. # Passing max_length to forms.CharField means that the value's length
  931. # will be validated twice. This is considered acceptable since we want
  932. # the value in the form field (to pass into widget for example).
  933. defaults = {'max_length': self.max_length}
  934. # TODO: Handle multiple backends with different feature flags.
  935. if self.null and not connection.features.interprets_empty_strings_as_nulls:
  936. defaults['empty_value'] = None
  937. defaults.update(kwargs)
  938. return super().formfield(**defaults)
  939. class CommaSeparatedIntegerField(CharField):
  940. default_validators = [validators.validate_comma_separated_integer_list]
  941. description = _("Comma-separated integers")
  942. system_check_removed_details = {
  943. 'msg': (
  944. 'CommaSeparatedIntegerField is removed except for support in '
  945. 'historical migrations.'
  946. ),
  947. 'hint': (
  948. 'Use CharField(validators=[validate_comma_separated_integer_list]) '
  949. 'instead.'
  950. ),
  951. 'id': 'fields.E901',
  952. }
  953. class DateTimeCheckMixin:
  954. def check(self, **kwargs):
  955. errors = super().check(**kwargs)
  956. errors.extend(self._check_mutually_exclusive_options())
  957. errors.extend(self._check_fix_default_value())
  958. return errors
  959. def _check_mutually_exclusive_options(self):
  960. # auto_now, auto_now_add, and default are mutually exclusive
  961. # options. The use of more than one of these options together
  962. # will trigger an Error
  963. mutually_exclusive_options = [self.auto_now_add, self.auto_now, self.has_default()]
  964. enabled_options = [option not in (None, False) for option in mutually_exclusive_options].count(True)
  965. if enabled_options > 1:
  966. return [
  967. checks.Error(
  968. "The options auto_now, auto_now_add, and default "
  969. "are mutually exclusive. Only one of these options "
  970. "may be present.",
  971. obj=self,
  972. id='fields.E160',
  973. )
  974. ]
  975. else:
  976. return []
  977. def _check_fix_default_value(self):
  978. return []
  979. class DateField(DateTimeCheckMixin, Field):
  980. empty_strings_allowed = False
  981. default_error_messages = {
  982. 'invalid': _("'%(value)s' value has an invalid date format. It must be "
  983. "in YYYY-MM-DD format."),
  984. 'invalid_date': _("'%(value)s' value has the correct format (YYYY-MM-DD) "
  985. "but it is an invalid date."),
  986. }
  987. description = _("Date (without time)")
  988. def __init__(self, verbose_name=None, name=None, auto_now=False,
  989. auto_now_add=False, **kwargs):
  990. self.auto_now, self.auto_now_add = auto_now, auto_now_add
  991. if auto_now or auto_now_add:
  992. kwargs['editable'] = False
  993. kwargs['blank'] = True
  994. super().__init__(verbose_name, name, **kwargs)
  995. def _check_fix_default_value(self):
  996. """
  997. Adds a warning to the checks framework stating, that using an actual
  998. date or datetime value is probably wrong; it's only being evaluated on
  999. server start-up.
  1000. For details see ticket #21905
  1001. """
  1002. if not self.has_default():
  1003. return []
  1004. now = timezone.now()
  1005. if not timezone.is_naive(now):
  1006. now = timezone.make_naive(now, timezone.utc)
  1007. value = self.default
  1008. if isinstance(value, datetime.datetime):
  1009. if not timezone.is_naive(value):
  1010. value = timezone.make_naive(value, timezone.utc)
  1011. value = value.date()
  1012. elif isinstance(value, datetime.date):
  1013. # Nothing to do, as dates don't have tz information
  1014. pass
  1015. else:
  1016. # No explicit date / datetime value -- no checks necessary
  1017. return []
  1018. offset = datetime.timedelta(days=1)
  1019. lower = (now - offset).date()
  1020. upper = (now + offset).date()
  1021. if lower <= value <= upper:
  1022. return [
  1023. checks.Warning(
  1024. 'Fixed default value provided.',
  1025. hint='It seems you set a fixed date / time / datetime '
  1026. 'value as default for this field. This may not be '
  1027. 'what you want. If you want to have the current date '
  1028. 'as default, use `django.utils.timezone.now`',
  1029. obj=self,
  1030. id='fields.W161',
  1031. )
  1032. ]
  1033. return []
  1034. def deconstruct(self):
  1035. name, path, args, kwargs = super().deconstruct()
  1036. if self.auto_now:
  1037. kwargs['auto_now'] = True
  1038. if self.auto_now_add:
  1039. kwargs['auto_now_add'] = True
  1040. if self.auto_now or self.auto_now_add:
  1041. del kwargs['editable']
  1042. del kwargs['blank']
  1043. return name, path, args, kwargs
  1044. def get_internal_type(self):
  1045. return "DateField"
  1046. def to_python(self, value):
  1047. if value is None:
  1048. return value
  1049. if isinstance(value, datetime.datetime):
  1050. if settings.USE_TZ and timezone.is_aware(value):
  1051. # Convert aware datetimes to the default time zone
  1052. # before casting them to dates (#17742).
  1053. default_timezone = timezone.get_default_timezone()
  1054. value = timezone.make_naive(value, default_timezone)
  1055. return value.date()
  1056. if isinstance(value, datetime.date):
  1057. return value
  1058. try:
  1059. parsed = parse_date(value)
  1060. if parsed is not None:
  1061. return parsed
  1062. except ValueError:
  1063. raise exceptions.ValidationError(
  1064. self.error_messages['invalid_date'],
  1065. code='invalid_date',
  1066. params={'value': value},
  1067. )
  1068. raise exceptions.ValidationError(
  1069. self.error_messages['invalid'],
  1070. code='invalid',
  1071. params={'value': value},
  1072. )
  1073. def pre_save(self, model_instance, add):
  1074. if self.auto_now or (self.auto_now_add and add):
  1075. value = datetime.date.today()
  1076. setattr(model_instance, self.attname, value)
  1077. return value
  1078. else:
  1079. return super().pre_save(model_instance, add)
  1080. def contribute_to_class(self, cls, name, **kwargs):
  1081. super().contribute_to_class(cls, name, **kwargs)
  1082. if not self.null:
  1083. setattr(
  1084. cls, 'get_next_by_%s' % self.name,
  1085. curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=True)
  1086. )
  1087. setattr(
  1088. cls, 'get_previous_by_%s' % self.name,
  1089. curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=False)
  1090. )
  1091. def get_prep_value(self, value):
  1092. value = super().get_prep_value(value)
  1093. return self.to_python(value)
  1094. def get_db_prep_value(self, value, connection, prepared=False):
  1095. # Casts dates into the format expected by the backend
  1096. if not prepared:
  1097. value = self.get_prep_value(value)
  1098. return connection.ops.adapt_datefield_value(value)
  1099. def value_to_string(self, obj):
  1100. val = self.value_from_object(obj)
  1101. return '' if val is None else val.isoformat()
  1102. def formfield(self, **kwargs):
  1103. defaults = {'form_class': forms.DateField}
  1104. defaults.update(kwargs)
  1105. return super().formfield(**defaults)
  1106. class DateTimeField(DateField):
  1107. empty_strings_allowed = False
  1108. default_error_messages = {
  1109. 'invalid': _("'%(value)s' value has an invalid format. It must be in "
  1110. "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."),
  1111. 'invalid_date': _("'%(value)s' value has the correct format "
  1112. "(YYYY-MM-DD) but it is an invalid date."),
  1113. 'invalid_datetime': _("'%(value)s' value has the correct format "
  1114. "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
  1115. "but it is an invalid date/time."),
  1116. }
  1117. description = _("Date (with time)")
  1118. # __init__ is inherited from DateField
  1119. def _check_fix_default_value(self):
  1120. """
  1121. Adds a warning to the checks framework stating, that using an actual
  1122. date or datetime value is probably wrong; it's only being evaluated on
  1123. server start-up.
  1124. For details see ticket #21905
  1125. """
  1126. if not self.has_default():
  1127. return []
  1128. now = timezone.now()
  1129. if not timezone.is_naive(now):
  1130. now = timezone.make_naive(now, timezone.utc)
  1131. value = self.default
  1132. if isinstance(value, datetime.datetime):
  1133. second_offset = datetime.timedelta(seconds=10)
  1134. lower = now - second_offset
  1135. upper = now + second_offset
  1136. if timezone.is_aware(value):
  1137. value = timezone.make_naive(value, timezone.utc)
  1138. elif isinstance(value, datetime.date):
  1139. second_offset = datetime.timedelta(seconds=10)
  1140. lower = now - second_offset
  1141. lower = datetime.datetime(lower.year, lower.month, lower.day)
  1142. upper = now + second_offset
  1143. upper = datetime.datetime(upper.year, upper.month, upper.day)
  1144. value = datetime.datetime(value.year, value.month, value.day)
  1145. else:
  1146. # No explicit date / datetime value -- no checks necessary
  1147. return []
  1148. if lower <= value <= upper:
  1149. return [
  1150. checks.Warning(
  1151. 'Fixed default value provided.',
  1152. hint='It seems you set a fixed date / time / datetime '
  1153. 'value as default for this field. This may not be '
  1154. 'what you want. If you want to have the current date '
  1155. 'as default, use `django.utils.timezone.now`',
  1156. obj=self,
  1157. id='fields.W161',
  1158. )
  1159. ]
  1160. return []
  1161. def get_internal_type(self):
  1162. return "DateTimeField"
  1163. def to_python(self, value):
  1164. if value is None:
  1165. return value
  1166. if isinstance(value, datetime.datetime):
  1167. return value
  1168. if isinstance(value, datetime.date):
  1169. value = datetime.datetime(value.year, value.month, value.day)
  1170. if settings.USE_TZ:
  1171. # For backwards compatibility, interpret naive datetimes in
  1172. # local time. This won't work during DST change, but we can't
  1173. # do much about it, so we let the exceptions percolate up the
  1174. # call stack.
  1175. warnings.warn("DateTimeField %s.%s received a naive datetime "
  1176. "(%s) while time zone support is active." %
  1177. (self.model.__name__, self.name, value),
  1178. RuntimeWarning)
  1179. default_timezone = timezone.get_default_timezone()
  1180. value = timezone.make_aware(value, default_timezone)
  1181. return value
  1182. try:
  1183. parsed = parse_datetime(value)
  1184. if parsed is not None:
  1185. return parsed
  1186. except ValueError:
  1187. raise exceptions.ValidationError(
  1188. self.error_messages['invalid_datetime'],
  1189. code='invalid_datetime',
  1190. params={'value': value},
  1191. )
  1192. try:
  1193. parsed = parse_date(value)
  1194. if parsed is not None:
  1195. return datetime.datetime(parsed.year, parsed.month, parsed.day)
  1196. except ValueError:
  1197. raise exceptions.ValidationError(
  1198. self.error_messages['invalid_date'],
  1199. code='invalid_date',
  1200. params={'value': value},
  1201. )
  1202. raise exceptions.ValidationError(
  1203. self.error_messages['invalid'],
  1204. code='invalid',
  1205. params={'value': value},
  1206. )
  1207. def pre_save(self, model_instance, add):
  1208. if self.auto_now or (self.auto_now_add and add):
  1209. value = timezone.now()
  1210. setattr(model_instance, self.attname, value)
  1211. return value
  1212. else:
  1213. return super().pre_save(model_instance, add)
  1214. # contribute_to_class is inherited from DateField, it registers
  1215. # get_next_by_FOO and get_prev_by_FOO
  1216. def get_prep_value(self, value):
  1217. value = super().get_prep_value(value)
  1218. value = self.to_python(value)
  1219. if value is not None and settings.USE_TZ and timezone.is_naive(value):
  1220. # For backwards compatibility, interpret naive datetimes in local
  1221. # time. This won't work during DST change, but we can't do much
  1222. # about it, so we let the exceptions percolate up the call stack.
  1223. try:
  1224. name = '%s.%s' % (self.model.__name__, self.name)
  1225. except AttributeError:
  1226. name = '(unbound)'
  1227. warnings.warn("DateTimeField %s received a naive datetime (%s)"
  1228. " while time zone support is active." %
  1229. (name, value),
  1230. RuntimeWarning)
  1231. default_timezone = timezone.get_default_timezone()
  1232. value = timezone.make_aware(value, default_timezone)
  1233. return value
  1234. def get_db_prep_value(self, value, connection, prepared=False):
  1235. # Casts datetimes into the format expected by the backend
  1236. if not prepared:
  1237. value = self.get_prep_value(value)
  1238. return connection.ops.adapt_datetimefield_value(value)
  1239. def value_to_string(self, obj):
  1240. val = self.value_from_object(obj)
  1241. return '' if val is None else val.isoformat()
  1242. def formfield(self, **kwargs):
  1243. defaults = {'form_class': forms.DateTimeField}
  1244. defaults.update(kwargs)
  1245. return super().formfield(**defaults)
  1246. class DecimalField(Field):
  1247. empty_strings_allowed = False
  1248. default_error_messages = {
  1249. 'invalid': _("'%(value)s' value must be a decimal number."),
  1250. }
  1251. description = _("Decimal number")
  1252. def __init__(self, verbose_name=None, name=None, max_digits=None,
  1253. decimal_places=None, **kwargs):
  1254. self.max_digits, self.decimal_places = max_digits, decimal_places
  1255. super().__init__(verbose_name, name, **kwargs)
  1256. def check(self, **kwargs):
  1257. errors = super().check(**kwargs)
  1258. digits_errors = self._check_decimal_places()
  1259. digits_errors.extend(self._check_max_digits())
  1260. if not digits_errors:
  1261. errors.extend(self._check_decimal_places_and_max_digits(**kwargs))
  1262. else:
  1263. errors.extend(digits_errors)
  1264. return errors
  1265. def _check_decimal_places(self):
  1266. try:
  1267. decimal_places = int(self.decimal_places)
  1268. if decimal_places < 0:
  1269. raise ValueError()
  1270. except TypeError:
  1271. return [
  1272. checks.Error(
  1273. "DecimalFields must define a 'decimal_places' attribute.",
  1274. obj=self,
  1275. id='fields.E130',
  1276. )
  1277. ]
  1278. except ValueError:
  1279. return [
  1280. checks.Error(
  1281. "'decimal_places' must be a non-negative integer.",
  1282. obj=self,
  1283. id='fields.E131',
  1284. )
  1285. ]
  1286. else:
  1287. return []
  1288. def _check_max_digits(self):
  1289. try:
  1290. max_digits = int(self.max_digits)
  1291. if max_digits <= 0:
  1292. raise ValueError()
  1293. except TypeError:
  1294. return [
  1295. checks.Error(
  1296. "DecimalFields must define a 'max_digits' attribute.",
  1297. obj=self,
  1298. id='fields.E132',
  1299. )
  1300. ]
  1301. except ValueError:
  1302. return [
  1303. checks.Error(
  1304. "'max_digits' must be a positive integer.",
  1305. obj=self,
  1306. id='fields.E133',
  1307. )
  1308. ]
  1309. else:
  1310. return []
  1311. def _check_decimal_places_and_max_digits(self, **kwargs):
  1312. if int(self.decimal_places) > int(self.max_digits):
  1313. return [
  1314. checks.Error(
  1315. "'max_digits' must be greater or equal to 'decimal_places'.",
  1316. obj=self,
  1317. id='fields.E134',
  1318. )
  1319. ]
  1320. return []
  1321. @cached_property
  1322. def validators(self):
  1323. return super().validators + [
  1324. validators.DecimalValidator(self.max_digits, self.decimal_places)
  1325. ]
  1326. def deconstruct(self):
  1327. name, path, args, kwargs = super().deconstruct()
  1328. if self.max_digits is not None:
  1329. kwargs['max_digits'] = self.max_digits
  1330. if self.decimal_places is not None:
  1331. kwargs['decimal_places'] = self.decimal_places
  1332. return name, path, args, kwargs
  1333. def get_internal_type(self):
  1334. return "DecimalField"
  1335. def to_python(self, value):
  1336. if value is None:
  1337. return value
  1338. try:
  1339. return decimal.Decimal(value)
  1340. except decimal.InvalidOperation:
  1341. raise exceptions.ValidationError(
  1342. self.error_messages['invalid'],
  1343. code='invalid',
  1344. params={'value': value},
  1345. )
  1346. def _format(self, value):
  1347. if isinstance(value, str):
  1348. return value
  1349. else:
  1350. return self.format_number(value)
  1351. def format_number(self, value):
  1352. """
  1353. Formats a number into a string with the requisite number of digits and
  1354. decimal places.
  1355. """
  1356. # Method moved to django.db.backends.utils.
  1357. #
  1358. # It is preserved because it is used by the oracle backend
  1359. # (django.db.backends.oracle.query), and also for
  1360. # backwards-compatibility with any external code which may have used
  1361. # this method.
  1362. from django.db.backends import utils
  1363. return utils.format_number(value, self.max_digits, self.decimal_places)
  1364. def get_db_prep_save(self, value, connection):
  1365. return connection.ops.adapt_decimalfield_value(self.to_python(value), self.max_digits, self.decimal_places)
  1366. def get_prep_value(self, value):
  1367. value = super().get_prep_value(value)
  1368. return self.to_python(value)
  1369. def formfield(self, **kwargs):
  1370. defaults = {
  1371. 'max_digits': self.max_digits,
  1372. 'decimal_places': self.decimal_places,
  1373. 'form_class': forms.DecimalField,
  1374. }
  1375. defaults.update(kwargs)
  1376. return super().formfield(**defaults)
  1377. class DurationField(Field):
  1378. """Stores timedelta objects.
  1379. Uses interval on postgres, INVERAL DAY TO SECOND on Oracle, and bigint of
  1380. microseconds on other databases.
  1381. """
  1382. empty_strings_allowed = False
  1383. default_error_messages = {
  1384. 'invalid': _("'%(value)s' value has an invalid format. It must be in "
  1385. "[DD] [HH:[MM:]]ss[.uuuuuu] format.")
  1386. }
  1387. description = _("Duration")
  1388. def get_internal_type(self):
  1389. return "DurationField"
  1390. def to_python(self, value):
  1391. if value is None:
  1392. return value
  1393. if isinstance(value, datetime.timedelta):
  1394. return value
  1395. try:
  1396. parsed = parse_duration(value)
  1397. except ValueError:
  1398. pass
  1399. else:
  1400. if parsed is not None:
  1401. return parsed
  1402. raise exceptions.ValidationError(
  1403. self.error_messages['invalid'],
  1404. code='invalid',
  1405. params={'value': value},
  1406. )
  1407. def get_db_prep_value(self, value, connection, prepared=False):
  1408. if connection.features.has_native_duration_field:
  1409. return value
  1410. if value is None:
  1411. return None
  1412. # Discard any fractional microseconds due to floating point arithmetic.
  1413. return int(round(value.total_seconds() * 1000000))
  1414. def get_db_converters(self, connection):
  1415. converters = []
  1416. if not connection.features.has_native_duration_field:
  1417. converters.append(connection.ops.convert_durationfield_value)
  1418. return converters + super().get_db_converters(connection)
  1419. def value_to_string(self, obj):
  1420. val = self.value_from_object(obj)
  1421. return '' if val is None else duration_string(val)
  1422. def formfield(self, **kwargs):
  1423. defaults = {
  1424. 'form_class': forms.DurationField,
  1425. }
  1426. defaults.update(kwargs)
  1427. return super().formfield(**defaults)
  1428. class EmailField(CharField):
  1429. default_validators = [validators.validate_email]
  1430. description = _("Email address")
  1431. def __init__(self, *args, **kwargs):
  1432. # max_length=254 to be compliant with RFCs 3696 and 5321
  1433. kwargs['max_length'] = kwargs.get('max_length', 254)
  1434. super().__init__(*args, **kwargs)
  1435. def deconstruct(self):
  1436. name, path, args, kwargs = super().deconstruct()
  1437. # We do not exclude max_length if it matches default as we want to change
  1438. # the default in future.
  1439. return name, path, args, kwargs
  1440. def formfield(self, **kwargs):
  1441. # As with CharField, this will cause email validation to be performed
  1442. # twice.
  1443. defaults = {
  1444. 'form_class': forms.EmailField,
  1445. }
  1446. defaults.update(kwargs)
  1447. return super().formfield(**defaults)
  1448. class FilePathField(Field):
  1449. description = _("File path")
  1450. def __init__(self, verbose_name=None, name=None, path='', match=None,
  1451. recursive=False, allow_files=True, allow_folders=False, **kwargs):
  1452. self.path, self.match, self.recursive = path, match, recursive
  1453. self.allow_files, self.allow_folders = allow_files, allow_folders
  1454. kwargs['max_length'] = kwargs.get('max_length', 100)
  1455. super().__init__(verbose_name, name, **kwargs)
  1456. def check(self, **kwargs):
  1457. errors = super().check(**kwargs)
  1458. errors.extend(self._check_allowing_files_or_folders(**kwargs))
  1459. return errors
  1460. def _check_allowing_files_or_folders(self, **kwargs):
  1461. if not self.allow_files and not self.allow_folders:
  1462. return [
  1463. checks.Error(
  1464. "FilePathFields must have either 'allow_files' or 'allow_folders' set to True.",
  1465. obj=self,
  1466. id='fields.E140',
  1467. )
  1468. ]
  1469. return []
  1470. def deconstruct(self):
  1471. name, path, args, kwargs = super().deconstruct()
  1472. if self.path != '':
  1473. kwargs['path'] = self.path
  1474. if self.match is not None:
  1475. kwargs['match'] = self.match
  1476. if self.recursive is not False:
  1477. kwargs['recursive'] = self.recursive
  1478. if self.allow_files is not True:
  1479. kwargs['allow_files'] = self.allow_files
  1480. if self.allow_folders is not False:
  1481. kwargs['allow_folders'] = self.allow_folders
  1482. if kwargs.get("max_length") == 100:
  1483. del kwargs["max_length"]
  1484. return name, path, args, kwargs
  1485. def get_prep_value(self, value):
  1486. value = super().get_prep_value(value)
  1487. if value is None:
  1488. return None
  1489. return str(value)
  1490. def formfield(self, **kwargs):
  1491. defaults = {
  1492. 'path': self.path,
  1493. 'match': self.match,
  1494. 'recursive': self.recursive,
  1495. 'form_class': forms.FilePathField,
  1496. 'allow_files': self.allow_files,
  1497. 'allow_folders': self.allow_folders,
  1498. }
  1499. defaults.update(kwargs)
  1500. return super().formfield(**defaults)
  1501. def get_internal_type(self):
  1502. return "FilePathField"
  1503. class FloatField(Field):
  1504. empty_strings_allowed = False
  1505. default_error_messages = {
  1506. 'invalid': _("'%(value)s' value must be a float."),
  1507. }
  1508. description = _("Floating point number")
  1509. def get_prep_value(self, value):
  1510. value = super().get_prep_value(value)
  1511. if value is None:
  1512. return None
  1513. return float(value)
  1514. def get_internal_type(self):
  1515. return "FloatField"
  1516. def to_python(self, value):
  1517. if value is None:
  1518. return value
  1519. try:
  1520. return float(value)
  1521. except (TypeError, ValueError):
  1522. raise exceptions.ValidationError(
  1523. self.error_messages['invalid'],
  1524. code='invalid',
  1525. params={'value': value},
  1526. )
  1527. def formfield(self, **kwargs):
  1528. defaults = {'form_class': forms.FloatField}
  1529. defaults.update(kwargs)
  1530. return super().formfield(**defaults)
  1531. class IntegerField(Field):
  1532. empty_strings_allowed = False
  1533. default_error_messages = {
  1534. 'invalid': _("'%(value)s' value must be an integer."),
  1535. }
  1536. description = _("Integer")
  1537. def check(self, **kwargs):
  1538. errors = super().check(**kwargs)
  1539. errors.extend(self._check_max_length_warning())
  1540. return errors
  1541. def _check_max_length_warning(self):
  1542. if self.max_length is not None:
  1543. return [
  1544. checks.Warning(
  1545. "'max_length' is ignored when used with IntegerField",
  1546. hint="Remove 'max_length' from field",
  1547. obj=self,
  1548. id='fields.W122',
  1549. )
  1550. ]
  1551. return []
  1552. @cached_property
  1553. def validators(self):
  1554. # These validators can't be added at field initialization time since
  1555. # they're based on values retrieved from `connection`.
  1556. validators_ = super().validators
  1557. internal_type = self.get_internal_type()
  1558. min_value, max_value = connection.ops.integer_field_range(internal_type)
  1559. if min_value is not None:
  1560. for validator in validators_:
  1561. if isinstance(validator, validators.MinValueValidator) and validator.limit_value >= min_value:
  1562. break
  1563. else:
  1564. validators_.append(validators.MinValueValidator(min_value))
  1565. if max_value is not None:
  1566. for validator in validators_:
  1567. if isinstance(validator, validators.MaxValueValidator) and validator.limit_value <= max_value:
  1568. break
  1569. else:
  1570. validators_.append(validators.MaxValueValidator(max_value))
  1571. return validators_
  1572. def get_prep_value(self, value):
  1573. value = super().get_prep_value(value)
  1574. if value is None:
  1575. return None
  1576. return int(value)
  1577. def get_internal_type(self):
  1578. return "IntegerField"
  1579. def to_python(self, value):
  1580. if value is None:
  1581. return value
  1582. try:
  1583. return int(value)
  1584. except (TypeError, ValueError):
  1585. raise exceptions.ValidationError(
  1586. self.error_messages['invalid'],
  1587. code='invalid',
  1588. params={'value': value},
  1589. )
  1590. def formfield(self, **kwargs):
  1591. defaults = {'form_class': forms.IntegerField}
  1592. defaults.update(kwargs)
  1593. return super().formfield(**defaults)
  1594. class BigIntegerField(IntegerField):
  1595. empty_strings_allowed = False
  1596. description = _("Big (8 byte) integer")
  1597. MAX_BIGINT = 9223372036854775807
  1598. def get_internal_type(self):
  1599. return "BigIntegerField"
  1600. def formfield(self, **kwargs):
  1601. defaults = {'min_value': -BigIntegerField.MAX_BIGINT - 1,
  1602. 'max_value': BigIntegerField.MAX_BIGINT}
  1603. defaults.update(kwargs)
  1604. return super().formfield(**defaults)
  1605. class IPAddressField(Field):
  1606. empty_strings_allowed = False
  1607. description = _("IPv4 address")
  1608. system_check_removed_details = {
  1609. 'msg': (
  1610. 'IPAddressField has been removed except for support in '
  1611. 'historical migrations.'
  1612. ),
  1613. 'hint': 'Use GenericIPAddressField instead.',
  1614. 'id': 'fields.E900',
  1615. }
  1616. def __init__(self, *args, **kwargs):
  1617. kwargs['max_length'] = 15
  1618. super().__init__(*args, **kwargs)
  1619. def deconstruct(self):
  1620. name, path, args, kwargs = super().deconstruct()
  1621. del kwargs['max_length']
  1622. return name, path, args, kwargs
  1623. def get_prep_value(self, value):
  1624. value = super().get_prep_value(value)
  1625. if value is None:
  1626. return None
  1627. return str(value)
  1628. def get_internal_type(self):
  1629. return "IPAddressField"
  1630. class GenericIPAddressField(Field):
  1631. empty_strings_allowed = False
  1632. description = _("IP address")
  1633. default_error_messages = {}
  1634. def __init__(self, verbose_name=None, name=None, protocol='both',
  1635. unpack_ipv4=False, *args, **kwargs):
  1636. self.unpack_ipv4 = unpack_ipv4
  1637. self.protocol = protocol
  1638. self.default_validators, invalid_error_message = \
  1639. validators.ip_address_validators(protocol, unpack_ipv4)
  1640. self.default_error_messages['invalid'] = invalid_error_message
  1641. kwargs['max_length'] = 39
  1642. super().__init__(verbose_name, name, *args, **kwargs)
  1643. def check(self, **kwargs):
  1644. errors = super().check(**kwargs)
  1645. errors.extend(self._check_blank_and_null_values(**kwargs))
  1646. return errors
  1647. def _check_blank_and_null_values(self, **kwargs):
  1648. if not getattr(self, 'null', False) and getattr(self, 'blank', False):
  1649. return [
  1650. checks.Error(
  1651. 'GenericIPAddressFields cannot have blank=True if null=False, '
  1652. 'as blank values are stored as nulls.',
  1653. obj=self,
  1654. id='fields.E150',
  1655. )
  1656. ]
  1657. return []
  1658. def deconstruct(self):
  1659. name, path, args, kwargs = super().deconstruct()
  1660. if self.unpack_ipv4 is not False:
  1661. kwargs['unpack_ipv4'] = self.unpack_ipv4
  1662. if self.protocol != "both":
  1663. kwargs['protocol'] = self.protocol
  1664. if kwargs.get("max_length") == 39:
  1665. del kwargs['max_length']
  1666. return name, path, args, kwargs
  1667. def get_internal_type(self):
  1668. return "GenericIPAddressField"
  1669. def to_python(self, value):
  1670. if value is None:
  1671. return None
  1672. if not isinstance(value, str):
  1673. value = force_text(value)
  1674. value = value.strip()
  1675. if ':' in value:
  1676. return clean_ipv6_address(value, self.unpack_ipv4, self.error_messages['invalid'])
  1677. return value
  1678. def get_db_prep_value(self, value, connection, prepared=False):
  1679. if not prepared:
  1680. value = self.get_prep_value(value)
  1681. return connection.ops.adapt_ipaddressfield_value(value)
  1682. def get_prep_value(self, value):
  1683. value = super().get_prep_value(value)
  1684. if value is None:
  1685. return None
  1686. if value and ':' in value:
  1687. try:
  1688. return clean_ipv6_address(value, self.unpack_ipv4)
  1689. except exceptions.ValidationError:
  1690. pass
  1691. return str(value)
  1692. def formfield(self, **kwargs):
  1693. defaults = {
  1694. 'protocol': self.protocol,
  1695. 'form_class': forms.GenericIPAddressField,
  1696. }
  1697. defaults.update(kwargs)
  1698. return super().formfield(**defaults)
  1699. class NullBooleanField(Field):
  1700. empty_strings_allowed = False
  1701. default_error_messages = {
  1702. 'invalid': _("'%(value)s' value must be either None, True or False."),
  1703. }
  1704. description = _("Boolean (Either True, False or None)")
  1705. def __init__(self, *args, **kwargs):
  1706. kwargs['null'] = True
  1707. kwargs['blank'] = True
  1708. super().__init__(*args, **kwargs)
  1709. def deconstruct(self):
  1710. name, path, args, kwargs = super().deconstruct()
  1711. del kwargs['null']
  1712. del kwargs['blank']
  1713. return name, path, args, kwargs
  1714. def get_internal_type(self):
  1715. return "NullBooleanField"
  1716. def to_python(self, value):
  1717. if value is None:
  1718. return None
  1719. if value in (True, False):
  1720. return bool(value)
  1721. if value in ('None',):
  1722. return None
  1723. if value in ('t', 'True', '1'):
  1724. return True
  1725. if value in ('f', 'False', '0'):
  1726. return False
  1727. raise exceptions.ValidationError(
  1728. self.error_messages['invalid'],
  1729. code='invalid',
  1730. params={'value': value},
  1731. )
  1732. def get_prep_value(self, value):
  1733. value = super().get_prep_value(value)
  1734. if value is None:
  1735. return None
  1736. return self.to_python(value)
  1737. def formfield(self, **kwargs):
  1738. defaults = {'form_class': forms.NullBooleanField}
  1739. defaults.update(kwargs)
  1740. return super().formfield(**defaults)
  1741. class PositiveIntegerRelDbTypeMixin:
  1742. def rel_db_type(self, connection):
  1743. """
  1744. Return the data type that a related field pointing to this field should
  1745. use. In most cases, a foreign key pointing to a positive integer
  1746. primary key will have an integer column data type but some databases
  1747. (e.g. MySQL) have an unsigned integer type. In that case
  1748. (related_fields_match_type=True), the primary key should return its
  1749. db_type.
  1750. """
  1751. if connection.features.related_fields_match_type:
  1752. return self.db_type(connection)
  1753. else:
  1754. return IntegerField().db_type(connection=connection)
  1755. class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField):
  1756. description = _("Positive integer")
  1757. def get_internal_type(self):
  1758. return "PositiveIntegerField"
  1759. def formfield(self, **kwargs):
  1760. defaults = {'min_value': 0}
  1761. defaults.update(kwargs)
  1762. return super().formfield(**defaults)
  1763. class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField):
  1764. description = _("Positive small integer")
  1765. def get_internal_type(self):
  1766. return "PositiveSmallIntegerField"
  1767. def formfield(self, **kwargs):
  1768. defaults = {'min_value': 0}
  1769. defaults.update(kwargs)
  1770. return super().formfield(**defaults)
  1771. class SlugField(CharField):
  1772. default_validators = [validators.validate_slug]
  1773. description = _("Slug (up to %(max_length)s)")
  1774. def __init__(self, *args, max_length=50, db_index=True, allow_unicode=False, **kwargs):
  1775. self.allow_unicode = allow_unicode
  1776. if self.allow_unicode:
  1777. self.default_validators = [validators.validate_unicode_slug]
  1778. super().__init__(*args, max_length=max_length, db_index=db_index, **kwargs)
  1779. def deconstruct(self):
  1780. name, path, args, kwargs = super().deconstruct()
  1781. if kwargs.get("max_length") == 50:
  1782. del kwargs['max_length']
  1783. if self.db_index is False:
  1784. kwargs['db_index'] = False
  1785. else:
  1786. del kwargs['db_index']
  1787. if self.allow_unicode is not False:
  1788. kwargs['allow_unicode'] = self.allow_unicode
  1789. return name, path, args, kwargs
  1790. def get_internal_type(self):
  1791. return "SlugField"
  1792. def formfield(self, **kwargs):
  1793. defaults = {'form_class': forms.SlugField, 'allow_unicode': self.allow_unicode}
  1794. defaults.update(kwargs)
  1795. return super().formfield(**defaults)
  1796. class SmallIntegerField(IntegerField):
  1797. description = _("Small integer")
  1798. def get_internal_type(self):
  1799. return "SmallIntegerField"
  1800. class TextField(Field):
  1801. description = _("Text")
  1802. def get_internal_type(self):
  1803. return "TextField"
  1804. def to_python(self, value):
  1805. if isinstance(value, str) or value is None:
  1806. return value
  1807. return force_text(value)
  1808. def get_prep_value(self, value):
  1809. value = super().get_prep_value(value)
  1810. return self.to_python(value)
  1811. def formfield(self, **kwargs):
  1812. # Passing max_length to forms.CharField means that the value's length
  1813. # will be validated twice. This is considered acceptable since we want
  1814. # the value in the form field (to pass into widget for example).
  1815. defaults = {'max_length': self.max_length, 'widget': forms.Textarea}
  1816. defaults.update(kwargs)
  1817. return super().formfield(**defaults)
  1818. class TimeField(DateTimeCheckMixin, Field):
  1819. empty_strings_allowed = False
  1820. default_error_messages = {
  1821. 'invalid': _("'%(value)s' value has an invalid format. It must be in "
  1822. "HH:MM[:ss[.uuuuuu]] format."),
  1823. 'invalid_time': _("'%(value)s' value has the correct format "
  1824. "(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."),
  1825. }
  1826. description = _("Time")
  1827. def __init__(self, verbose_name=None, name=None, auto_now=False,
  1828. auto_now_add=False, **kwargs):
  1829. self.auto_now, self.auto_now_add = auto_now, auto_now_add
  1830. if auto_now or auto_now_add:
  1831. kwargs['editable'] = False
  1832. kwargs['blank'] = True
  1833. super().__init__(verbose_name, name, **kwargs)
  1834. def _check_fix_default_value(self):
  1835. """
  1836. Adds a warning to the checks framework stating, that using an actual
  1837. time or datetime value is probably wrong; it's only being evaluated on
  1838. server start-up.
  1839. For details see ticket #21905
  1840. """
  1841. if not self.has_default():
  1842. return []
  1843. now = timezone.now()
  1844. if not timezone.is_naive(now):
  1845. now = timezone.make_naive(now, timezone.utc)
  1846. value = self.default
  1847. if isinstance(value, datetime.datetime):
  1848. second_offset = datetime.timedelta(seconds=10)
  1849. lower = now - second_offset
  1850. upper = now + second_offset
  1851. if timezone.is_aware(value):
  1852. value = timezone.make_naive(value, timezone.utc)
  1853. elif isinstance(value, datetime.time):
  1854. second_offset = datetime.timedelta(seconds=10)
  1855. lower = now - second_offset
  1856. upper = now + second_offset
  1857. value = datetime.datetime.combine(now.date(), value)
  1858. if timezone.is_aware(value):
  1859. value = timezone.make_naive(value, timezone.utc).time()
  1860. else:
  1861. # No explicit time / datetime value -- no checks necessary
  1862. return []
  1863. if lower <= value <= upper:
  1864. return [
  1865. checks.Warning(
  1866. 'Fixed default value provided.',
  1867. hint='It seems you set a fixed date / time / datetime '
  1868. 'value as default for this field. This may not be '
  1869. 'what you want. If you want to have the current date '
  1870. 'as default, use `django.utils.timezone.now`',
  1871. obj=self,
  1872. id='fields.W161',
  1873. )
  1874. ]
  1875. return []
  1876. def deconstruct(self):
  1877. name, path, args, kwargs = super().deconstruct()
  1878. if self.auto_now is not False:
  1879. kwargs["auto_now"] = self.auto_now
  1880. if self.auto_now_add is not False:
  1881. kwargs["auto_now_add"] = self.auto_now_add
  1882. if self.auto_now or self.auto_now_add:
  1883. del kwargs['blank']
  1884. del kwargs['editable']
  1885. return name, path, args, kwargs
  1886. def get_internal_type(self):
  1887. return "TimeField"
  1888. def to_python(self, value):
  1889. if value is None:
  1890. return None
  1891. if isinstance(value, datetime.time):
  1892. return value
  1893. if isinstance(value, datetime.datetime):
  1894. # Not usually a good idea to pass in a datetime here (it loses
  1895. # information), but this can be a side-effect of interacting with a
  1896. # database backend (e.g. Oracle), so we'll be accommodating.
  1897. return value.time()
  1898. try:
  1899. parsed = parse_time(value)
  1900. if parsed is not None:
  1901. return parsed
  1902. except ValueError:
  1903. raise exceptions.ValidationError(
  1904. self.error_messages['invalid_time'],
  1905. code='invalid_time',
  1906. params={'value': value},
  1907. )
  1908. raise exceptions.ValidationError(
  1909. self.error_messages['invalid'],
  1910. code='invalid',
  1911. params={'value': value},
  1912. )
  1913. def pre_save(self, model_instance, add):
  1914. if self.auto_now or (self.auto_now_add and add):
  1915. value = datetime.datetime.now().time()
  1916. setattr(model_instance, self.attname, value)
  1917. return value
  1918. else:
  1919. return super().pre_save(model_instance, add)
  1920. def get_prep_value(self, value):
  1921. value = super().get_prep_value(value)
  1922. return self.to_python(value)
  1923. def get_db_prep_value(self, value, connection, prepared=False):
  1924. # Casts times into the format expected by the backend
  1925. if not prepared:
  1926. value = self.get_prep_value(value)
  1927. return connection.ops.adapt_timefield_value(value)
  1928. def value_to_string(self, obj):
  1929. val = self.value_from_object(obj)
  1930. return '' if val is None else val.isoformat()
  1931. def formfield(self, **kwargs):
  1932. defaults = {'form_class': forms.TimeField}
  1933. defaults.update(kwargs)
  1934. return super().formfield(**defaults)
  1935. class URLField(CharField):
  1936. default_validators = [validators.URLValidator()]
  1937. description = _("URL")
  1938. def __init__(self, verbose_name=None, name=None, **kwargs):
  1939. kwargs['max_length'] = kwargs.get('max_length', 200)
  1940. super().__init__(verbose_name, name, **kwargs)
  1941. def deconstruct(self):
  1942. name, path, args, kwargs = super().deconstruct()
  1943. if kwargs.get("max_length") == 200:
  1944. del kwargs['max_length']
  1945. return name, path, args, kwargs
  1946. def formfield(self, **kwargs):
  1947. # As with CharField, this will cause URL validation to be performed
  1948. # twice.
  1949. defaults = {
  1950. 'form_class': forms.URLField,
  1951. }
  1952. defaults.update(kwargs)
  1953. return super().formfield(**defaults)
  1954. class BinaryField(Field):
  1955. description = _("Raw binary data")
  1956. empty_values = [None, b'']
  1957. def __init__(self, *args, **kwargs):
  1958. kwargs['editable'] = False
  1959. super().__init__(*args, **kwargs)
  1960. if self.max_length is not None:
  1961. self.validators.append(validators.MaxLengthValidator(self.max_length))
  1962. def deconstruct(self):
  1963. name, path, args, kwargs = super().deconstruct()
  1964. del kwargs['editable']
  1965. return name, path, args, kwargs
  1966. def get_internal_type(self):
  1967. return "BinaryField"
  1968. def get_placeholder(self, value, compiler, connection):
  1969. return connection.ops.binary_placeholder_sql(value)
  1970. def get_default(self):
  1971. if self.has_default() and not callable(self.default):
  1972. return self.default
  1973. default = super().get_default()
  1974. if default == '':
  1975. return b''
  1976. return default
  1977. def get_db_prep_value(self, value, connection, prepared=False):
  1978. value = super().get_db_prep_value(value, connection, prepared)
  1979. if value is not None:
  1980. return connection.Database.Binary(value)
  1981. return value
  1982. def value_to_string(self, obj):
  1983. """Binary data is serialized as base64"""
  1984. return b64encode(force_bytes(self.value_from_object(obj))).decode('ascii')
  1985. def to_python(self, value):
  1986. # If it's a string, it should be base64-encoded data
  1987. if isinstance(value, str):
  1988. return memoryview(b64decode(force_bytes(value)))
  1989. return value
  1990. class UUIDField(Field):
  1991. default_error_messages = {
  1992. 'invalid': _("'%(value)s' is not a valid UUID."),
  1993. }
  1994. description = 'Universally unique identifier'
  1995. empty_strings_allowed = False
  1996. def __init__(self, verbose_name=None, **kwargs):
  1997. kwargs['max_length'] = 32
  1998. super().__init__(verbose_name, **kwargs)
  1999. def deconstruct(self):
  2000. name, path, args, kwargs = super().deconstruct()
  2001. del kwargs['max_length']
  2002. return name, path, args, kwargs
  2003. def get_internal_type(self):
  2004. return "UUIDField"
  2005. def get_db_prep_value(self, value, connection, prepared=False):
  2006. if value is None:
  2007. return None
  2008. if not isinstance(value, uuid.UUID):
  2009. value = self.to_python(value)
  2010. if connection.features.has_native_uuid_field:
  2011. return value
  2012. return value.hex
  2013. def to_python(self, value):
  2014. if not isinstance(value, uuid.UUID):
  2015. try:
  2016. return uuid.UUID(value)
  2017. except (AttributeError, ValueError):
  2018. raise exceptions.ValidationError(
  2019. self.error_messages['invalid'],
  2020. code='invalid',
  2021. params={'value': value},
  2022. )
  2023. return value
  2024. def formfield(self, **kwargs):
  2025. defaults = {
  2026. 'form_class': forms.UUIDField,
  2027. }
  2028. defaults.update(kwargs)
  2029. return super().formfield(**defaults)