Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/django/db/models/fields/__init__.py: 61%

1278 statements  

« prev     ^ index     » next       coverage.py v6.4.4, created at 2023-07-17 14:22 -0600

1import collections.abc 

2import copy 

3import datetime 

4import decimal 

5import math 

6import operator 

7import uuid 

8import warnings 

9from base64 import b64decode, b64encode 

10from functools import partialmethod, total_ordering 

11 

12from django import forms 

13from django.apps import apps 

14from django.conf import settings 

15from django.core import checks, exceptions, validators 

16from django.db import connection, connections, router 

17from django.db.models.constants import LOOKUP_SEP 

18from django.db.models.query_utils import DeferredAttribute, RegisterLookupMixin 

19from django.utils import timezone 

20from django.utils.datastructures import DictWrapper 

21from django.utils.dateparse import ( 

22 parse_date, 

23 parse_datetime, 

24 parse_duration, 

25 parse_time, 

26) 

27from django.utils.duration import duration_microseconds, duration_string 

28from django.utils.functional import Promise, cached_property 

29from django.utils.ipv6 import clean_ipv6_address 

30from django.utils.itercompat import is_iterable 

31from django.utils.text import capfirst 

32from django.utils.translation import gettext_lazy as _ 

33 

34__all__ = [ 

35 "AutoField", 

36 "BLANK_CHOICE_DASH", 

37 "BigAutoField", 

38 "BigIntegerField", 

39 "BinaryField", 

40 "BooleanField", 

41 "CharField", 

42 "CommaSeparatedIntegerField", 

43 "DateField", 

44 "DateTimeField", 

45 "DecimalField", 

46 "DurationField", 

47 "EmailField", 

48 "Empty", 

49 "Field", 

50 "FilePathField", 

51 "FloatField", 

52 "GenericIPAddressField", 

53 "IPAddressField", 

54 "IntegerField", 

55 "NOT_PROVIDED", 

56 "NullBooleanField", 

57 "PositiveBigIntegerField", 

58 "PositiveIntegerField", 

59 "PositiveSmallIntegerField", 

60 "SlugField", 

61 "SmallAutoField", 

62 "SmallIntegerField", 

63 "TextField", 

64 "TimeField", 

65 "URLField", 

66 "UUIDField", 

67] 

68 

69 

70class Empty: 

71 pass 

72 

73 

74class NOT_PROVIDED: 

75 pass 

76 

77 

78# The values to use for "blank" in SelectFields. Will be appended to the start 

79# of most "choices" lists. 

80BLANK_CHOICE_DASH = [("", "---------")] 

81 

82 

83def _load_field(app_label, model_name, field_name): 

84 return apps.get_model(app_label, model_name)._meta.get_field(field_name) 

85 

86 

87# A guide to Field parameters: 

88# 

89# * name: The name of the field specified in the model. 

90# * attname: The attribute to use on the model object. This is the same as 

91# "name", except in the case of ForeignKeys, where "_id" is 

92# appended. 

93# * db_column: The db_column specified in the model (or None). 

94# * column: The database column for this field. This is the same as 

95# "attname", except if db_column is specified. 

96# 

97# Code that introspects values, or does other dynamic things, should use 

98# attname. For example, this gets the primary key value of object "obj": 

99# 

100# getattr(obj, opts.pk.attname) 

101 

102 

103def _empty(of_cls): 

104 new = Empty() 

105 new.__class__ = of_cls 

106 return new 

107 

108 

109def return_None(): 

110 return None 

111 

112 

113@total_ordering 

114class Field(RegisterLookupMixin): 

115 """Base class for all field types""" 

116 

117 # Designates whether empty strings fundamentally are allowed at the 

118 # database level. 

119 empty_strings_allowed = True 

120 empty_values = list(validators.EMPTY_VALUES) 

121 

122 # These track each time a Field instance is created. Used to retain order. 

123 # The auto_creation_counter is used for fields that Django implicitly 

124 # creates, creation_counter is used for all user-specified fields. 

125 creation_counter = 0 

126 auto_creation_counter = -1 

127 default_validators = [] # Default set of validators 

128 default_error_messages = { 

129 "invalid_choice": _("Value %(value)r is not a valid choice."), 

130 "null": _("This field cannot be null."), 

131 "blank": _("This field cannot be blank."), 

132 "unique": _("%(model_name)s with this %(field_label)s already exists."), 

133 # Translators: The 'lookup_type' is one of 'date', 'year' or 'month'. 

134 # Eg: "Title must be unique for pub_date year" 

135 "unique_for_date": _( 

136 "%(field_label)s must be unique for " 

137 "%(date_field_label)s %(lookup_type)s." 

138 ), 

139 } 

140 system_check_deprecated_details = None 

141 system_check_removed_details = None 

142 

143 # Field flags 

144 hidden = False 

145 

146 many_to_many = None 

147 many_to_one = None 

148 one_to_many = None 

149 one_to_one = None 

150 related_model = None 

151 

152 descriptor_class = DeferredAttribute 

153 

154 # Generic field type description, usually overridden by subclasses 

155 def _description(self): 

156 return _("Field of type: %(field_type)s") % { 

157 "field_type": self.__class__.__name__ 

158 } 

159 

160 description = property(_description) 

161 

162 def __init__( 

163 self, 

164 verbose_name=None, 

165 name=None, 

166 primary_key=False, 

167 max_length=None, 

168 unique=False, 

169 blank=False, 

170 null=False, 

171 db_index=False, 

172 rel=None, 

173 default=NOT_PROVIDED, 

174 editable=True, 

175 serialize=True, 

176 unique_for_date=None, 

177 unique_for_month=None, 

178 unique_for_year=None, 

179 choices=None, 

180 help_text="", 

181 db_column=None, 

182 db_tablespace=None, 

183 auto_created=False, 

184 validators=(), 

185 error_messages=None, 

186 ): 

187 self.name = name 

188 self.verbose_name = verbose_name # May be set by set_attributes_from_name 

189 self._verbose_name = verbose_name # Store original for deconstruction 

190 self.primary_key = primary_key 

191 self.max_length, self._unique = max_length, unique 

192 self.blank, self.null = blank, null 

193 self.remote_field = rel 

194 self.is_relation = self.remote_field is not None 

195 self.default = default 

196 self.editable = editable 

197 self.serialize = serialize 

198 self.unique_for_date = unique_for_date 

199 self.unique_for_month = unique_for_month 

200 self.unique_for_year = unique_for_year 

201 if isinstance(choices, collections.abc.Iterator): 201 ↛ 202line 201 didn't jump to line 202, because the condition on line 201 was never true

202 choices = list(choices) 

203 self.choices = choices 

204 self.help_text = help_text 

205 self.db_index = db_index 

206 self.db_column = db_column 

207 self._db_tablespace = db_tablespace 

208 self.auto_created = auto_created 

209 

210 # Adjust the appropriate creation counter, and save our local copy. 

211 if auto_created: 

212 self.creation_counter = Field.auto_creation_counter 

213 Field.auto_creation_counter -= 1 

214 else: 

215 self.creation_counter = Field.creation_counter 

216 Field.creation_counter += 1 

217 

218 self._validators = list(validators) # Store for deconstruction later 

219 

220 messages = {} 

221 for c in reversed(self.__class__.__mro__): 

222 messages.update(getattr(c, "default_error_messages", {})) 

223 messages.update(error_messages or {}) 

224 self._error_messages = error_messages # Store for deconstruction later 

225 self.error_messages = messages 

226 

227 def __str__(self): 

228 """ 

229 Return "app_label.model_label.field_name" for fields attached to 

230 models. 

231 """ 

232 if not hasattr(self, "model"): 

233 return super().__str__() 

234 model = self.model 

235 return "%s.%s" % (model._meta.label, self.name) 

236 

237 def __repr__(self): 

238 """Display the module, class, and name of the field.""" 

239 path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__) 

240 name = getattr(self, "name", None) 

241 if name is not None: 

242 return "<%s: %s>" % (path, name) 

243 return "<%s>" % path 

244 

245 def check(self, **kwargs): 

246 return [ 

247 *self._check_field_name(), 

248 *self._check_choices(), 

249 *self._check_db_index(), 

250 *self._check_null_allowed_for_primary_keys(), 

251 *self._check_backend_specific_checks(**kwargs), 

252 *self._check_validators(), 

253 *self._check_deprecation_details(), 

254 ] 

255 

256 def _check_field_name(self): 

257 """ 

258 Check if field name is valid, i.e. 1) does not end with an 

259 underscore, 2) does not contain "__" and 3) is not "pk". 

260 """ 

261 if self.name.endswith("_"): 261 ↛ 262line 261 didn't jump to line 262, because the condition on line 261 was never true

262 return [ 

263 checks.Error( 

264 "Field names must not end with an underscore.", 

265 obj=self, 

266 id="fields.E001", 

267 ) 

268 ] 

269 elif LOOKUP_SEP in self.name: 269 ↛ 270line 269 didn't jump to line 270, because the condition on line 269 was never true

270 return [ 

271 checks.Error( 

272 'Field names must not contain "%s".' % LOOKUP_SEP, 

273 obj=self, 

274 id="fields.E002", 

275 ) 

276 ] 

277 elif self.name == "pk": 277 ↛ 278line 277 didn't jump to line 278, because the condition on line 277 was never true

278 return [ 

279 checks.Error( 

280 "'pk' is a reserved word that cannot be used as a field name.", 

281 obj=self, 

282 id="fields.E003", 

283 ) 

284 ] 

285 else: 

286 return [] 

287 

288 @classmethod 

289 def _choices_is_value(cls, value): 

290 return isinstance(value, (str, Promise)) or not is_iterable(value) 

291 

292 def _check_choices(self): 

293 if not self.choices: 

294 return [] 

295 

296 if not is_iterable(self.choices) or isinstance(self.choices, str): 296 ↛ 297line 296 didn't jump to line 297, because the condition on line 296 was never true

297 return [ 

298 checks.Error( 

299 "'choices' must be an iterable (e.g., a list or tuple).", 

300 obj=self, 

301 id="fields.E004", 

302 ) 

303 ] 

304 

305 choice_max_length = 0 

306 # Expect [group_name, [value, display]] 

307 for choices_group in self.choices: 

308 try: 

309 group_name, group_choices = choices_group 

310 except (TypeError, ValueError): 

311 # Containing non-pairs 

312 break 

313 try: 

314 if not all( 314 ↛ 318,   314 ↛ 3192 missed branches: 1) line 314 didn't jump to line 318, because the condition on line 314 was never true, 2) line 314 didn't jump to line 319, because the condition on line 314 was never false

315 self._choices_is_value(value) and self._choices_is_value(human_name) 

316 for value, human_name in group_choices 

317 ): 

318 break 

319 if self.max_length is not None and group_choices: 

320 choice_max_length = max( 

321 [ 

322 choice_max_length, 

323 *( 

324 len(value) 

325 for value, _ in group_choices 

326 if isinstance(value, str) 

327 ), 

328 ] 

329 ) 

330 except (TypeError, ValueError): 

331 # No groups, choices in the form [value, display] 

332 value, human_name = group_name, group_choices 

333 if not self._choices_is_value(value) or not self._choices_is_value( 333 ↛ 336line 333 didn't jump to line 336, because the condition on line 333 was never true

334 human_name 

335 ): 

336 break 

337 if self.max_length is not None and isinstance(value, str): 

338 choice_max_length = max(choice_max_length, len(value)) 

339 

340 # Special case: choices=['ab'] 

341 if isinstance(choices_group, str): 341 ↛ 342line 341 didn't jump to line 342, because the condition on line 341 was never true

342 break 

343 else: 

344 if self.max_length is not None and choice_max_length > self.max_length: 344 ↛ 345line 344 didn't jump to line 345, because the condition on line 344 was never true

345 return [ 

346 checks.Error( 

347 "'max_length' is too small to fit the longest value " 

348 "in 'choices' (%d characters)." % choice_max_length, 

349 obj=self, 

350 id="fields.E009", 

351 ), 

352 ] 

353 return [] 

354 

355 return [ 

356 checks.Error( 

357 "'choices' must be an iterable containing " 

358 "(actual value, human readable name) tuples.", 

359 obj=self, 

360 id="fields.E005", 

361 ) 

362 ] 

363 

364 def _check_db_index(self): 

365 if self.db_index not in (None, True, False): 365 ↛ 366line 365 didn't jump to line 366, because the condition on line 365 was never true

