You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 82KB

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