Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 82KB

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