366 return [ 

367 checks.Error( 

368 "'db_index' must be None, True or False.", 

369 obj=self, 

370 id="fields.E006", 

371 ) 

372 ] 

373 else: 

374 return [] 

375 

376 def _check_null_allowed_for_primary_keys(self): 

377 if ( 377 ↛ 385line 377 didn't jump to line 385

378 self.primary_key 

379 and self.null 

380 and not connection.features.interprets_empty_strings_as_nulls 

381 ): 

382 # We cannot reliably check this for backends like Oracle which 

383 # consider NULL and '' to be equal (and thus set up 

384 # character-based fields a little differently). 

385 return [ 

386 checks.Error( 

387 "Primary keys must not have null=True.", 

388 hint=( 

389 "Set null=False on the field, or " 

390 "remove primary_key=True argument." 

391 ), 

392 obj=self, 

393 id="fields.E007", 

394 ) 

395 ] 

396 else: 

397 return [] 

398 

399 def _check_backend_specific_checks(self, databases=None, **kwargs): 

400 if databases is None: 400 ↛ 401line 400 didn't jump to line 401, because the condition on line 400 was never true

401 return [] 

402 app_label = self.model._meta.app_label 

403 errors = [] 

404 for alias in databases: 

405 if router.allow_migrate( 405 ↛ 404line 405 didn't jump to line 404, because the condition on line 405 was never false

406 alias, app_label, model_name=self.model._meta.model_name 

407 ): 

408 errors.extend(connections[alias].validation.check_field(self, **kwargs)) 

409 return errors 

410 

411 def _check_validators(self): 

412 errors = [] 

413 for i, validator in enumerate(self.validators): 

414 if not callable(validator): 414 ↛ 415line 414 didn't jump to line 415, because the condition on line 414 was never true

415 errors.append( 

416 checks.Error( 

417 "All 'validators' must be callable.", 

418 hint=( 

419 "validators[{i}] ({repr}) isn't a function or " 

420 "instance of a validator class.".format( 

421 i=i, 

422 repr=repr(validator), 

423 ) 

424 ), 

425 obj=self, 

426 id="fields.E008", 

427 ) 

428 ) 

429 return errors 

430 

431 def _check_deprecation_details(self): 

432 if self.system_check_removed_details is not None: 432 ↛ 433line 432 didn't jump to line 433, because the condition on line 432 was never true

433 return [ 

434 checks.Error( 

435 self.system_check_removed_details.get( 

436 "msg", 

437 "%s has been removed except for support in historical " 

438 "migrations." % self.__class__.__name__, 

439 ), 

440 hint=self.system_check_removed_details.get("hint"), 

441 obj=self, 

442 id=self.system_check_removed_details.get("id", "fields.EXXX"), 

443 ) 

444 ] 

445 elif self.system_check_deprecated_details is not None: 445 ↛ 446line 445 didn't jump to line 446, because the condition on line 445 was never true

446 return [ 

447 checks.Warning( 

448 self.system_check_deprecated_details.get( 

449 "msg", "%s has been deprecated." % self.__class__.__name__ 

450 ), 

451 hint=self.system_check_deprecated_details.get("hint"), 

452 obj=self, 

453 id=self.system_check_deprecated_details.get("id", "fields.WXXX"), 

454 ) 

455 ] 

456 return [] 

457 

458 def get_col(self, alias, output_field=None): 

459 if alias == self.model._meta.db_table and ( 

460 output_field is None or output_field == self 

461 ): 

462 return self.cached_col 

463 from django.db.models.expressions import Col 

464 

465 return Col(alias, self, output_field) 

466 

467 @cached_property 

468 def cached_col(self): 

469 from django.db.models.expressions import Col 

470 

471 return Col(self.model._meta.db_table, self) 

472 

473 def select_format(self, compiler, sql, params): 

474 """ 

475 Custom format for select clauses. For example, GIS columns need to be 

476 selected as AsText(table.col) on MySQL as the table.col data can't be 

477 used by Django. 

478 """ 

479 return sql, params 

480 

481 def deconstruct(self): 

482 """ 

483 Return enough information to recreate the field as a 4-tuple: 

484 

485 * The name of the field on the model, if contribute_to_class() has 

486 been run. 

487 * The import path of the field, including the class, e.g. 

488 django.db.models.IntegerField. This should be the most portable 

489 version, so less specific may be better. 

490 * A list of positional arguments. 

491 * A dict of keyword arguments. 

492 

493 Note that the positional or keyword arguments must contain values of 

494 the following types (including inner values of collection types): 

495 

496 * None, bool, str, int, float, complex, set, frozenset, list, tuple, 

497 dict 

498 * UUID 

499 * datetime.datetime (naive), datetime.date 

500 * top-level classes, top-level functions - will be referenced by their 

501 full import path 

502 * Storage instances - these have their own deconstruct() method 

503 

504 This is because the values here must be serialized into a text format 

505 (possibly new Python code, possibly JSON) and these are the only types 

506 with encoding handlers defined. 

507 

508 There's no need to return the exact way the field was instantiated this 

509 time, just ensure that the resulting field is the same - prefer keyword 

510 arguments over positional ones, and omit parameters with their default 

511 values. 

512 """ 

513 # Short-form way of fetching all the default parameters 

514 keywords = {} 

515 possibles = { 

516 "verbose_name": None, 

517 "primary_key": False, 

518 "max_length": None, 

519 "unique": False, 

520 "blank": False, 

521 "null": False, 

522 "db_index": False, 

523 "default": NOT_PROVIDED, 

524 "editable": True, 

525 "serialize": True, 

526 "unique_for_date": None, 

527 "unique_for_month": None, 

528 "unique_for_year": None, 

529 "choices": None, 

530 "help_text": "", 

531 "db_column": None, 

532 "db_tablespace": None, 

533 "auto_created": False, 

534 "validators": [], 

535 "error_messages": None, 

536 } 

537 attr_overrides = { 

538 "unique": "_unique", 

539 "error_messages": "_error_messages", 

540 "validators": "_validators", 

541 "verbose_name": "_verbose_name", 

542 "db_tablespace": "_db_tablespace", 

543 } 

544 equals_comparison = {"choices", "validators"} 

545 for name, default in possibles.items(): 

546 value = getattr(self, attr_overrides.get(name, name)) 

547 # Unroll anything iterable for choices into a concrete list 

548 if name == "choices" and isinstance(value, collections.abc.Iterable): 

549 value = list(value) 

550 # Do correct kind of comparison 

551 if name in equals_comparison: 

552 if value != default: 

553 keywords[name] = value 

554 else: 

555 if value is not default: 

556 keywords[name] = value 

557 # Work out path - we shorten it for known Django core fields 

558 path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__) 

559 if path.startswith("django.db.models.fields.related"): 

560 path = path.replace("django.db.models.fields.related", "django.db.models") 

561 elif path.startswith("django.db.models.fields.files"): 

562 path = path.replace("django.db.models.fields.files", "django.db.models") 

563 elif path.startswith("django.db.models.fields.json"): 

564 path = path.replace("django.db.models.fields.json", "django.db.models") 

565 elif path.startswith("django.db.models.fields.proxy"): 565 ↛ 566line 565 didn't jump to line 566, because the condition on line 565 was never true

566 path = path.replace("django.db.models.fields.proxy", "django.db.models") 

567 elif path.startswith("django.db.models.fields"): 

568 path = path.replace("django.db.models.fields", "django.db.models") 

569 # Return basic info - other fields should override this. 

570 return (self.name, path, [], keywords) 

571 

572 def clone(self): 

573 """ 

574 Uses deconstruct() to clone a new copy of this Field. 

575 Will not preserve any class attachments/attribute names. 

576 """ 

577 name, path, args, kwargs = self.deconstruct() 

578 return self.__class__(*args, **kwargs) 

579 

580 def __eq__(self, other): 

581 # Needed for @total_ordering 

582 if isinstance(other, Field): 582 ↛ 586line 582 didn't jump to line 586, because the condition on line 582 was never false

583 return self.creation_counter == other.creation_counter and getattr( 

584 self, "model", None 

585 ) == getattr(other, "model", None) 

586 return NotImplemented 

587 

588 def __lt__(self, other): 

589 # This is needed because bisect does not take a comparison function. 

590 # Order by creation_counter first for backward compatibility. 

591 if isinstance(other, Field): 591 ↛ 606line 591 didn't jump to line 606, because the condition on line 591 was never false

592 if ( 592 ↛ 598line 592 didn't jump to line 598

593 self.creation_counter != other.creation_counter 

594 or not hasattr(self, "model") 

595 and not hasattr(other, "model") 

596 ): 

597 return self.creation_counter < other.creation_counter 

598 elif hasattr(self, "model") != hasattr(other, "model"): 

599 return not hasattr(self, "model") # Order no-model fields first 

600 else: 

601 # creation_counter's are equal, compare only models. 

602 return (self.model._meta.app_label, self.model._meta.model_name) < ( 

603 other.model._meta.app_label, 

604 other.model._meta.model_name, 

605 ) 

606 return NotImplemented 

607 

608 def __hash__(self): 

609 return hash( 

610 ( 

611 self.creation_counter, 

612 self.model._meta.app_label if hasattr(self, "model") else None, 

613 self.model._meta.model_name if hasattr(self, "model") else None, 

614 ) 

615 ) 

616 

617 def __deepcopy__(self, memodict): 

618 # We don't have to deepcopy very much here, since most things are not 

619 # intended to be altered after initial creation. 

620 obj = copy.copy(self) 

621 if self.remote_field: 

622 obj.remote_field = copy.copy(self.remote_field) 

623 if hasattr(self.remote_field, "field") and self.remote_field.field is self: 623 ↛ 625line 623 didn't jump to line 625, because the condition on line 623 was never false

624 obj.remote_field.field = obj 

625 memodict[id(self)] = obj 

626 return obj 

627 

628 def __copy__(self): 

629 # We need to avoid hitting __reduce__, so define this 

630 # slightly weird copy construct. 

631 obj = Empty() 

632 obj.__class__ = self.__class__ 

633 obj.__dict__ = self.__dict__.copy() 

634 return obj 

635 

636 def __reduce__(self): 

637 """ 

638 Pickling should return the model._meta.fields instance of the field, 

639 not a new copy of that field. So, use the app registry to load the 

640 model and then the field back. 

641 """ 

642 if not hasattr(self, "model"): 

643 # Fields are sometimes used without attaching them to models (for 

644 # example in aggregation). In this case give back a plain field 

645 # instance. The code below will create a new empty instance of 

646 # class self.__class__, then update its dict with self.__dict__ 

647 # values - so, this is very close to normal pickle. 

648 state = self.__dict__.copy() 

649 # The _get_default cached_property can't be pickled due to lambda 

650 # usage. 

651 state.pop("_get_default", None) 

652 return _empty, (self.__class__,), state 

653 return _load_field, ( 

654 self.model._meta.app_label, 

655 self.model._meta.object_name, 

656 self.name, 

657 ) 

658 

659 def get_pk_value_on_save(self, instance): 

660 """ 

661 Hook to generate new PK values on save. This method is called when 

662 saving instances with no primary key value set. If this method returns 

663 something else than None, then the returned value is used when saving 

664 the new instance. 

665 """ 

666 if self.default: 666 ↛ 668line 666 didn't jump to line 668, because the condition on line 666 was never false

667 return self.get_default() 

668 return None 

669 

670 def to_python(self, value): 

671 """ 

672 Convert the input value into the expected Python data type, raising 

673 django.core.exceptions.ValidationError if the data can't be converted. 

674 Return the converted value. Subclasses should override this. 

675 """ 

676 return value 

677 

678 @cached_property 

679 def validators(self): 

680 """ 

681 Some validators can't be created at field initialization time. 

682 This method provides a way to delay their creation until required. 

683 """ 

684 return [*self.default_validators, *self._validators] 

685 

686 def run_validators(self, value): 

687 if value in self.empty_values: 

688 return 

689 

690 errors = [] 

691 for v in self.validators: 

692 try: 

693 v(value) 

694 except exceptions.ValidationError as e: 

695 if hasattr(e, "code") and e.code in self.error_messages: 

696 e.message = self.error_messages[e.code] 

697 errors.extend(e.error_list) 

698 

699 if errors: 

700 raise exceptions.ValidationError(errors) 

701 

702 def validate(self, value, model_instance): 

