__init__.py 92 KB

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