__init__.py 86 KB

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