703 """ 

704 Validate value and raise ValidationError if necessary. Subclasses 

705 should override this to provide validation logic. 

706 """ 

707 if not self.editable: 

708 # Skip validation for non-editable fields. 

709 return 

710 

711 if self.choices is not None and value not in self.empty_values: 

712 for option_key, option_value in self.choices: 

713 if isinstance(option_value, (list, tuple)): 

714 # This is an optgroup, so look inside the group for 

715 # options. 

716 for optgroup_key, optgroup_value in option_value: 

717 if value == optgroup_key: 

718 return 

719 elif value == option_key: 

720 return 

721 raise exceptions.ValidationError( 

722 self.error_messages["invalid_choice"], 

723 code="invalid_choice", 

724 params={"value": value}, 

725 ) 

726 

727 if value is None and not self.null: 

728 raise exceptions.ValidationError(self.error_messages["null"], code="null") 

729 

730 if not self.blank and value in self.empty_values: 

731 raise exceptions.ValidationError(self.error_messages["blank"], code="blank") 

732 

733 def clean(self, value, model_instance): 

734 """ 

735 Convert the value's type and run validation. Validation errors 

736 from to_python() and validate() are propagated. Return the correct 

737 value if no error is raised. 

738 """ 

739 value = self.to_python(value) 

740 self.validate(value, model_instance) 

741 self.run_validators(value) 

742 return value 

743 

744 def db_type_parameters(self, connection): 

745 return DictWrapper(self.__dict__, connection.ops.quote_name, "qn_") 

746 

747 def db_check(self, connection): 

748 """ 

749 Return the database column check constraint for this field, for the 

750 provided connection. Works the same way as db_type() for the case that 

751 get_internal_type() does not map to a preexisting model field. 

752 """ 

753 data = self.db_type_parameters(connection) 

754 try: 

755 return ( 

756 connection.data_type_check_constraints[self.get_internal_type()] % data 

757 ) 

758 except KeyError: 

759 return None 

760 

761 def db_type(self, connection): 

762 """ 

763 Return the database column data type for this field, for the provided 

764 connection. 

765 """ 

766 # The default implementation of this method looks at the 

767 # backend-specific data_types dictionary, looking up the field by its 

768 # "internal type". 

769 # 

770 # A Field class can implement the get_internal_type() method to specify 

771 # which *preexisting* Django Field class it's most similar to -- i.e., 

772 # a custom field might be represented by a TEXT column type, which is 

773 # the same as the TextField Django field type, which means the custom 

774 # field's get_internal_type() returns 'TextField'. 

775 # 

776 # But the limitation of the get_internal_type() / data_types approach 

777 # is that it cannot handle database column types that aren't already 

778 # mapped to one of the built-in Django field types. In this case, you 

779 # can implement db_type() instead of get_internal_type() to specify 

780 # exactly which wacky database column type you want to use. 

781 data = self.db_type_parameters(connection) 

782 try: 

783 return connection.data_types[self.get_internal_type()] % data 

784 except KeyError: 

785 return None 

786 

787 def rel_db_type(self, connection): 

788 """ 

789 Return the data type that a related field pointing to this field should 

790 use. For example, this method is called by ForeignKey and OneToOneField 

791 to determine its data type. 

792 """ 

793 return self.db_type(connection) 

794 

795 def cast_db_type(self, connection): 

796 """Return the data type to use in the Cast() function.""" 

797 db_type = connection.ops.cast_data_types.get(self.get_internal_type()) 

798 if db_type: 

799 return db_type % self.db_type_parameters(connection) 

800 return self.db_type(connection) 

801 

802 def db_parameters(self, connection): 

803 """ 

804 Extension of db_type(), providing a range of different return values 

805 (type, checks). This will look at db_type(), allowing custom model 

806 fields to override it. 

807 """ 

808 type_string = self.db_type(connection) 

809 check_string = self.db_check(connection) 

810 return { 

811 "type": type_string, 

812 "check": check_string, 

813 } 

814 

815 def db_type_suffix(self, connection): 

816 return connection.data_types_suffix.get(self.get_internal_type()) 

817 

818 def get_db_converters(self, connection): 

819 if hasattr(self, "from_db_value"): 

820 return [self.from_db_value] 

821 return [] 

822 

823 @property 

824 def unique(self): 

825 return self._unique or self.primary_key 

826 

827 @property 

828 def db_tablespace(self): 

829 return self._db_tablespace or settings.DEFAULT_INDEX_TABLESPACE 

830 

831 @property 

832 def db_returning(self): 

833 """ 

834 Private API intended only to be used by Django itself. Currently only 

835 the PostgreSQL backend supports returning multiple fields on a model. 

836 """ 

837 return False 

838 

839 def set_attributes_from_name(self, name): 

840 self.name = self.name or name 

841 self.attname, self.column = self.get_attname_column() 

842 self.concrete = self.column is not None 

843 if self.verbose_name is None and self.name: 

844 self.verbose_name = self.name.replace("_", " ") 

845 

846 def contribute_to_class(self, cls, name, private_only=False): 

847 """ 

848 Register the field with the model class it belongs to. 

849 

850 If private_only is True, create a separate instance of this field 

851 for every subclass of cls, even if cls is not an abstract model. 

852 """ 

853 self.set_attributes_from_name(name) 

854 self.model = cls 

855 cls._meta.add_field(self, private=private_only) 

856 if self.column: 856 ↛ 858line 856 didn't jump to line 858, because the condition on line 856 was never false

857 setattr(cls, self.attname, self.descriptor_class(self)) 

858 if self.choices is not None: 

859 # Don't override a get_FOO_display() method defined explicitly on 

860 # this class, but don't check methods derived from inheritance, to 

861 # allow overriding inherited choices. For more complex inheritance 

862 # structures users should override contribute_to_class(). 

863 if "get_%s_display" % self.name not in cls.__dict__: 863 ↛ exitline 863 didn't return from function 'contribute_to_class', because the condition on line 863 was never false

864 setattr( 

865 cls, 

866 "get_%s_display" % self.name, 

867 partialmethod(cls._get_FIELD_display, field=self), 

868 ) 

869 

870 def get_filter_kwargs_for_object(self, obj): 

871 """ 

872 Return a dict that when passed as kwargs to self.model.filter(), would 

873 yield all instances having the same value for this field as obj has. 

874 """ 

875 return {self.name: getattr(obj, self.attname)} 

876 

877 def get_attname(self): 

878 return self.name 

879 

880 def get_attname_column(self): 

881 attname = self.get_attname() 

882 column = self.db_column or attname 

883 return attname, column 

884 

885 def get_internal_type(self): 

886 return self.__class__.__name__ 

887 

888 def pre_save(self, model_instance, add): 

889 """Return field's value just before saving.""" 

890 return getattr(model_instance, self.attname) 

891 

892 def get_prep_value(self, value): 

893 """Perform preliminary non-db specific value checks and conversions.""" 

894 if isinstance(value, Promise): 894 ↛ 895line 894 didn't jump to line 895, because the condition on line 894 was never true

895 value = value._proxy____cast() 

896 return value 

897 

898 def get_db_prep_value(self, value, connection, prepared=False): 

899 """ 

900 Return field's value prepared for interacting with the database backend. 

901 

902 Used by the default implementations of get_db_prep_save(). 

903 """ 

904 if not prepared: 

905 value = self.get_prep_value(value) 

906 return value 

907 

908 def get_db_prep_save(self, value, connection): 

909 """Return field's value prepared for saving into a database.""" 

910 return self.get_db_prep_value(value, connection=connection, prepared=False) 

911 

912 def has_default(self): 

913 """Return a boolean of whether this field has a default value.""" 

914 return self.default is not NOT_PROVIDED 

915 

916 def get_default(self): 

917 """Return the default value for this field.""" 

918 return self._get_default() 

919 

920 @cached_property 

921 def _get_default(self): 

922 if self.has_default(): 

923 if callable(self.default): 

924 return self.default 

925 return lambda: self.default 

926 

927 if ( 

928 not self.empty_strings_allowed 

929 or self.null 

930 and not connection.features.interprets_empty_strings_as_nulls 

931 ): 

932 return return_None 

933 return str # return empty string 

934 

935 def get_choices( 

936 self, 

937 include_blank=True, 

938 blank_choice=BLANK_CHOICE_DASH, 

939 limit_choices_to=None, 

940 ordering=(), 

941 ): 

942 """ 

943 Return choices with a default blank choices included, for use 

944 as <select> choices for this field. 

945 """ 

946 if self.choices is not None: 

947 choices = list(self.choices) 

948 if include_blank: 

949 blank_defined = any( 

950 choice in ("", None) for choice, _ in self.flatchoices 

951 ) 

952 if not blank_defined: 

953 choices = blank_choice + choices 

954 return choices 

955 rel_model = self.remote_field.model 

956 limit_choices_to = limit_choices_to or self.get_limit_choices_to() 

957 choice_func = operator.attrgetter( 

958 self.remote_field.get_related_field().attname 

959 if hasattr(self.remote_field, "get_related_field") 

960 else "pk" 

961 ) 

962 qs = rel_model._default_manager.complex_filter(limit_choices_to) 

963 if ordering: 

964 qs = qs.order_by(*ordering) 

965 return (blank_choice if include_blank else []) + [ 

966 (choice_func(x), str(x)) for x in qs 

967 ] 

968 

969 def value_to_string(self, obj): 

970 """ 

971 Return a string value of this field from the passed obj. 

972 This is used by the serialization framework. 

973 """ 

974 return str(self.value_from_object(obj)) 

975 

976 def _get_flatchoices(self): 

977 """Flattened version of choices tuple.""" 

978 if self.choices is None: 

979 return [] 

980 flat = [] 

981 for choice, value in self.choices: 

982 if isinstance(value, (list, tuple)): 

983 flat.extend(value) 

984 else: 

985 flat.append((choice, value)) 

986 return flat 

987 

988 flatchoices = property(_get_flatchoices) 

989 

990 def save_form_data(self, instance, data): 

991 setattr(instance, self.name, data) 

992 

993 def formfield(self, form_class=None, choices_form_class=None, **kwargs): 

994 """Return a django.forms.Field instance for this field.""" 

995 defaults = { 

996 "required": not self.blank, 

997 "label": capfirst(self.verbose_name), 

998 "help_text": self.help_text, 

999 } 

1000 if self.has_default(): 

1001 if callable(self.default): 

1002 defaults["initial"] = self.default 

1003 defaults["show_hidden_initial"] = True 

1004 else: 

1005 defaults["initial"] = self.get_default() 

1006 if self.choices is not None: 1006 ↛ 1008line 1006 didn't jump to line 1008, because the condition on line 1006 was never true

1007 # Fields with choices get special treatment. 

1008 include_blank = self.blank or not ( 

1009 self.has_default() or "initial" in kwargs 

1010 ) 

1011 defaults["choices"] = self.get_choices(include_blank=include_blank) 

1012 defaults["coerce"] = self.to_python 

1013 if self.null: 

1014 defaults["empty_value"] = None 

1015 if choices_form_class is not None: 

1016 form_class = choices_form_class 

1017 else: 

1018 form_class = forms.TypedChoiceField 

1019 # Many of the subclass-specific formfield arguments (min_value, 

1020 # max_value) don't apply for choice fields, so be sure to only pass 

1021 # the values that TypedChoiceField will understand. 

1022 for k in list(kwargs): 

1023 if k not in ( 

1024 "coerce", 

1025 "empty_value", 

1026 "choices", 

1027 "required", 

1028 "widget", 

1029 "label", 

1030 "initial", 

1031 "help_text", 

1032 "error_messages", 

1033 "show_hidden_initial", 

1034 "disabled", 

1035 ): 

1036 del kwargs[k] 

1037 defaults.update(kwargs) 

1038 if form_class is None: 

1039 form_class = forms.CharField 

1040 return form_class(**defaults) 

1041 

1042 def value_from_object(self, obj): 

1043 """Return the value of this field in the given model instance.""" 

1044 return getattr(obj, self.attname) 

1045 

1046 

1047class BooleanField(Field): 

1048 empty_strings_allowed = False 

1049 default_error_messages = { 

1050 "invalid": _("“%(value)s” value must be either True or False."), 

1051 "invalid_nullable": _("“%(value)s” value must be either True, False, or None."), 

1052 } 

1053 description = _("Boolean (Either True or False)") 

1054 

1055 def get_internal_type(self): 

