__init__.py 83 KB

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