1056 return "BooleanField" 

1057 

1058 def to_python(self, value): 

1059 if self.null and value in self.empty_values: 1059 ↛ 1060line 1059 didn't jump to line 1060, because the condition on line 1059 was never true

1060 return None 

1061 if value in (True, False): 1061 ↛ 1064line 1061 didn't jump to line 1064, because the condition on line 1061 was never false

1062 # 1/0 are equal to True/False. bool() converts former to latter. 

1063 return bool(value) 

1064 if value in ("t", "True", "1"): 

1065 return True 

1066 if value in ("f", "False", "0"): 

1067 return False 

1068 raise exceptions.ValidationError( 

1069 self.error_messages["invalid_nullable" if self.null else "invalid"], 

1070 code="invalid", 

1071 params={"value": value}, 

1072 ) 

1073 

1074 def get_prep_value(self, value): 

1075 value = super().get_prep_value(value) 

1076 if value is None: 1076 ↛ 1077line 1076 didn't jump to line 1077, because the condition on line 1076 was never true

1077 return None 

1078 return self.to_python(value) 

1079 

1080 def formfield(self, **kwargs): 

1081 if self.choices is not None: 1081 ↛ 1082line 1081 didn't jump to line 1082, because the condition on line 1081 was never true

1082 include_blank = not (self.has_default() or "initial" in kwargs) 

1083 defaults = {"choices": self.get_choices(include_blank=include_blank)} 

1084 else: 

1085 form_class = forms.NullBooleanField if self.null else forms.BooleanField 

1086 # In HTML checkboxes, 'required' means "must be checked" which is 

1087 # different from the choices case ("must select some value"). 

1088 # required=False allows unchecked checkboxes. 

1089 defaults = {"form_class": form_class, "required": False} 

1090 return super().formfield(**{**defaults, **kwargs}) 

1091 

1092 

1093class CharField(Field): 

1094 description = _("String (up to %(max_length)s)") 

1095 

1096 def __init__(self, *args, db_collation=None, **kwargs): 

1097 super().__init__(*args, **kwargs) 

1098 self.db_collation = db_collation 

1099 self.validators.append(validators.MaxLengthValidator(self.max_length)) 

1100 

1101 def check(self, **kwargs): 

1102 databases = kwargs.get("databases") or [] 

1103 return [ 

1104 *super().check(**kwargs), 

1105 *self._check_db_collation(databases), 

1106 *self._check_max_length_attribute(**kwargs), 

1107 ] 

1108 

1109 def _check_max_length_attribute(self, **kwargs): 

1110 if self.max_length is None: 1110 ↛ 1111line 1110 didn't jump to line 1111, because the condition on line 1110 was never true

1111 return [ 

1112 checks.Error( 

1113 "CharFields must define a 'max_length' attribute.", 

1114 obj=self, 

1115 id="fields.E120", 

1116 ) 

1117 ] 

1118 elif ( 1118 ↛ 1123line 1118 didn't jump to line 1123

1119 not isinstance(self.max_length, int) 

1120 or isinstance(self.max_length, bool) 

1121 or self.max_length <= 0 

1122 ): 

1123 return [ 

1124 checks.Error( 

1125 "'max_length' must be a positive integer.", 

1126 obj=self, 

1127 id="fields.E121", 

1128 ) 

1129 ] 

1130 else: 

1131 return [] 

1132 

1133 def _check_db_collation(self, databases): 

1134 errors = [] 

1135 for db in databases: 

1136 if not router.allow_migrate_model(db, self.model): 1136 ↛ 1137line 1136 didn't jump to line 1137, because the condition on line 1136 was never true

1137 continue 

1138 connection = connections[db] 

1139 if not ( 1139 ↛ 1145line 1139 didn't jump to line 1145, because the condition on line 1139 was never true

1140 self.db_collation is None 

1141 or "supports_collation_on_charfield" 

1142 in self.model._meta.required_db_features 

1143 or connection.features.supports_collation_on_charfield 

1144 ): 

1145 errors.append( 

1146 checks.Error( 

1147 "%s does not support a database collation on " 

1148 "CharFields." % connection.display_name, 

1149 obj=self, 

1150 id="fields.E190", 

1151 ), 

1152 ) 

1153 return errors 

1154 

1155 def cast_db_type(self, connection): 

1156 if self.max_length is None: 

1157 return connection.ops.cast_char_field_without_max_length 

1158 return super().cast_db_type(connection) 

1159 

1160 def get_internal_type(self): 

1161 return "CharField" 

1162 

1163 def to_python(self, value): 

1164 if isinstance(value, str) or value is None: 

1165 return value 

1166 return str(value) 

1167 

1168 def get_prep_value(self, value): 

1169 value = super().get_prep_value(value) 

1170 return self.to_python(value) 

1171 

1172 def formfield(self, **kwargs): 

1173 # Passing max_length to forms.CharField means that the value's length 

1174 # will be validated twice. This is considered acceptable since we want 

1175 # the value in the form field (to pass into widget for example). 

1176 defaults = {"max_length": self.max_length} 

1177 # TODO: Handle multiple backends with different feature flags. 

1178 if self.null and not connection.features.interprets_empty_strings_as_nulls: 1178 ↛ 1179line 1178 didn't jump to line 1179, because the condition on line 1178 was never true

1179 defaults["empty_value"] = None 

1180 defaults.update(kwargs) 

1181 return super().formfield(**defaults) 

1182 

1183 def deconstruct(self): 

1184 name, path, args, kwargs = super().deconstruct() 

1185 if self.db_collation: 1185 ↛ 1186line 1185 didn't jump to line 1186, because the condition on line 1185 was never true

1186 kwargs["db_collation"] = self.db_collation 

1187 return name, path, args, kwargs 

1188 

1189 

1190class CommaSeparatedIntegerField(CharField): 

1191 default_validators = [validators.validate_comma_separated_integer_list] 

1192 description = _("Comma-separated integers") 

1193 system_check_removed_details = { 

1194 "msg": ( 

1195 "CommaSeparatedIntegerField is removed except for support in " 

1196 "historical migrations." 

1197 ), 

1198 "hint": ( 

1199 "Use CharField(validators=[validate_comma_separated_integer_list]) " 

1200 "instead." 

1201 ), 

1202 "id": "fields.E901", 

1203 } 

1204 

1205 

1206def _to_naive(value): 

1207 if timezone.is_aware(value): 

1208 value = timezone.make_naive(value, timezone.utc) 

1209 return value 

1210 

1211 

1212def _get_naive_now(): 

1213 return _to_naive(timezone.now()) 

1214 

1215 

1216class DateTimeCheckMixin: 

1217 def check(self, **kwargs): 

1218 return [ 

1219 *super().check(**kwargs), 

1220 *self._check_mutually_exclusive_options(), 

1221 *self._check_fix_default_value(), 

1222 ] 

1223 

1224 def _check_mutually_exclusive_options(self): 

1225 # auto_now, auto_now_add, and default are mutually exclusive 

1226 # options. The use of more than one of these options together 

1227 # will trigger an Error 

1228 mutually_exclusive_options = [ 

1229 self.auto_now_add, 

1230 self.auto_now, 

1231 self.has_default(), 

1232 ] 

1233 enabled_options = [ 

1234 option not in (None, False) for option in mutually_exclusive_options 

1235 ].count(True) 

1236 if enabled_options > 1: 1236 ↛ 1237line 1236 didn't jump to line 1237, because the condition on line 1236 was never true

1237 return [ 

1238 checks.Error( 

1239 "The options auto_now, auto_now_add, and default " 

1240 "are mutually exclusive. Only one of these options " 

1241 "may be present.", 

1242 obj=self, 

1243 id="fields.E160", 

1244 ) 

1245 ] 

1246 else: 

1247 return [] 

1248 

1249 def _check_fix_default_value(self): 

1250 return [] 

1251 

1252 # Concrete subclasses use this in their implementations of 

1253 # _check_fix_default_value(). 

1254 def _check_if_value_fixed(self, value, now=None): 

1255 """ 

1256 Check if the given value appears to have been provided as a "fixed" 

1257 time value, and include a warning in the returned list if it does. The 

1258 value argument must be a date object or aware/naive datetime object. If 

1259 now is provided, it must be a naive datetime object. 

1260 """ 

1261 if now is None: 

1262 now = _get_naive_now() 

1263 offset = datetime.timedelta(seconds=10) 

1264 lower = now - offset 

1265 upper = now + offset 

1266 if isinstance(value, datetime.datetime): 

1267 value = _to_naive(value) 

1268 else: 

1269 assert isinstance(value, datetime.date) 

1270 lower = lower.date() 

1271 upper = upper.date() 

1272 if lower <= value <= upper: 

1273 return [ 

1274 checks.Warning( 

1275 "Fixed default value provided.", 

1276 hint=( 

1277 "It seems you set a fixed date / time / datetime " 

1278 "value as default for this field. This may not be " 

1279 "what you want. If you want to have the current date " 

1280 "as default, use `django.utils.timezone.now`" 

1281 ), 

1282 obj=self, 

1283 id="fields.W161", 

1284 ) 

1285 ] 

1286 return [] 

1287 

1288 

1289class DateField(DateTimeCheckMixin, Field): 

1290 empty_strings_allowed = False 

1291 default_error_messages = { 

1292 "invalid": _( 

1293 "“%(value)s” value has an invalid date format. It must be " 

1294 "in YYYY-MM-DD format." 

1295 ), 

1296 "invalid_date": _( 

1297 "“%(value)s” value has the correct format (YYYY-MM-DD) " 

1298 "but it is an invalid date." 

1299 ), 

1300 } 

1301 description = _("Date (without time)") 

1302 

1303 def __init__( 

1304 self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs 

1305 ): 

1306 self.auto_now, self.auto_now_add = auto_now, auto_now_add 

1307 if auto_now or auto_now_add: 

1308 kwargs["editable"] = False 

1309 kwargs["blank"] = True 

1310 super().__init__(verbose_name, name, **kwargs) 

1311 

1312 def _check_fix_default_value(self): 

1313 """ 

1314 Warn that using an actual date or datetime value is probably wrong; 

1315 it's only evaluated on server startup. 

1316 """ 

1317 if not self.has_default(): 

1318 return [] 

1319 

1320 value = self.default 

1321 if isinstance(value, datetime.datetime): 1321 ↛ 1322line 1321 didn't jump to line 1322, because the condition on line 1321 was never true

1322 value = _to_naive(value).date() 

1323 elif isinstance(value, datetime.date): 1323 ↛ 1324line 1323 didn't jump to line 1324, because the condition on line 1323 was never true

1324 pass 

1325 else: 

1326 # No explicit date / datetime value -- no checks necessary 

1327 return [] 

1328 # At this point, value is a date object. 

1329 return self._check_if_value_fixed(value) 

1330 

1331 def deconstruct(self): 

1332 name, path, args, kwargs = super().deconstruct() 

1333 if self.auto_now: 

1334 kwargs["auto_now"] = True 

1335 if self.auto_now_add: 

1336 kwargs["auto_now_add"] = True 

1337 if self.auto_now or self.auto_now_add: 

1338 del kwargs["editable"] 

1339 del kwargs["blank"] 

1340 return name, path, args, kwargs 

1341 

1342 def get_internal_type(self): 

1343 return "DateField" 

1344 

1345 def to_python(self, value): 

1346 if value is None: 

1347 return value 

1348 if isinstance(value, datetime.datetime): 

1349 if settings.USE_TZ and timezone.is_aware(value): 1349 ↛ 1352line 1349 didn't jump to line 1352, because the condition on line 1349 was never true

1350 # Convert aware datetimes to the default time zone 

1351 # before casting them to dates (#17742). 

1352 default_timezone = timezone.get_default_timezone() 

1353 value = timezone.make_naive(value, default_timezone) 

1354 return value.date() 

1355 if isinstance(value, datetime.date): 

1356 return value 

1357 

1358 try: 

1359 parsed = parse_date(value) 

1360 if parsed is not None: 1360 ↛ 1369line 1360 didn't jump to line 1369, because the condition on line 1360 was never false

1361 return parsed 

1362 except ValueError: 

1363 raise exceptions.ValidationError( 

1364 self.error_messages["invalid_date"], 

1365 code="invalid_date", 

1366 params={"value": value}, 

1367 ) 

1368 

1369 raise exceptions.ValidationError( 

1370 self.error_messages["invalid"], 

1371 code="invalid", 

1372 params={"value": value}, 

1373 ) 

1374 

1375 def pre_save(self, model_instance, add): 

1376 if self.auto_now or (self.auto_now_add and add): 1376 ↛ 1377line 1376 didn't jump to line 1377, because the condition on line 1376 was never true

1377 value = datetime.date.today() 

1378 setattr(model_instance, self.attname, value) 

1379 return value 

1380 else: 

1381 return super().pre_save(model_instance, add) 

1382 

1383 def contribute_to_class(self, cls, name, **kwargs): 

1384 super().contribute_to_class(cls, name, **kwargs) 

1385 if not self.null: 

1386 setattr( 

1387 cls, 

1388 "get_next_by_%s" % self.name, 

1389 partialmethod( 

1390 cls._get_next_or_previous_by_FIELD, field=self, is_next=True 

1391 ), 

1392 ) 

1393 setattr( 

1394 cls, 

1395 "get_previous_by_%s" % self.name, 

1396 partialmethod( 

1397 cls._get_next_or_previous_by_FIELD, field=self, is_next=False 

1398 ), 

1399 ) 

1400 

1401 def get_prep_value(self, value): 

1402 value = super().get_prep_value(value) 

1403 return self.to_python(value) 

1404 

1405 def get_db_prep_value(self, value, connection, prepared=False): 

1406 # Casts dates into the format expected by the backend 

1407 if not prepared: 

1408 value = self.get_prep_value(value) 

1409 return connection.ops.adapt_datefield_value(value) 

1410 

1411 def value_to_string(self, obj): 

1412 val = self.value_from_object(obj) 

1413 return "" if val is None else val.isoformat() 

1414 

1415 def formfield(self, **kwargs): 

1416 return super().formfield( 

1417 **{ 

1418 "form_class": forms.DateField, 

1419 **kwargs, 

1420 } 

1421 ) 

1422 

1423 

1424class DateTimeField(DateField): 

1425 empty_strings_allowed = False 

1426 default_error_messages = { 

1427 "invalid": _( 

1428 "“%(value)s” value has an invalid format. It must be in " 

1429 "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format." 

1430 ), 

1431 "invalid_date": _( 

1432 "“%(value)s” value has the correct format " 

1433 "(YYYY-MM-DD) but it is an invalid date." 

1434 ), 

1435 "invalid_datetime": _( 

1436 "“%(value)s” value has the correct format " 

1437 "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) " 

1438 "but it is an invalid date/time." 

1439 ), 

1440 } 

1441 description = _("Date (with time)") 

1442 

1443 # __init__ is inherited from DateField 

1444 

1445 def _check_fix_default_value(self): 

1446 """ 

1447 Warn that using an actual date or datetime value is probably wrong; 

1448 it's only evaluated on server startup. 

1449 """ 

1450 if not self.has_default(): 

1451 return [] 

1452 

1453 value = self.default 

1454 if isinstance(value, (datetime.datetime, datetime.date)): 1454 ↛ 1455line 1454 didn't jump to line 1455, because the condition on line 1454 was never true

1455 return self._check_if_value_fixed(value) 

1456 # No explicit date / datetime value -- no checks necessary. 

1457 return [] 

1458 

1459 def get_internal_type(self): 

1460 return "DateTimeField" 

1461 

1462 def to_python(self, value): 

1463 if value is None: 

1464 return value 

1465 if isinstance(value, datetime.datetime): 1465 ↛ 1467line 1465 didn't jump to line 1467, because the condition on line 1465 was never false

1466 return value 

1467 if isinstance(value, datetime.date): 

1468 value = datetime.datetime(value.year, value.month, value.day) 

1469 if settings.USE_TZ: 

1470 # For backwards compatibility, interpret naive datetimes in 

1471 # local time. This won't work during DST change, but we can't 

1472 # do much about it, so we let the exceptions percolate up the 

1473 # call stack. 

1474 warnings.warn( 

1475 "DateTimeField %s.%s received a naive datetime " 

1476 "(%s) while time zone support is active." 

1477 % (self.model.__name__, self.name, value), 

1478 RuntimeWarning, 

1479 ) 

1480 default_timezone = timezone.get_default_timezone() 

1481 value = timezone.make_aware(value, default_timezone) 

1482 return value 

1483 

1484 try: 

1485 parsed = parse_datetime(value) 

1486 if parsed is not None: 

1487 return parsed 

1488 except ValueError: 

1489 raise exceptions.ValidationError( 

1490 self.error_messages["invalid_datetime"], 

1491 code="invalid_datetime", 

1492 params={"value": value}, 

1493 ) 

1494 

1495 try: 

1496 parsed = parse_date(value) 

1497 if parsed is not None: 

1498 return datetime.datetime(parsed.year, parsed.month, parsed.day) 

1499 except ValueError: 

1500 raise exceptions.ValidationError( 

1501 self.error_messages["invalid_date"], 

1502 code="invalid_date", 

1503 params={"value": value}, 

1504 ) 

1505 

1506 raise exceptions.ValidationError( 

1507 self.error_messages["invalid"], 

1508 code="invalid", 

1509 params={"value": value}, 

1510 ) 

1511 

1512 def pre_save(self, model_instance, add): 

1513 if self.auto_now or (self.auto_now_add and add): 

1514 value = timezone.now() 

1515 setattr(model_instance, self.attname, value) 

1516 return value 

1517 else: 

1518 return super().pre_save(model_instance, add) 

1519 

1520 # contribute_to_class is inherited from DateField, it registers 

1521 # get_next_by_FOO and get_prev_by_FOO 

1522 

1523 def get_prep_value(self, value): 

1524 value = super().get_prep_value(value) 

1525 value = self.to_python(value) 

1526 if value is not None and settings.USE_TZ and timezone.is_naive(value): 1526 ↛ 1530line 1526 didn't jump to line 1530, because the condition on line 1526 was never true

1527 # For backwards compatibility, interpret naive datetimes in local 

1528 # time. This won't work during DST change, but we can't do much 

1529 # about it, so we let the exceptions percolate up the call stack. 

1530 try: 

1531 name = "%s.%s" % (self.model.__name__, self.name) 

1532 except AttributeError: 

1533 name = "(unbound)" 

1534 warnings.warn( 

1535 "DateTimeField %s received a naive datetime (%s)" 

1536 " while time zone support is active." % (name, value), 

1537 RuntimeWarning, 

1538 ) 

1539 default_timezone = timezone.get_default_timezone() 

1540 value = timezone.make_aware(value, default_timezone) 

1541 return value 

1542 

1543 def get_db_prep_value(self, value, connection, prepared=False): 

1544 # Casts datetimes into the format expected by the backend 

1545 if not prepared: 1545 ↛ 1547line 1545 didn't jump to line 1547, because the condition on line 1545 was never false

1546 value = self.get_prep_value(value) 

1547 return connection.ops.adapt_datetimefield_value(value) 

1548 

1549 def value_to_string(self, obj): 

1550 val = self.value_from_object(obj) 

1551 return "" if val is None else val.isoformat() 

1552 

1553 def formfield(self, **kwargs): 

1554 return super().formfield( 

1555 **{ 

1556 "form_class": forms.DateTimeField, 

1557 **kwargs, 

1558 } 

1559 ) 

1560 

1561 

1562class DecimalField(Field): 

1563 empty_strings_allowed = False 

1564 default_error_messages = { 

1565 "invalid": _("“%(value)s” value must be a decimal number."), 

1566 } 

1567 description = _("Decimal number") 

1568 

1569 def __init__( 

1570 self, 

1571 verbose_name=None, 

1572 name=None, 

1573 max_digits=None, 

1574 decimal_places=None, 

1575 **kwargs, 

1576 ): 

1577 self.max_digits, self.decimal_places = max_digits, decimal_places 

1578 super().__init__(verbose_name, name, **kwargs) 

1579 

1580 def check(self, **kwargs): 

1581 errors = super().check(**kwargs) 

1582 

1583 digits_errors = [ 

1584 *self._check_decimal_places(), 

1585 *self._check_max_digits(), 

1586 ] 

1587 if not digits_errors: 1587 ↛ 1590line 1587 didn't jump to line 1590, because the condition on line 1587 was never false

1588 errors.extend(self._check_decimal_places_and_max_digits(**kwargs)) 

1589 else: 

1590 errors.extend(digits_errors) 

1591 return errors 

1592 

1593 def _check_decimal_places(self): 

1594 try: 

1595 decimal_places = int(self.decimal_places) 

1596 if decimal_places < 0: 1596 ↛ 1597line 1596 didn't jump to line 1597, because the condition on line 1596 was never true

1597 raise ValueError() 

1598 except TypeError: 

1599 return [ 

1600 checks.Error( 

1601 "DecimalFields must define a 'decimal_places' attribute.", 

1602 obj=self, 

1603 id="fields.E130", 

1604 ) 

1605 ] 

1606 except ValueError: 

1607 return [ 

1608 checks.Error( 

1609 "'decimal_places' must be a non-negative integer.", 

1610 obj=self, 

1611 id="fields.E131", 

1612 ) 

1613 ] 

1614 else: 

1615 return [] 

1616 

1617 def _check_max_digits(self): 

1618 try: 

1619 max_digits = int(self.max_digits) 

1620 if max_digits <= 0: 1620 ↛ 1621line 1620 didn't jump to line 1621, because the condition on line 1620 was never true

1621 raise ValueError() 

1622 except TypeError: 

1623 return [ 

1624 checks.Error( 

1625 "DecimalFields must define a 'max_digits' attribute.", 

1626 obj=self, 

1627 id="fields.E132", 

1628 ) 

1629 ] 

1630 except ValueError: 

1631 return [ 

1632 checks.Error( 

1633 "'max_digits' must be a positive integer.", 

1634 obj=self, 

1635 id="fields.E133", 

1636 ) 

1637 ] 

1638 else: 

1639 return [] 

1640 

1641 def _check_decimal_places_and_max_digits(self, **kwargs): 

1642 if int(self.decimal_places) > int(self.max_digits): 1642 ↛ 1643line 1642 didn't jump to line 1643, because the condition on line 1642 was never true

1643 return [ 

1644 checks.Error( 

1645 "'max_digits' must be greater or equal to 'decimal_places'.", 

1646 obj=self, 

1647 id="fields.E134", 

1648 ) 

1649 ] 

1650 return [] 

1651 

1652 @cached_property 

1653 def validators(self): 

1654 return super().validators + [ 

1655 validators.DecimalValidator(self.max_digits, self.decimal_places) 

1656 ] 

1657 

1658 @cached_property 

1659 def context(self): 

1660 return decimal.Context(prec=self.max_digits) 

1661 

1662 def deconstruct(self): 

1663 name, path, args, kwargs = super().deconstruct() 

1664 if self.max_digits is not None: 1664 ↛ 1666line 1664 didn't jump to line 1666, because the condition on line 1664 was never false

1665 kwargs["max_digits"] = self.max_digits 

1666 if self.decimal_places is not None: 1666 ↛ 1668line 1666 didn't jump to line 1668, because the condition on line 1666 was never false

1667 kwargs["decimal_places"] = self.decimal_places 

1668 return name, path, args, kwargs 

1669 

1670 def get_internal_type(self): 

1671 return "DecimalField" 

1672 

1673 def to_python(self, value): 

1674 if value is None: 1674 ↛ 1675line 1674 didn't jump to line 1675, because the condition on line 1674 was never true

1675 return value 

1676 if isinstance(value, float): 

1677 if math.isnan(value): 1677 ↛ 1678line 1677 didn't jump to line 1678, because the condition on line 1677 was never true

1678 raise exceptions.ValidationError( 

1679 self.error_messages["invalid"], 

1680 code="invalid", 

1681 params={"value": value}, 

1682 ) 

1683 return self.context.create_decimal_from_float(value) 

1684 try: 

1685 return decimal.Decimal(value) 

1686 except (decimal.InvalidOperation, TypeError, ValueError): 

1687 raise exceptions.ValidationError( 

1688 self.error_messages["invalid"], 

1689 code="invalid", 

1690 params={"value": value}, 

1691 ) 

1692 

1693 def get_db_prep_save(self, value, connection): 

1694 return connection.ops.adapt_decimalfield_value( 

1695 self.to_python(value), self.max_digits, self.decimal_places 

1696 ) 

1697 

1698 def get_prep_value(self, value): 

1699 value = super().get_prep_value(value) 

1700 return self.to_python(value) 

1701 

1702 def formfield(self, **kwargs): 

1703 return super().formfield( 

1704 **{ 

1705 "max_digits": self.max_digits, 

1706 "decimal_places": self.decimal_places, 

1707 "form_class": forms.DecimalField, 

1708 **kwargs, 

1709 } 

1710 ) 

1711 

1712 

1713class DurationField(Field): 

1714 """ 

1715 Store timedelta objects. 

1716 

1717 Use interval on PostgreSQL, INTERVAL DAY TO SECOND on Oracle, and bigint 

1718 of microseconds on other databases. 

1719 """ 

1720 

1721 empty_strings_allowed = False 

1722 default_error_messages = { 

1723 "invalid": _( 

1724 "“%(value)s” value has an invalid format. It must be in " 

1725 "[DD] [[HH:]MM:]ss[.uuuuuu] format." 

1726 ) 

1727 } 

1728 description = _("Duration") 

1729 

1730 def get_internal_type(self): 

1731 return "DurationField" 

1732 

1733 def to_python(self, value): 

1734 if value is None: 

1735 return value 

1736 if isinstance(value, datetime.timedelta): 

1737 return value 

1738 try: 

1739 parsed = parse_duration(value) 

1740 except ValueError: 

1741 pass 

1742 else: 

1743 if parsed is not None: 

1744 return parsed 

1745 

1746 raise exceptions.ValidationError( 

1747 self.error_messages["invalid"], 

1748 code="invalid", 

1749 params={"value": value}, 

1750 ) 

1751 

1752 def get_db_prep_value(self, value, connection, prepared=False): 

1753 if connection.features.has_native_duration_field: 

1754 return value 

1755 if value is None: 

1756 return None 

1757 return duration_microseconds(value) 

1758 

1759 def get_db_converters(self, connection): 

1760 converters = [] 

1761 if not connection.features.has_native_duration_field: 

1762 converters.append(connection.ops.convert_durationfield_value) 

1763 return converters + super().get_db_converters(connection) 

1764 

1765 def value_to_string(self, obj): 

1766 val = self.value_from_object(obj) 

1767 return "" if val is None else duration_string(val) 

1768 

1769 def formfield(self, **kwargs): 

1770 return super().formfield( 

1771 **{ 

1772 "form_class": forms.DurationField, 

1773 **kwargs, 

1774 } 

1775 ) 

1776 

1777 

1778class EmailField(CharField): 

1779 default_validators = [validators.validate_email] 

1780 description = _("Email address") 

1781 

1782 def __init__(self, *args, **kwargs): 

1783 # max_length=254 to be compliant with RFCs 3696 and 5321 

1784 kwargs.setdefault("max_length", 254) 

1785 super().__init__(*args, **kwargs) 

1786 

1787 def deconstruct(self): 

1788 name, path, args, kwargs = super().deconstruct() 

1789 # We do not exclude max_length if it matches default as we want to change 

1790 # the default in future. 

1791 return name, path, args, kwargs 

1792 

1793 def formfield(self, **kwargs): 

1794 # As with CharField, this will cause email validation to be performed 

1795 # twice. 

1796 return super().formfield( 

1797 **{ 

1798 "form_class": forms.EmailField, 

1799 **kwargs, 

1800 } 

1801 ) 

1802 

1803 

1804class FilePathField(Field): 

1805 description = _("File path") 

1806 

1807 def __init__( 

1808 self, 

1809 verbose_name=None, 

1810 name=None, 

1811 path="", 

1812 match=None, 

1813 recursive=False, 

1814 allow_files=True, 

1815 allow_folders=False, 

1816 **kwargs, 

1817 ): 

1818 self.path, self.match, self.recursive = path, match, recursive 

1819 self.allow_files, self.allow_folders = allow_files, allow_folders 

1820 kwargs.setdefault("max_length", 100) 

1821 super().__init__(verbose_name, name, **kwargs) 

1822 

1823 def check(self, **kwargs): 

1824 return [ 

1825 *super().check(**kwargs), 

1826 *self._check_allowing_files_or_folders(**kwargs), 

1827 ] 

1828 

1829 def _check_allowing_files_or_folders(self, **kwargs): 

1830 if not self.allow_files and not self.allow_folders: 

1831 return [ 

1832 checks.Error( 

1833 "FilePathFields must have either 'allow_files' or 'allow_folders' " 

1834 "set to True.", 

1835 obj=self, 

1836 id="fields.E140", 

1837 ) 

1838 ] 

1839 return [] 

1840 

1841 def deconstruct(self): 

1842 name, path, args, kwargs = super().deconstruct() 

1843 if self.path != "": 

1844 kwargs["path"] = self.path 

1845 if self.match is not None: 

1846 kwargs["match"] = self.match 

1847 if self.recursive is not False: 

1848 kwargs["recursive"] = self.recursive 

1849 if self.allow_files is not True: 

1850 kwargs["allow_files"] = self.allow_files 

1851 if self.allow_folders is not False: 

1852 kwargs["allow_folders"] = self.allow_folders 

1853 if kwargs.get("max_length") == 100: 

1854 del kwargs["max_length"] 

1855 return name, path, args, kwargs 

1856 

1857 def get_prep_value(self, value): 

1858 value = super().get_prep_value(value) 

1859 if value is None: 

1860 return None 

1861 return str(value) 

1862 

1863 def formfield(self, **kwargs): 

1864 return super().formfield( 

1865 **{ 

1866 "path": self.path() if callable(self.path) else self.path, 

1867 "match": self.match, 

1868 "recursive": self.recursive, 

1869 "form_class": forms.FilePathField, 

1870 "allow_files": self.allow_files, 

1871 "allow_folders": self.allow_folders, 

1872 **kwargs, 

1873 } 

1874 ) 

1875 

1876 def get_internal_type(self): 

1877 return "FilePathField" 

1878 

1879 

1880class FloatField(Field): 

1881 empty_strings_allowed = False 

1882 default_error_messages = { 

1883 "invalid": _("“%(value)s” value must be a float."), 

1884 } 

1885 description = _("Floating point number") 

1886 

1887 def get_prep_value(self, value): 

1888 value = super().get_prep_value(value) 

1889 if value is None: 1889 ↛ 1891line 1889 didn't jump to line 1891, because the condition on line 1889 was never false

1890 return None 

1891 try: 

1892 return float(value) 

1893 except (TypeError, ValueError) as e: 

1894 raise e.__class__( 

1895 "Field '%s' expected a number but got %r." % (self.name, value), 

1896 ) from e 

1897 

1898 def get_internal_type(self): 

1899 return "FloatField" 

1900 

1901 def to_python(self, value): 

1902 if value is None: 

1903 return value 

1904 try: 

1905 return float(value) 

1906 except (TypeError, ValueError): 

1907 raise exceptions.ValidationError( 

1908 self.error_messages["invalid"], 

1909 code="invalid", 

1910 params={"value": value}, 

1911 ) 

1912 

1913 def formfield(self, **kwargs): 

1914 return super().formfield( 

1915 **{ 

1916 "form_class": forms.FloatField, 

1917 **kwargs, 

1918 } 

1919 ) 

1920 

1921 

1922class IntegerField(Field): 

1923 empty_strings_allowed = False 

1924 default_error_messages = { 

1925 "invalid": _("“%(value)s” value must be an integer."), 

1926 } 

1927 description = _("Integer") 

1928 

1929 def check(self, **kwargs): 

1930 return [ 

1931 *super().check(**kwargs), 

1932 *self._check_max_length_warning(), 

1933 ] 

1934 

1935 def _check_max_length_warning(self): 

1936 if self.max_length is not None: 1936 ↛ 1937line 1936 didn't jump to line 1937, because the condition on line 1936 was never true

1937 return [ 

1938 checks.Warning( 

1939 "'max_length' is ignored when used with %s." 

1940 % self.__class__.__name__, 

1941 hint="Remove 'max_length' from field", 

1942 obj=self, 

1943 id="fields.W122", 

1944 ) 

1945 ] 

1946 return [] 

1947 

1948 @cached_property 

1949 def validators(self): 

1950 # These validators can't be added at field initialization time since 

1951 # they're based on values retrieved from `connection`. 

1952 validators_ = super().validators 

1953 internal_type = self.get_internal_type() 

1954 min_value, max_value = connection.ops.integer_field_range(internal_type) 

1955 if min_value is not None and not any( 1955 ↛ 1968line 1955 didn't jump to line 1968, because the condition on line 1955 was never false

1956 ( 

1957 isinstance(validator, validators.MinValueValidator) 

1958 and ( 

1959 validator.limit_value() 

1960 if callable(validator.limit_value) 

1961 else validator.limit_value 

1962 ) 

1963 >= min_value 

1964 ) 

1965 for validator in validators_ 

1966 ): 

1967 validators_.append(validators.MinValueValidator(min_value)) 

1968 if max_value is not None and not any( 1968 ↛ 1981line 1968 didn't jump to line 1981, because the condition on line 1968 was never false

1969 ( 

1970 isinstance(validator, validators.MaxValueValidator) 

1971 and ( 

1972 validator.limit_value() 

1973 if callable(validator.limit_value) 

1974 else validator.limit_value 

1975 ) 

1976 <= max_value 

1977 ) 

1978 for validator in validators_ 

1979 ): 

1980 validators_.append(validators.MaxValueValidator(max_value)) 

1981 return validators_ 

1982 

1983 def get_prep_value(self, value): 

1984 value = super().get_prep_value(value) 

1985 if value is None: 

1986 return None 

1987 try: 

1988 return int(value) 

1989 except (TypeError, ValueError) as e: 

1990 raise e.__class__( 

1991 "Field '%s' expected a number but got %r." % (self.name, value), 

1992 ) from e 

1993 

1994 def get_internal_type(self): 

1995 return "IntegerField" 

1996 

1997 def to_python(self, value): 

1998 if value is None: 

1999 return value 

2000 try: 

2001 return int(value) 

2002 except (TypeError, ValueError): 

2003 raise exceptions.ValidationError( 

2004 self.error_messages["invalid"], 

2005 code="invalid", 

2006 params={"value": value}, 

2007 ) 

2008 

2009 def formfield(self, **kwargs): 

2010 return super().formfield( 

2011 **{ 

2012 "form_class": forms.IntegerField, 

2013 **kwargs, 

2014 } 

2015 ) 

2016 

2017 

2018class BigIntegerField(IntegerField): 

2019 description = _("Big (8 byte) integer") 

2020 MAX_BIGINT = 9223372036854775807 

2021 

2022 def get_internal_type(self): 

2023 return "BigIntegerField" 

2024 

2025 def formfield(self, **kwargs): 

2026 return super().formfield( 

2027 **{ 

2028 "min_value": -BigIntegerField.MAX_BIGINT - 1, 

2029 "max_value": BigIntegerField.MAX_BIGINT, 

2030 **kwargs, 

2031 } 

2032 ) 

2033 

2034 

2035class SmallIntegerField(IntegerField): 

2036 description = _("Small integer") 

2037 

2038 def get_internal_type(self): 

2039 return "SmallIntegerField" 

2040 

2041 

2042class IPAddressField(Field): 

2043 empty_strings_allowed = False 

2044 description = _("IPv4 address") 

2045 system_check_removed_details = { 

2046 "msg": ( 

2047 "IPAddressField has been removed except for support in " 

2048 "historical migrations." 

2049 ), 

2050 "hint": "Use GenericIPAddressField instead.", 

2051 "id": "fields.E900", 

2052 } 

2053 

2054 def __init__(self, *args, **kwargs): 

2055 kwargs["max_length"] = 15 

2056 super().__init__(*args, **kwargs) 

2057 

2058 def deconstruct(self): 

2059 name, path, args, kwargs = super().deconstruct() 

2060 del kwargs["max_length"] 

2061 return name, path, args, kwargs 

2062 

2063 def get_prep_value(self, value): 

2064 value = super().get_prep_value(value) 

2065 if value is None: 

2066 return None 

2067 return str(value) 

2068 

2069 def get_internal_type(self): 

2070 return "IPAddressField" 

2071 

2072 

2073class GenericIPAddressField(Field): 

2074 empty_strings_allowed = False 

2075 description = _("IP address") 

2076 default_error_messages = {} 

2077 

2078 def __init__( 

2079 self, 

2080 verbose_name=None, 

2081 name=None, 

2082 protocol="both", 

2083 unpack_ipv4=False, 

2084 *args, 

2085 **kwargs, 

2086 ): 

2087 self.unpack_ipv4 = unpack_ipv4 

2088 self.protocol = protocol 

2089 ( 

2090 self.default_validators, 

2091 invalid_error_message, 

2092 ) = validators.ip_address_validators(protocol, unpack_ipv4) 

2093 self.default_error_messages["invalid"] = invalid_error_message 

2094 kwargs["max_length"] = 39 

2095 super().__init__(verbose_name, name, *args, **kwargs) 

2096 

2097 def check(self, **kwargs): 

2098 return [ 

2099 *super().check(**kwargs), 

2100 *self._check_blank_and_null_values(**kwargs), 

2101 ] 

2102 

2103 def _check_blank_and_null_values(self, **kwargs): 

2104 if not getattr(self, "null", False) and getattr(self, "blank", False): 

2105 return [ 

2106 checks.Error( 

2107 "GenericIPAddressFields cannot have blank=True if null=False, " 

2108 "as blank values are stored as nulls.", 

2109 obj=self, 

2110 id="fields.E150", 

2111 ) 

2112 ] 

2113 return [] 

2114 

2115 def deconstruct(self): 

2116 name, path, args, kwargs = super().deconstruct() 

2117 if self.unpack_ipv4 is not False: 

2118 kwargs["unpack_ipv4"] = self.unpack_ipv4 

2119 if self.protocol != "both": 

2120 kwargs["protocol"] = self.protocol 

2121 if kwargs.get("max_length") == 39: 

2122 del kwargs["max_length"] 

2123 return name, path, args, kwargs 

2124 

2125 def get_internal_type(self): 

2126 return "GenericIPAddressField" 

2127 

2128 def to_python(self, value): 

2129 if value is None: 

2130 return None 

2131 if not isinstance(value, str): 

2132 value = str(value) 

2133 value = value.strip() 

2134 if ":" in value: 

2135 return clean_ipv6_address( 

2136 value, self.unpack_ipv4, self.error_messages["invalid"] 

2137 ) 

2138 return value 

2139 

2140 def get_db_prep_value(self, value, connection, prepared=False): 

2141 if not prepared: 

2142 value = self.get_prep_value(value) 

2143 return connection.ops.adapt_ipaddressfield_value(value) 

2144 

2145 def get_prep_value(self, value): 

2146 value = super().get_prep_value(value) 

2147 if value is None: 

2148 return None 

2149 if value and ":" in value: 

2150 try: 

2151 return clean_ipv6_address(value, self.unpack_ipv4) 

2152 except exceptions.ValidationError: 

2153 pass 

2154 return str(value) 

2155 

2156 def formfield(self, **kwargs): 

2157 return super().formfield( 

2158 **{ 

2159 "protocol": self.protocol, 

2160 "form_class": forms.GenericIPAddressField, 

2161 **kwargs, 

2162 } 

2163 ) 

2164 

2165 

2166class NullBooleanField(BooleanField): 

2167 default_error_messages = { 

2168 "invalid": _("“%(value)s” value must be either None, True or False."), 

2169 "invalid_nullable": _("“%(value)s” value must be either None, True or False."), 

2170 } 

2171 description = _("Boolean (Either True, False or None)") 

2172 system_check_removed_details = { 

2173 "msg": ( 

2174 "NullBooleanField is removed except for support in historical " 

2175 "migrations." 

2176 ), 

2177 "hint": "Use BooleanField(null=True) instead.", 

2178 "id": "fields.E903", 

2179 } 

2180 

2181 def __init__(self, *args, **kwargs): 

2182 kwargs["null"] = True 

2183 kwargs["blank"] = True 

2184 super().__init__(*args, **kwargs) 

2185 

2186 def deconstruct(self): 

2187 name, path, args, kwargs = super().deconstruct() 

2188 del kwargs["null"] 

2189 del kwargs["blank"] 

2190 return name, path, args, kwargs 

2191 

2192 

2193class PositiveIntegerRelDbTypeMixin: 

2194 def __init_subclass__(cls, **kwargs): 

2195 super().__init_subclass__(**kwargs) 

2196 if not hasattr(cls, "integer_field_class"): 2196 ↛ exitline 2196 didn't return from function '__init_subclass__', because the condition on line 2196 was never false

2197 cls.integer_field_class = next( 2197 ↛ exitline 2197 didn't jump to the function exit

2198 ( 

2199 parent 

2200 for parent in cls.__mro__[1:] 

2201 if issubclass(parent, IntegerField) 

2202 ), 

2203 None, 

2204 ) 

2205 

2206 def rel_db_type(self, connection): 

2207 """ 

2208 Return the data type that a related field pointing to this field should 

2209 use. In most cases, a foreign key pointing to a positive integer 

2210 primary key will have an integer column data type but some databases 

2211 (e.g. MySQL) have an unsigned integer type. In that case 

2212 (related_fields_match_type=True), the primary key should return its 

2213 db_type. 

2214 """ 

2215 if connection.features.related_fields_match_type: 

2216 return self.db_type(connection) 

2217 else: 

2218 return self.integer_field_class().db_type(connection=connection) 

2219 

2220 

2221class PositiveBigIntegerField(PositiveIntegerRelDbTypeMixin, BigIntegerField): 

2222 description = _("Positive big integer") 

2223 

2224 def get_internal_type(self): 

2225 return "PositiveBigIntegerField" 

2226 

2227 def formfield(self, **kwargs): 

2228 return super().formfield( 

2229 **{ 

2230 "min_value": 0, 

2231 **kwargs, 

2232 } 

2233 ) 

2234 

2235 

2236class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField): 

2237 description = _("Positive integer") 

2238 

2239 def get_internal_type(self): 

2240 return "PositiveIntegerField" 

2241 

2242 def formfield(self, **kwargs): 

2243 return super().formfield( 

2244 **{ 

2245 "min_value": 0, 

2246 **kwargs, 

2247 } 

2248 ) 

2249 

2250 

2251class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, SmallIntegerField): 

2252 description = _("Positive small integer") 

2253 

2254 def get_internal_type(self): 

2255 return "PositiveSmallIntegerField" 

2256 

2257 def formfield(self, **kwargs): 

2258 return super().formfield( 

2259 **{ 

2260 "min_value": 0, 

2261 **kwargs, 

2262 } 

2263 ) 

2264 

2265 

2266class SlugField(CharField): 

2267 default_validators = [validators.validate_slug] 

2268 description = _("Slug (up to %(max_length)s)") 

2269 

2270 def __init__( 

2271 self, *args, max_length=50, db_index=True, allow_unicode=False, **kwargs 

2272 ): 

2273 self.allow_unicode = allow_unicode 

2274 if self.allow_unicode: 2274 ↛ 2275line 2274 didn't jump to line 2275, because the condition on line 2274 was never true

2275 self.default_validators = [validators.validate_unicode_slug] 

2276 super().__init__(*args, max_length=max_length, db_index=db_index, **kwargs) 

2277 

2278 def deconstruct(self): 

2279 name, path, args, kwargs = super().deconstruct() 

2280 if kwargs.get("max_length") == 50: 2280 ↛ 2282line 2280 didn't jump to line 2282, because the condition on line 2280 was never false

2281 del kwargs["max_length"] 

2282 if self.db_index is False: 2282 ↛ 2283line 2282 didn't jump to line 2283, because the condition on line 2282 was never true

2283 kwargs["db_index"] = False 

2284 else: 

2285 del kwargs["db_index"] 

2286 if self.allow_unicode is not False: 2286 ↛ 2287line 2286 didn't jump to line 2287, because the condition on line 2286 was never true

2287 kwargs["allow_unicode"] = self.allow_unicode 

2288 return name, path, args, kwargs 

2289 

2290 def get_internal_type(self): 

2291 return "SlugField" 

2292 

2293 def formfield(self, **kwargs): 

2294 return super().formfield( 

2295 **{ 

2296 "form_class": forms.SlugField, 

2297 "allow_unicode": self.allow_unicode, 

2298 **kwargs, 

2299 } 

2300 ) 

2301 

2302 

2303class TextField(Field): 

2304 description = _("Text") 

2305 

2306 def __init__(self, *args, db_collation=None, **kwargs): 

2307 super().__init__(*args, **kwargs) 

2308 self.db_collation = db_collation 

2309 

2310 def check(self, **kwargs): 

2311 databases = kwargs.get("databases") or [] 

2312 return [ 

2313 *super().check(**kwargs), 

2314 *self._check_db_collation(databases), 

2315 ] 

2316 

2317 def _check_db_collation(self, databases): 

2318 errors = [] 

2319 for db in databases: 

2320 if not router.allow_migrate_model(db, self.model): 2320 ↛ 2321line 2320 didn't jump to line 2321, because the condition on line 2320 was never true

2321 continue 

2322 connection = connections[db] 

2323 if not ( 2323 ↛ 2329line 2323 didn't jump to line 2329, because the condition on line 2323 was never true

2324 self.db_collation is None 

2325 or "supports_collation_on_textfield" 

2326 in self.model._meta.required_db_features 

2327 or connection.features.supports_collation_on_textfield 

2328 ): 

2329 errors.append( 

2330 checks.Error( 

2331 "%s does not support a database collation on " 

2332 "TextFields." % connection.display_name, 

2333 obj=self, 

2334 id="fields.E190", 

2335 ), 

2336 ) 

2337 return errors 

2338 

2339 def get_internal_type(self): 

2340 return "TextField" 

2341 

2342 def to_python(self, value): 

2343 if isinstance(value, str) or value is None: 2343 ↛ 2345line 2343 didn't jump to line 2345, because the condition on line 2343 was never false

2344 return value 

2345 return str(value) 

2346 

2347 def get_prep_value(self, value): 

2348 value = super().get_prep_value(value) 

2349 return self.to_python(value) 

2350 

2351 def formfield(self, **kwargs): 

2352 # Passing max_length to forms.CharField means that the value's length 

2353 # will be validated twice. This is considered acceptable since we want 

2354 # the value in the form field (to pass into widget for example). 

2355 return super().formfield( 

2356 **{ 

2357 "max_length": self.max_length, 

2358 **({} if self.choices is not None else {"widget": forms.Textarea}), 

2359 **kwargs, 

2360 } 

2361 ) 

2362 

2363 def deconstruct(self): 

2364 name, path, args, kwargs = super().deconstruct() 

2365 if self.db_collation: 2365 ↛ 2366line 2365 didn't jump to line 2366, because the condition on line 2365 was never true

2366 kwargs["db_collation"] = self.db_collation 

2367 return name, path, args, kwargs 

2368 

2369 

2370class TimeField(DateTimeCheckMixin, Field): 

2371 empty_strings_allowed = False 

2372 default_error_messages = { 

2373 "invalid": _( 

2374 "“%(value)s” value has an invalid format. It must be in " 

2375 "HH:MM[:ss[.uuuuuu]] format." 

2376 ), 

2377 "invalid_time": _( 

2378 "“%(value)s” value has the correct format " 

2379 "(HH:MM[:ss[.uuuuuu]]) but it is an invalid time." 

2380 ), 

2381 } 

2382 description = _("Time") 

2383 

2384 def __init__( 

2385 self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs 

2386 ): 

2387 self.auto_now, self.auto_now_add = auto_now, auto_now_add 

2388 if auto_now or auto_now_add: 2388 ↛ 2389line 2388 didn't jump to line 2389, because the condition on line 2388 was never true

2389 kwargs["editable"] = False 

2390 kwargs["blank"] = True 

2391 super().__init__(verbose_name, name, **kwargs) 

2392 

2393 def _check_fix_default_value(self): 

2394 """ 

2395 Warn that using an actual date or datetime value is probably wrong; 

2396 it's only evaluated on server startup. 

2397 """ 

2398 if not self.has_default(): 2398 ↛ 2401line 2398 didn't jump to line 2401, because the condition on line 2398 was never false

2399 return [] 

2400 

2401 value = self.default 

2402 if isinstance(value, datetime.datetime): 

2403 now = None 

2404 elif isinstance(value, datetime.time): 

2405 now = _get_naive_now() 

2406 # This will not use the right date in the race condition where now 

2407 # is just before the date change and value is just past 0:00. 

2408 value = datetime.datetime.combine(now.date(), value) 

2409 else: 

2410 # No explicit time / datetime value -- no checks necessary 

2411 return [] 

2412 # At this point, value is a datetime object. 

2413 return self._check_if_value_fixed(value, now=now) 

2414 

2415 def deconstruct(self): 

2416 name, path, args, kwargs = super().deconstruct() 

2417 if self.auto_now is not False: 2417 ↛ 2418line 2417 didn't jump to line 2418, because the condition on line 2417 was never true

2418 kwargs["auto_now"] = self.auto_now 

2419 if self.auto_now_add is not False: 2419 ↛ 2420line 2419 didn't jump to line 2420, because the condition on line 2419 was never true

2420 kwargs["auto_now_add"] = self.auto_now_add 

2421 if self.auto_now or self.auto_now_add: 2421 ↛ 2422line 2421 didn't jump to line 2422, because the condition on line 2421 was never true

2422 del kwargs["blank"] 

2423 del kwargs["editable"] 

2424 return name, path, args, kwargs 

2425 

2426 def get_internal_type(self): 

2427 return "TimeField" 

2428 

2429 def to_python(self, value): 

2430 if value is None: 2430 ↛ 2431line 2430 didn't jump to line 2431, because the condition on line 2430 was never true

2431 return None 

2432 if isinstance(value, datetime.time): 

2433 return value 

2434 if isinstance(value, datetime.datetime): 2434 ↛ 2438line 2434 didn't jump to line 2438, because the condition on line 2434 was never true

2435 # Not usually a good idea to pass in a datetime here (it loses 

2436 # information), but this can be a side-effect of interacting with a 

2437 # database backend (e.g. Oracle), so we'll be accommodating. 

2438 return value.time() 

2439 

2440 try: 

2441 parsed = parse_time(value) 

2442 if parsed is not None: 2442 ↛ 2451line 2442 didn't jump to line 2451, because the condition on line 2442 was never false

2443 return parsed 

2444 except ValueError: 

2445 raise exceptions.ValidationError( 

2446 self.error_messages["invalid_time"], 

2447 code="invalid_time", 

2448 params={"value": value}, 

2449 ) 

2450 

2451 raise exceptions.ValidationError( 

2452 self.error_messages["invalid"], 

2453 code="invalid", 

2454 params={"value": value}, 

2455 ) 

2456 

2457 def pre_save(self, model_instance, add): 

2458 if self.auto_now or (self.auto_now_add and add): 2458 ↛ 2459line 2458 didn't jump to line 2459, because the condition on line 2458 was never true

2459 value = datetime.datetime.now().time() 

2460 setattr(model_instance, self.attname, value) 

2461 return value 

2462 else: 

2463 return super().pre_save(model_instance, add) 

2464 

2465 def get_prep_value(self, value): 

2466 value = super().get_prep_value(value) 

2467 return self.to_python(value) 

2468 

2469 def get_db_prep_value(self, value, connection, prepared=False): 

2470 # Casts times into the format expected by the backend 

2471 if not prepared: 2471 ↛ 2473line 2471 didn't jump to line 2473, because the condition on line 2471 was never false

2472 value = self.get_prep_value(value) 

2473 return connection.ops.adapt_timefield_value(value) 

2474 

2475 def value_to_string(self, obj): 

2476 val = self.value_from_object(obj) 

2477 return "" if val is None else val.isoformat() 

2478 

2479 def formfield(self, **kwargs): 

2480 return super().formfield( 

2481 **{ 

2482 "form_class": forms.TimeField, 

2483 **kwargs, 

2484 } 

2485 ) 

2486 

2487 

2488class URLField(CharField): 

2489 default_validators = [validators.URLValidator()] 

2490 description = _("URL") 

2491 

2492 def __init__(self, verbose_name=None, name=None, **kwargs): 

2493 kwargs.setdefault("max_length", 200) 

2494 super().__init__(verbose_name, name, **kwargs) 

2495 

2496 def deconstruct(self): 

2497 name, path, args, kwargs = super().deconstruct() 

2498 if kwargs.get("max_length") == 200: 

2499 del kwargs["max_length"] 

2500 return name, path, args, kwargs 

2501 

2502 def formfield(self, **kwargs): 

2503 # As with CharField, this will cause URL validation to be performed 

2504 # twice. 

2505 return super().formfield( 

2506 **{ 

2507 "form_class": forms.URLField, 

2508 **kwargs, 

2509 } 

2510 ) 

2511 

2512 

2513class BinaryField(Field): 

2514 description = _("Raw binary data") 

2515 empty_values = [None, b""] 

2516 

2517 def __init__(self, *args, **kwargs): 

2518 kwargs.setdefault("editable", False) 

2519 super().__init__(*args, **kwargs) 

2520 if self.max_length is not None: 

2521 self.validators.append(validators.MaxLengthValidator(self.max_length)) 

2522 

2523 def check(self, **kwargs): 

2524 return [*super().check(**kwargs), *self._check_str_default_value()] 

2525 

2526 def _check_str_default_value(self): 

2527 if self.has_default() and isinstance(self.default, str): 

2528 return [ 

2529 checks.Error( 

2530 "BinaryField's default cannot be a string. Use bytes " 

2531 "content instead.", 

2532 obj=self, 

2533 id="fields.E170", 

2534 ) 

2535 ] 

2536 return [] 

2537 

2538 def deconstruct(self): 

2539 name, path, args, kwargs = super().deconstruct() 

2540 if self.editable: 

2541 kwargs["editable"] = True 

2542 else: 

2543 del kwargs["editable"] 

2544 return name, path, args, kwargs 

2545 

2546 def get_internal_type(self): 

2547 return "BinaryField" 

2548 

2549 def get_placeholder(self, value, compiler, connection): 

2550 return connection.ops.binary_placeholder_sql(value) 

2551 

2552 def get_default(self): 

2553 if self.has_default() and not callable(self.default): 

2554 return self.default 

2555 default = super().get_default() 

2556 if default == "": 

2557 return b"" 

2558 return default 

2559 

2560 def get_db_prep_value(self, value, connection, prepared=False): 

2561 value = super().get_db_prep_value(value, connection, prepared) 

2562 if value is not None: 

2563 return connection.Database.Binary(value) 

2564 return value 

2565 

2566 def value_to_string(self, obj): 

2567 """Binary data is serialized as base64""" 

2568 return b64encode(self.value_from_object(obj)).decode("ascii") 

2569 

2570 def to_python(self, value): 

2571 # If it's a string, it should be base64-encoded data 

2572 if isinstance(value, str): 

2573 return memoryview(b64decode(value.encode("ascii"))) 

2574 return value 

2575 

2576 

2577class UUIDField(Field): 

2578 default_error_messages = { 

2579 "invalid": _("“%(value)s” is not a valid UUID."), 

2580 } 

2581 description = _("Universally unique identifier") 

2582 empty_strings_allowed = False 

2583 

2584 def __init__(self, verbose_name=None, **kwargs): 

2585 kwargs["max_length"] = 32 

2586 super().__init__(verbose_name, **kwargs) 

2587 

2588 def deconstruct(self): 

2589 name, path, args, kwargs = super().deconstruct() 

2590 del kwargs["max_length"] 

2591 return name, path, args, kwargs 

2592 

2593 def get_internal_type(self): 

2594 return "UUIDField" 

2595 

2596 def get_prep_value(self, value): 

2597 value = super().get_prep_value(value) 

2598 return self.to_python(value) 

2599 

2600 def get_db_prep_value(self, value, connection, prepared=False): 

2601 if value is None: 2601 ↛ 2602line 2601 didn't jump to line 2602, because the condition on line 2601 was never true

2602 return None 

2603 if not isinstance(value, uuid.UUID): 2603 ↛ 2604line 2603 didn't jump to line 2604, because the condition on line 2603 was never true

2604 value = self.to_python(value) 

2605 

2606 if connection.features.has_native_uuid_field: 2606 ↛ 2608line 2606 didn't jump to line 2608, because the condition on line 2606 was never false

2607 return value 

2608 return value.hex 

2609 

2610 def to_python(self, value): 

2611 if value is not None and not isinstance(value, uuid.UUID): 

2612 input_form = "int" if isinstance(value, int) else "hex" 

2613 try: 

2614 return uuid.UUID(**{input_form: value}) 

2615 except (AttributeError, ValueError): 

2616 raise exceptions.ValidationError( 

2617 self.error_messages["invalid"], 

2618 code="invalid", 

2619 params={"value": value}, 

2620 ) 

2621 return value 

2622 

2623 def formfield(self, **kwargs): 

2624 return super().formfield( 

2625 **{ 

2626 "form_class": forms.UUIDField, 

2627 **kwargs, 

2628 } 

2629 ) 

2630 

2631 

2632class AutoFieldMixin: 

2633 db_returning = True 

2634 

2635 def __init__(self, *args, **kwargs): 

2636 kwargs["blank"] = True 

2637 super().__init__(*args, **kwargs) 

2638 

2639 def check(self, **kwargs): 

2640 return [ 

2641 *super().check(**kwargs), 

2642 *self._check_primary_key(), 

2643 ] 

2644 

2645 def _check_primary_key(self): 

2646 if not self.primary_key: 2646 ↛ 2647line 2646 didn't jump to line 2647, because the condition on line 2646 was never true

2647 return [ 

2648 checks.Error( 

2649 "AutoFields must set primary_key=True.", 

2650 obj=self, 

2651 id="fields.E100", 

2652 ), 

2653 ] 

2654 else: 

2655 return [] 

2656 

2657 def deconstruct(self): 

2658 name, path, args, kwargs = super().deconstruct() 

2659 del kwargs["blank"] 

2660 kwargs["primary_key"] = True 

2661 return name, path, args, kwargs 

2662 

2663 def validate(self, value, model_instance): 

2664 pass 

2665 

2666 def get_db_prep_value(self, value, connection, prepared=False): 

2667 if not prepared: 

2668 value = self.get_prep_value(value) 

2669 value = connection.ops.validate_autopk_value(value) 

2670 return value 

2671 

2672 def contribute_to_class(self, cls, name, **kwargs): 

2673 if cls._meta.auto_field: 2673 ↛ 2674line 2673 didn't jump to line 2674, because the condition on line 2673 was never true

2674 raise ValueError( 

2675 "Model %s can't have more than one auto-generated field." 

2676 % cls._meta.label 

2677 ) 

2678 super().contribute_to_class(cls, name, **kwargs) 

2679 cls._meta.auto_field = self 

2680 

2681 def formfield(self, **kwargs): 

2682 return None 

2683 

2684 

2685class AutoFieldMeta(type): 

2686 """ 

2687 Metaclass to maintain backward inheritance compatibility for AutoField. 

2688 

2689 It is intended that AutoFieldMixin become public API when it is possible to 

2690 create a non-integer automatically-generated field using column defaults 

2691 stored in the database. 

2692 

2693 In many areas Django also relies on using isinstance() to check for an 

2694 automatically-generated field as a subclass of AutoField. A new flag needs 

2695 to be implemented on Field to be used instead. 

2696 

2697 When these issues have been addressed, this metaclass could be used to 

2698 deprecate inheritance from AutoField and use of isinstance() with AutoField 

2699 for detecting automatically-generated fields. 

2700 """ 

2701 

2702 @property 

2703 def _subclasses(self): 

2704 return (BigAutoField, SmallAutoField) 

2705 

2706 def __instancecheck__(self, instance): 

2707 return isinstance(instance, self._subclasses) or super().__instancecheck__( 

2708 instance 

2709 ) 

2710 

2711 def __subclasscheck__(self, subclass): 

2712 return issubclass(subclass, self._subclasses) or super().__subclasscheck__( 

2713 subclass 

2714 ) 

2715 

2716 

2717class AutoField(AutoFieldMixin, IntegerField, metaclass=AutoFieldMeta): 

2718 def get_internal_type(self): 

2719 return "AutoField" 

2720 

2721 def rel_db_type(self, connection): 

2722 return IntegerField().db_type(connection=connection) 

2723 

2724 

2725class BigAutoField(AutoFieldMixin, BigIntegerField): 

2726 def get_internal_type(self): 

2727 return "BigAutoField" 

2728 

2729 def rel_db_type(self, connection): 

2730 return BigIntegerField().db_type(connection=connection) 

2731 

2732 

2733class SmallAutoField(AutoFieldMixin, SmallIntegerField): 

2734 def get_internal_type(self): 

2735 return "SmallAutoField" 

2736 

2737 def rel_db_type(self, connection): 

2738 return SmallIntegerField().db_type(connection=connection)