-
commit 4b037b92b6f98081de848d31f06f0b4f7045d403
Author: Дилян Палаузов <Dilyan.Palauzov@db.com>
Date: Mon Nov 20 13:15:38 2017 +0100
Remove 'else' after 'return' or 'raise'
diff --git a/django/apps/config.py b/django/apps/config.py
index 157fda7..f5f913b 100644
a
|
b
|
class AppConfig:
|
71 | 71 | "The app module %r has multiple filesystem locations (%r); " |
72 | 72 | "you must configure this app with an AppConfig subclass " |
73 | 73 | "with a 'path' class attribute." % (module, paths)) |
74 | | elif not paths: |
| 74 | if not paths: |
75 | 75 | raise ImproperlyConfigured( |
76 | 76 | "The app module %r has no filesystem location, " |
77 | 77 | "you must configure this app with an AppConfig subclass " |
-
diff --git a/django/conf/urls/static.py b/django/conf/urls/static.py
index 150f4ff..83ebda4 100644
a
|
b
|
def static(prefix, view=serve, **kwargs):
|
19 | 19 | """ |
20 | 20 | if not prefix: |
21 | 21 | raise ImproperlyConfigured("Empty static prefix not permitted") |
22 | | elif not settings.DEBUG or '://' in prefix: |
| 22 | if not settings.DEBUG or '://' in prefix: |
23 | 23 | # No-op if not in debug mode or a non-local prefix. |
24 | 24 | return [] |
25 | 25 | return [ |
-
diff --git a/django/contrib/admin/checks.py b/django/contrib/admin/checks.py
index c8e05bd..182d805 100644
a
|
b
|
class BaseModelAdminChecks:
|
87 | 87 | """ |
88 | 88 | if not isinstance(obj.autocomplete_fields, (list, tuple)): |
89 | 89 | return must_be('a list or tuple', option='autocomplete_fields', obj=obj, id='admin.E036') |
90 | | else: |
91 | | return list(chain.from_iterable([ |
92 | | self._check_autocomplete_fields_item(obj, obj.model, field_name, 'autocomplete_fields[%d]' % index) |
93 | | for index, field_name in enumerate(obj.autocomplete_fields) |
94 | | ])) |
| 90 | return list(chain.from_iterable([ |
| 91 | self._check_autocomplete_fields_item(obj, obj.model, field_name, 'autocomplete_fields[%d]' % index) |
| 92 | for index, field_name in enumerate(obj.autocomplete_fields) |
| 93 | ])) |
95 | 94 | |
96 | 95 | def _check_autocomplete_fields_item(self, obj, model, field_name, label): |
97 | 96 | """ |
… |
… |
class BaseModelAdminChecks:
|
122 | 121 | id='admin.E039', |
123 | 122 | ) |
124 | 123 | ] |
125 | | elif not related_admin.search_fields: |
| 124 | if not related_admin.search_fields: |
126 | 125 | return [ |
127 | 126 | checks.Error( |
128 | 127 | '%s must define "search_fields", because it\'s ' |
… |
… |
class BaseModelAdminChecks:
|
142 | 141 | |
143 | 142 | if not isinstance(obj.raw_id_fields, (list, tuple)): |
144 | 143 | return must_be('a list or tuple', option='raw_id_fields', obj=obj, id='admin.E001') |
145 | | else: |
146 | | return list(chain.from_iterable( |
147 | | self._check_raw_id_fields_item(obj, obj.model, field_name, 'raw_id_fields[%d]' % index) |
148 | | for index, field_name in enumerate(obj.raw_id_fields) |
149 | | )) |
| 144 | return list(chain.from_iterable( |
| 145 | self._check_raw_id_fields_item(obj, obj.model, field_name, 'raw_id_fields[%d]' % index) |
| 146 | for index, field_name in enumerate(obj.raw_id_fields) |
| 147 | )) |
150 | 148 | |
151 | 149 | def _check_raw_id_fields_item(self, obj, model, field_name, label): |
152 | 150 | """ Check an item of `raw_id_fields`, i.e. check that field named |
… |
… |
class BaseModelAdminChecks:
|
162 | 160 | if not field.many_to_many and not isinstance(field, models.ForeignKey): |
163 | 161 | return must_be('a foreign key or a many-to-many field', |
164 | 162 | option=label, obj=obj, id='admin.E003') |
165 | | else: |
166 | | return [] |
| 163 | return [] |
167 | 164 | |
168 | 165 | def _check_fields(self, obj): |
169 | 166 | """ Check that `fields` only refer to existing fields, doesn't contain |
… |
… |
class BaseModelAdminChecks:
|
172 | 169 | |
173 | 170 | if obj.fields is None: |
174 | 171 | return [] |
175 | | elif not isinstance(obj.fields, (list, tuple)): |
| 172 | if not isinstance(obj.fields, (list, tuple)): |
176 | 173 | return must_be('a list or tuple', option='fields', obj=obj, id='admin.E004') |
177 | | elif obj.fieldsets: |
| 174 | if obj.fieldsets: |
178 | 175 | return [ |
179 | 176 | checks.Error( |
180 | 177 | "Both 'fieldsets' and 'fields' are specified.", |
… |
… |
class BaseModelAdminChecks:
|
203 | 200 | |
204 | 201 | if obj.fieldsets is None: |
205 | 202 | return [] |
206 | | elif not isinstance(obj.fieldsets, (list, tuple)): |
| 203 | if not isinstance(obj.fieldsets, (list, tuple)): |
207 | 204 | return must_be('a list or tuple', option='fieldsets', obj=obj, id='admin.E007') |
208 | | else: |
209 | | return list(chain.from_iterable( |
210 | | self._check_fieldsets_item(obj, obj.model, fieldset, 'fieldsets[%d]' % index) |
211 | | for index, fieldset in enumerate(obj.fieldsets) |
212 | | )) |
| 205 | return list(chain.from_iterable( |
| 206 | self._check_fieldsets_item(obj, obj.model, fieldset, 'fieldsets[%d]' % index) |
| 207 | for index, fieldset in enumerate(obj.fieldsets) |
| 208 | )) |
213 | 209 | |
214 | 210 | def _check_fieldsets_item(self, obj, model, fieldset, label): |
215 | 211 | """ Check an item of `fieldsets`, i.e. check that this is a pair of a |
… |
… |
class BaseModelAdminChecks:
|
217 | 213 | |
218 | 214 | if not isinstance(fieldset, (list, tuple)): |
219 | 215 | return must_be('a list or tuple', option=label, obj=obj, id='admin.E008') |
220 | | elif len(fieldset) != 2: |
| 216 | if len(fieldset) != 2: |
221 | 217 | return must_be('of length 2', option=label, obj=obj, id='admin.E009') |
222 | | elif not isinstance(fieldset[1], dict): |
| 218 | if not isinstance(fieldset[1], dict): |
223 | 219 | return must_be('a dictionary', option='%s[1]' % label, obj=obj, id='admin.E010') |
224 | | elif 'fields' not in fieldset[1]: |
| 220 | if 'fields' not in fieldset[1]: |
225 | 221 | return [ |
226 | 222 | checks.Error( |
227 | 223 | "The value of '%s[1]' must contain the key 'fields'." % label, |
… |
… |
class BaseModelAdminChecks:
|
229 | 225 | id='admin.E011', |
230 | 226 | ) |
231 | 227 | ] |
232 | | elif not isinstance(fieldset[1]['fields'], (list, tuple)): |
| 228 | if not isinstance(fieldset[1]['fields'], (list, tuple)): |
233 | 229 | return must_be('a list or tuple', option="%s[1]['fields']" % label, obj=obj, id='admin.E008') |
234 | 230 | |
235 | 231 | fields = flatten(fieldset[1]['fields']) |
… |
… |
class BaseModelAdminChecks:
|
256 | 252 | self._check_field_spec_item(obj, model, field_name, "%s[%d]" % (label, index)) |
257 | 253 | for index, field_name in enumerate(fields) |
258 | 254 | )) |
259 | | else: |
260 | | return self._check_field_spec_item(obj, model, fields, label) |
| 255 | return self._check_field_spec_item(obj, model, fields, label) |
261 | 256 | |
262 | 257 | def _check_field_spec_item(self, obj, model, field_name, label): |
263 | 258 | if field_name in obj.readonly_fields: |
… |
… |
class BaseModelAdminChecks:
|
265 | 260 | # it's in readonly_fields, readonly_fields will handle the |
266 | 261 | # validation of such things. |
267 | 262 | return [] |
| 263 | try: |
| 264 | field = model._meta.get_field(field_name) |
| 265 | except FieldDoesNotExist: |
| 266 | # If we can't find a field on the model that matches, it could |
| 267 | # be an extra field on the form. |
| 268 | return [] |
268 | 269 | else: |
269 | | try: |
270 | | field = model._meta.get_field(field_name) |
271 | | except FieldDoesNotExist: |
272 | | # If we can't find a field on the model that matches, it could |
273 | | # be an extra field on the form. |
274 | | return [] |
275 | | else: |
276 | | if (isinstance(field, models.ManyToManyField) and |
277 | | not field.remote_field.through._meta.auto_created): |
278 | | return [ |
279 | | checks.Error( |
280 | | "The value of '%s' cannot include the ManyToManyField '%s', " |
281 | | "because that field manually specifies a relationship model." |
282 | | % (label, field_name), |
283 | | obj=obj.__class__, |
284 | | id='admin.E013', |
285 | | ) |
286 | | ] |
287 | | else: |
288 | | return [] |
| 270 | if (isinstance(field, models.ManyToManyField) and |
| 271 | not field.remote_field.through._meta.auto_created): |
| 272 | return [ |
| 273 | checks.Error( |
| 274 | "The value of '%s' cannot include the ManyToManyField '%s', " |
| 275 | "because that field manually specifies a relationship model." |
| 276 | % (label, field_name), |
| 277 | obj=obj.__class__, |
| 278 | id='admin.E013', |
| 279 | ) |
| 280 | ] |
| 281 | return [] |
289 | 282 | |
290 | 283 | def _check_exclude(self, obj): |
291 | 284 | """ Check that exclude is a sequence without duplicates. """ |
292 | 285 | |
293 | 286 | if obj.exclude is None: # default value is None |
294 | 287 | return [] |
295 | | elif not isinstance(obj.exclude, (list, tuple)): |
| 288 | if not isinstance(obj.exclude, (list, tuple)): |
296 | 289 | return must_be('a list or tuple', option='exclude', obj=obj, id='admin.E014') |
297 | | elif len(obj.exclude) > len(set(obj.exclude)): |
| 290 | if len(obj.exclude) > len(set(obj.exclude)): |
298 | 291 | return [ |
299 | 292 | checks.Error( |
300 | 293 | "The value of 'exclude' contains duplicate field(s).", |
… |
… |
class BaseModelAdminChecks:
|
302 | 295 | id='admin.E015', |
303 | 296 | ) |
304 | 297 | ] |
305 | | else: |
306 | | return [] |
| 298 | return [] |
307 | 299 | |
308 | 300 | def _check_form(self, obj): |
309 | 301 | """ Check that form subclasses BaseModelForm. """ |
310 | 302 | if not issubclass(obj.form, BaseModelForm): |
311 | 303 | return must_inherit_from(parent='BaseModelForm', option='form', |
312 | 304 | obj=obj, id='admin.E016') |
313 | | else: |
314 | | return [] |
| 305 | return [] |
315 | 306 | |
316 | 307 | def _check_filter_vertical(self, obj): |
317 | 308 | """ Check that filter_vertical is a sequence of field names. """ |
318 | 309 | if not isinstance(obj.filter_vertical, (list, tuple)): |
319 | 310 | return must_be('a list or tuple', option='filter_vertical', obj=obj, id='admin.E017') |
320 | | else: |
321 | | return list(chain.from_iterable( |
322 | | self._check_filter_item(obj, obj.model, field_name, "filter_vertical[%d]" % index) |
323 | | for index, field_name in enumerate(obj.filter_vertical) |
324 | | )) |
| 311 | return list(chain.from_iterable( |
| 312 | self._check_filter_item(obj, obj.model, field_name, "filter_vertical[%d]" % index) |
| 313 | for index, field_name in enumerate(obj.filter_vertical) |
| 314 | )) |
325 | 315 | |
326 | 316 | def _check_filter_horizontal(self, obj): |
327 | 317 | """ Check that filter_horizontal is a sequence of field names. """ |
328 | 318 | if not isinstance(obj.filter_horizontal, (list, tuple)): |
329 | 319 | return must_be('a list or tuple', option='filter_horizontal', obj=obj, id='admin.E018') |
330 | | else: |
331 | | return list(chain.from_iterable( |
332 | | self._check_filter_item(obj, obj.model, field_name, "filter_horizontal[%d]" % index) |
333 | | for index, field_name in enumerate(obj.filter_horizontal) |
334 | | )) |
| 320 | return list(chain.from_iterable( |
| 321 | self._check_filter_item(obj, obj.model, field_name, "filter_horizontal[%d]" % index) |
| 322 | for index, field_name in enumerate(obj.filter_horizontal) |
| 323 | )) |
335 | 324 | |
336 | 325 | def _check_filter_item(self, obj, model, field_name, label): |
337 | 326 | """ Check one item of `filter_vertical` or `filter_horizontal`, i.e. |
… |
… |
class BaseModelAdminChecks:
|
342 | 331 | except FieldDoesNotExist: |
343 | 332 | return refer_to_missing_field(field=field_name, option=label, |
344 | 333 | model=model, obj=obj, id='admin.E019') |
345 | | else: |
346 | | if not field.many_to_many: |
347 | | return must_be('a many-to-many field', option=label, obj=obj, id='admin.E020') |
348 | | else: |
349 | | return [] |
| 334 | if not field.many_to_many: |
| 335 | return must_be('a many-to-many field', option=label, obj=obj, id='admin.E020') |
| 336 | return [] |
350 | 337 | |
351 | 338 | def _check_radio_fields(self, obj): |
352 | 339 | """ Check that `radio_fields` is a dictionary. """ |
353 | 340 | if not isinstance(obj.radio_fields, dict): |
354 | 341 | return must_be('a dictionary', option='radio_fields', obj=obj, id='admin.E021') |
355 | | else: |
356 | | return list(chain.from_iterable( |
357 | | self._check_radio_fields_key(obj, obj.model, field_name, 'radio_fields') + |
358 | | self._check_radio_fields_value(obj, val, 'radio_fields["%s"]' % field_name) |
359 | | for field_name, val in obj.radio_fields.items() |
360 | | )) |
| 342 | return list(chain.from_iterable( |
| 343 | self._check_radio_fields_key(obj, obj.model, field_name, 'radio_fields') + |
| 344 | self._check_radio_fields_value(obj, val, 'radio_fields["%s"]' % field_name) |
| 345 | for field_name, val in obj.radio_fields.items() |
| 346 | )) |
361 | 347 | |
362 | 348 | def _check_radio_fields_key(self, obj, model, field_name, label): |
363 | 349 | """ Check that a key of `radio_fields` dictionary is name of existing |
… |
… |
class BaseModelAdminChecks:
|
380 | 366 | id='admin.E023', |
381 | 367 | ) |
382 | 368 | ] |
383 | | else: |
384 | | return [] |
| 369 | return [] |
385 | 370 | |
386 | 371 | def _check_radio_fields_value(self, obj, val, label): |
387 | 372 | """ Check type of a value of `radio_fields` dictionary. """ |
… |
… |
class BaseModelAdminChecks:
|
396 | 381 | id='admin.E024', |
397 | 382 | ) |
398 | 383 | ] |
399 | | else: |
400 | | return [] |
| 384 | return [] |
401 | 385 | |
402 | 386 | def _check_view_on_site_url(self, obj): |
403 | 387 | if not callable(obj.view_on_site) and not isinstance(obj.view_on_site, bool): |
… |
… |
class BaseModelAdminChecks:
|
408 | 392 | id='admin.E025', |
409 | 393 | ) |
410 | 394 | ] |
411 | | else: |
412 | | return [] |
| 395 | return [] |
413 | 396 | |
414 | 397 | def _check_prepopulated_fields(self, obj): |
415 | 398 | """ Check that `prepopulated_fields` is a dictionary containing allowed |
416 | 399 | field types. """ |
417 | 400 | if not isinstance(obj.prepopulated_fields, dict): |
418 | 401 | return must_be('a dictionary', option='prepopulated_fields', obj=obj, id='admin.E026') |
419 | | else: |
420 | | return list(chain.from_iterable( |
421 | | self._check_prepopulated_fields_key(obj, obj.model, field_name, 'prepopulated_fields') + |
422 | | self._check_prepopulated_fields_value(obj, obj.model, val, 'prepopulated_fields["%s"]' % field_name) |
423 | | for field_name, val in obj.prepopulated_fields.items() |
424 | | )) |
| 402 | return list(chain.from_iterable( |
| 403 | self._check_prepopulated_fields_key(obj, obj.model, field_name, 'prepopulated_fields') + |
| 404 | self._check_prepopulated_fields_value(obj, obj.model, val, 'prepopulated_fields["%s"]' % field_name) |
| 405 | for field_name, val in obj.prepopulated_fields.items() |
| 406 | )) |
425 | 407 | |
426 | 408 | def _check_prepopulated_fields_key(self, obj, model, field_name, label): |
427 | 409 | """ Check a key of `prepopulated_fields` dictionary, i.e. check that it |
… |
… |
class BaseModelAdminChecks:
|
443 | 425 | id='admin.E028', |
444 | 426 | ) |
445 | 427 | ] |
446 | | else: |
447 | | return [] |
| 428 | return [] |
448 | 429 | |
449 | 430 | def _check_prepopulated_fields_value(self, obj, model, val, label): |
450 | 431 | """ Check a value of `prepopulated_fields` dictionary, i.e. it's an |
… |
… |
class BaseModelAdminChecks:
|
452 | 433 | |
453 | 434 | if not isinstance(val, (list, tuple)): |
454 | 435 | return must_be('a list or tuple', option=label, obj=obj, id='admin.E029') |
455 | | else: |
456 | | return list(chain.from_iterable( |
457 | | self._check_prepopulated_fields_value_item(obj, model, subfield_name, "%s[%r]" % (label, index)) |
458 | | for index, subfield_name in enumerate(val) |
459 | | )) |
| 436 | return list(chain.from_iterable( |
| 437 | self._check_prepopulated_fields_value_item(obj, model, subfield_name, "%s[%r]" % (label, index)) |
| 438 | for index, subfield_name in enumerate(val) |
| 439 | )) |
460 | 440 | |
461 | 441 | def _check_prepopulated_fields_value_item(self, obj, model, field_name, label): |
462 | 442 | """ For `prepopulated_fields` equal to {"slug": ("title",)}, |
… |
… |
class BaseModelAdminChecks:
|
475 | 455 | # ordering = None |
476 | 456 | if obj.ordering is None: # The default value is None |
477 | 457 | return [] |
478 | | elif not isinstance(obj.ordering, (list, tuple)): |
| 458 | if not isinstance(obj.ordering, (list, tuple)): |
479 | 459 | return must_be('a list or tuple', option='ordering', obj=obj, id='admin.E031') |
480 | | else: |
481 | | return list(chain.from_iterable( |
482 | | self._check_ordering_item(obj, obj.model, field_name, 'ordering[%d]' % index) |
483 | | for index, field_name in enumerate(obj.ordering) |
484 | | )) |
| 460 | return list(chain.from_iterable( |
| 461 | self._check_ordering_item(obj, obj.model, field_name, 'ordering[%d]' % index) |
| 462 | for index, field_name in enumerate(obj.ordering) |
| 463 | )) |
485 | 464 | |
486 | 465 | def _check_ordering_item(self, obj, model, field_name, label): |
487 | 466 | """ Check that `ordering` refers to existing fields. """ |
… |
… |
class BaseModelAdminChecks:
|
496 | 475 | id='admin.E032', |
497 | 476 | ) |
498 | 477 | ] |
499 | | elif field_name == '?': |
| 478 | if field_name == '?': |
500 | 479 | return [] |
501 | | elif LOOKUP_SEP in field_name: |
| 480 | if LOOKUP_SEP in field_name: |
502 | 481 | # Skip ordering in the format field1__field2 (FIXME: checking |
503 | 482 | # this format would be nice, but it's a little fiddly). |
504 | 483 | return [] |
| 484 | if field_name.startswith('-'): |
| 485 | field_name = field_name[1:] |
| 486 | if field_name == 'pk': |
| 487 | return [] |
| 488 | try: |
| 489 | model._meta.get_field(field_name) |
| 490 | except FieldDoesNotExist: |
| 491 | return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E033') |
505 | 492 | else: |
506 | | if field_name.startswith('-'): |
507 | | field_name = field_name[1:] |
508 | | if field_name == 'pk': |
509 | | return [] |
510 | | try: |
511 | | model._meta.get_field(field_name) |
512 | | except FieldDoesNotExist: |
513 | | return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E033') |
514 | | else: |
515 | | return [] |
| 493 | return [] |
516 | 494 | |
517 | 495 | def _check_readonly_fields(self, obj): |
518 | 496 | """ Check that readonly_fields refers to proper attribute or field. """ |
519 | 497 | |
520 | 498 | if obj.readonly_fields == (): |
521 | 499 | return [] |
522 | | elif not isinstance(obj.readonly_fields, (list, tuple)): |
| 500 | if not isinstance(obj.readonly_fields, (list, tuple)): |
523 | 501 | return must_be('a list or tuple', option='readonly_fields', obj=obj, id='admin.E034') |
524 | | else: |
525 | | return list(chain.from_iterable( |
526 | | self._check_readonly_fields_item(obj, obj.model, field_name, "readonly_fields[%d]" % index) |
527 | | for index, field_name in enumerate(obj.readonly_fields) |
528 | | )) |
| 502 | return list(chain.from_iterable( |
| 503 | self._check_readonly_fields_item(obj, obj.model, field_name, "readonly_fields[%d]" % index) |
| 504 | for index, field_name in enumerate(obj.readonly_fields) |
| 505 | )) |
529 | 506 | |
530 | 507 | def _check_readonly_fields_item(self, obj, model, field_name, label): |
531 | 508 | if callable(field_name): |
532 | 509 | return [] |
533 | | elif hasattr(obj, field_name): |
| 510 | if hasattr(obj, field_name): |
534 | 511 | return [] |
535 | | elif hasattr(model, field_name): |
| 512 | if hasattr(model, field_name): |
536 | 513 | return [] |
| 514 | try: |
| 515 | model._meta.get_field(field_name) |
| 516 | except FieldDoesNotExist: |
| 517 | return [ |
| 518 | checks.Error( |
| 519 | "The value of '%s' is not a callable, an attribute of '%s', or an attribute of '%s.%s'." % ( |
| 520 | label, obj.__class__.__name__, model._meta.app_label, model._meta.object_name |
| 521 | ), |
| 522 | obj=obj.__class__, |
| 523 | id='admin.E035', |
| 524 | ) |
| 525 | ] |
537 | 526 | else: |
538 | | try: |
539 | | model._meta.get_field(field_name) |
540 | | except FieldDoesNotExist: |
541 | | return [ |
542 | | checks.Error( |
543 | | "The value of '%s' is not a callable, an attribute of '%s', or an attribute of '%s.%s'." % ( |
544 | | label, obj.__class__.__name__, model._meta.app_label, model._meta.object_name |
545 | | ), |
546 | | obj=obj.__class__, |
547 | | id='admin.E035', |
548 | | ) |
549 | | ] |
550 | | else: |
551 | | return [] |
| 527 | return [] |
552 | 528 | |
553 | 529 | |
554 | 530 | class ModelAdminChecks(BaseModelAdminChecks): |
… |
… |
class ModelAdminChecks(BaseModelAdminChecks):
|
575 | 551 | if not isinstance(obj.save_as, bool): |
576 | 552 | return must_be('a boolean', option='save_as', |
577 | 553 | obj=obj, id='admin.E101') |
578 | | else: |
579 | | return [] |
| 554 | return [] |
580 | 555 | |
581 | 556 | def _check_save_on_top(self, obj): |
582 | 557 | """ Check save_on_top is a boolean. """ |
… |
… |
class ModelAdminChecks(BaseModelAdminChecks):
|
584 | 559 | if not isinstance(obj.save_on_top, bool): |
585 | 560 | return must_be('a boolean', option='save_on_top', |
586 | 561 | obj=obj, id='admin.E102') |
587 | | else: |
588 | | return [] |
| 562 | return [] |
589 | 563 | |
590 | 564 | def _check_inlines(self, obj): |
591 | 565 | """ Check all inline model admin classes. """ |
592 | 566 | |
593 | 567 | if not isinstance(obj.inlines, (list, tuple)): |
594 | 568 | return must_be('a list or tuple', option='inlines', obj=obj, id='admin.E103') |
595 | | else: |
596 | | return list(chain.from_iterable( |
597 | | self._check_inlines_item(obj, obj.model, item, "inlines[%d]" % index) |
598 | | for index, item in enumerate(obj.inlines) |
599 | | )) |
| 569 | return list(chain.from_iterable( |
| 570 | self._check_inlines_item(obj, obj.model, item, "inlines[%d]" % index) |
| 571 | for index, item in enumerate(obj.inlines) |
| 572 | )) |
600 | 573 | |
601 | 574 | def _check_inlines_item(self, obj, model, inline, label): |
602 | 575 | """ Check one inline model admin. """ |
… |
… |
class ModelAdminChecks(BaseModelAdminChecks):
|
612 | 585 | id='admin.E104', |
613 | 586 | ) |
614 | 587 | ] |
615 | | elif not inline.model: |
| 588 | if not inline.model: |
616 | 589 | return [ |
617 | 590 | checks.Error( |
618 | 591 | "'%s' must have a 'model' attribute." % inline_label, |
… |
… |
class ModelAdminChecks(BaseModelAdminChecks):
|
620 | 593 | id='admin.E105', |
621 | 594 | ) |
622 | 595 | ] |
623 | | elif not issubclass(inline.model, models.Model): |
| 596 | if not issubclass(inline.model, models.Model): |
624 | 597 | return must_be('a Model', option='%s.model' % inline_label, obj=obj, id='admin.E106') |
625 | | else: |
626 | | return inline(model, obj.admin_site).check() |
| 598 | return inline(model, obj.admin_site).check() |
627 | 599 | |
628 | 600 | def _check_list_display(self, obj): |
629 | 601 | """ Check that list_display only contains fields or usable attributes. |
… |
… |
class ModelAdminChecks(BaseModelAdminChecks):
|
631 | 603 | |
632 | 604 | if not isinstance(obj.list_display, (list, tuple)): |
633 | 605 | return must_be('a list or tuple', option='list_display', obj=obj, id='admin.E107') |
634 | | else: |
635 | | return list(chain.from_iterable( |
636 | | self._check_list_display_item(obj, obj.model, item, "list_display[%d]" % index) |
637 | | for index, item in enumerate(obj.list_display) |
638 | | )) |
| 606 | return list(chain.from_iterable( |
| 607 | self._check_list_display_item(obj, obj.model, item, "list_display[%d]" % index) |
| 608 | for index, item in enumerate(obj.list_display) |
| 609 | )) |
639 | 610 | |
640 | 611 | def _check_list_display_item(self, obj, model, item, label): |
641 | 612 | if callable(item): |
642 | 613 | return [] |
643 | | elif hasattr(obj, item): |
| 614 | if hasattr(obj, item): |
644 | 615 | return [] |
645 | | elif hasattr(model, item): |
| 616 | if hasattr(model, item): |
646 | 617 | try: |
647 | 618 | field = model._meta.get_field(item) |
648 | 619 | except FieldDoesNotExist: |
… |
… |
class ModelAdminChecks(BaseModelAdminChecks):
|
657 | 628 | ) |
658 | 629 | ] |
659 | 630 | return [] |
660 | | else: |
661 | | return [ |
662 | | checks.Error( |
663 | | "The value of '%s' refers to '%s', which is not a callable, " |
664 | | "an attribute of '%s', or an attribute or method on '%s.%s'." % ( |
665 | | label, item, obj.__class__.__name__, |
666 | | model._meta.app_label, model._meta.object_name, |
667 | | ), |
668 | | obj=obj.__class__, |
669 | | id='admin.E108', |
670 | | ) |
671 | | ] |
| 631 | return [ |
| 632 | checks.Error( |
| 633 | "The value of '%s' refers to '%s', which is not a callable, " |
| 634 | "an attribute of '%s', or an attribute or method on '%s.%s'." % ( |
| 635 | label, item, obj.__class__.__name__, |
| 636 | model._meta.app_label, model._meta.object_name, |
| 637 | ), |
| 638 | obj=obj.__class__, |
| 639 | id='admin.E108', |
| 640 | ) |
| 641 | ] |
672 | 642 | |
673 | 643 | def _check_list_display_links(self, obj): |
674 | 644 | """ Check that list_display_links is a unique subset of list_display. |
… |
… |
class ModelAdminChecks(BaseModelAdminChecks):
|
677 | 647 | |
678 | 648 | if obj.list_display_links is None: |
679 | 649 | return [] |
680 | | elif not isinstance(obj.list_display_links, (list, tuple)): |
| 650 | if not isinstance(obj.list_display_links, (list, tuple)): |
681 | 651 | return must_be('a list, a tuple, or None', option='list_display_links', obj=obj, id='admin.E110') |
682 | 652 | # Check only if ModelAdmin.get_list_display() isn't overridden. |
683 | | elif obj.get_list_display.__func__ is ModelAdmin.get_list_display: |
| 653 | if obj.get_list_display.__func__ is ModelAdmin.get_list_display: |
684 | 654 | return list(chain.from_iterable( |
685 | 655 | self._check_list_display_links_item(obj, field_name, "list_display_links[%d]" % index) |
686 | 656 | for index, field_name in enumerate(obj.list_display_links) |
… |
… |
class ModelAdminChecks(BaseModelAdminChecks):
|
698 | 668 | id='admin.E111', |
699 | 669 | ) |
700 | 670 | ] |
701 | | else: |
702 | | return [] |
| 671 | return [] |
703 | 672 | |
704 | 673 | def _check_list_filter(self, obj): |
705 | 674 | if not isinstance(obj.list_filter, (list, tuple)): |
706 | 675 | return must_be('a list or tuple', option='list_filter', obj=obj, id='admin.E112') |
707 | | else: |
708 | | return list(chain.from_iterable( |
709 | | self._check_list_filter_item(obj, obj.model, item, "list_filter[%d]" % index) |
710 | | for index, item in enumerate(obj.list_filter) |
711 | | )) |
| 676 | return list(chain.from_iterable( |
| 677 | self._check_list_filter_item(obj, obj.model, item, "list_filter[%d]" % index) |
| 678 | for index, item in enumerate(obj.list_filter) |
| 679 | )) |
712 | 680 | |
713 | 681 | def _check_list_filter_item(self, obj, model, item, label): |
714 | 682 | """ |
… |
… |
class ModelAdminChecks(BaseModelAdminChecks):
|
727 | 695 | return must_inherit_from(parent='ListFilter', option=label, |
728 | 696 | obj=obj, id='admin.E113') |
729 | 697 | # ... but not a FieldListFilter. |
730 | | elif issubclass(item, FieldListFilter): |
| 698 | if issubclass(item, FieldListFilter): |
731 | 699 | return [ |
732 | 700 | checks.Error( |
733 | 701 | "The value of '%s' must not inherit from 'FieldListFilter'." % label, |
… |
… |
class ModelAdminChecks(BaseModelAdminChecks):
|
735 | 703 | id='admin.E114', |
736 | 704 | ) |
737 | 705 | ] |
738 | | else: |
739 | | return [] |
740 | | elif isinstance(item, (tuple, list)): |
| 706 | return [] |
| 707 | if isinstance(item, (tuple, list)): |
741 | 708 | # item is option #2 |
742 | 709 | field, list_filter_class = item |
743 | 710 | if not issubclass(list_filter_class, FieldListFilter): |
744 | 711 | return must_inherit_from(parent='FieldListFilter', option='%s[1]' % label, obj=obj, id='admin.E115') |
745 | | else: |
746 | | return [] |
747 | | else: |
748 | | # item is option #1 |
749 | | field = item |
| 712 | return [] |
| 713 | # item is option #1 |
| 714 | field = item |
750 | 715 | |
751 | | # Validate the field string |
752 | | try: |
753 | | get_fields_from_path(model, field) |
754 | | except (NotRelationField, FieldDoesNotExist): |
755 | | return [ |
756 | | checks.Error( |
757 | | "The value of '%s' refers to '%s', which does not refer to a Field." % (label, field), |
758 | | obj=obj.__class__, |
759 | | id='admin.E116', |
760 | | ) |
761 | | ] |
762 | | else: |
763 | | return [] |
| 716 | # Validate the field string |
| 717 | try: |
| 718 | get_fields_from_path(model, field) |
| 719 | except (NotRelationField, FieldDoesNotExist): |
| 720 | return [ |
| 721 | checks.Error( |
| 722 | "The value of '%s' refers to '%s', which does not refer to a Field." % (label, field), |
| 723 | obj=obj.__class__, |
| 724 | id='admin.E116', |
| 725 | ) |
| 726 | ] |
| 727 | else: |
| 728 | return [] |
764 | 729 | |
765 | 730 | def _check_list_select_related(self, obj): |
766 | 731 | """ Check that list_select_related is a boolean, a list or a tuple. """ |
767 | 732 | |
768 | 733 | if not isinstance(obj.list_select_related, (bool, list, tuple)): |
769 | 734 | return must_be('a boolean, tuple or list', option='list_select_related', obj=obj, id='admin.E117') |
770 | | else: |
771 | | return [] |
| 735 | return [] |
772 | 736 | |
773 | 737 | def _check_list_per_page(self, obj): |
774 | 738 | """ Check that list_per_page is an integer. """ |
775 | 739 | |
776 | 740 | if not isinstance(obj.list_per_page, int): |
777 | 741 | return must_be('an integer', option='list_per_page', obj=obj, id='admin.E118') |
778 | | else: |
779 | | return [] |
| 742 | return [] |
780 | 743 | |
781 | 744 | def _check_list_max_show_all(self, obj): |
782 | 745 | """ Check that list_max_show_all is an integer. """ |
783 | 746 | |
784 | 747 | if not isinstance(obj.list_max_show_all, int): |
785 | 748 | return must_be('an integer', option='list_max_show_all', obj=obj, id='admin.E119') |
786 | | else: |
787 | | return [] |
| 749 | return [] |
788 | 750 | |
789 | 751 | def _check_list_editable(self, obj): |
790 | 752 | """ Check that list_editable is a sequence of editable fields from |
… |
… |
class ModelAdminChecks(BaseModelAdminChecks):
|
792 | 754 | |
793 | 755 | if not isinstance(obj.list_editable, (list, tuple)): |
794 | 756 | return must_be('a list or tuple', option='list_editable', obj=obj, id='admin.E120') |
795 | | else: |
796 | | return list(chain.from_iterable( |
797 | | self._check_list_editable_item(obj, obj.model, item, "list_editable[%d]" % index) |
798 | | for index, item in enumerate(obj.list_editable) |
799 | | )) |
| 757 | return list(chain.from_iterable( |
| 758 | self._check_list_editable_item(obj, obj.model, item, "list_editable[%d]" % index) |
| 759 | for index, item in enumerate(obj.list_editable) |
| 760 | )) |
800 | 761 | |
801 | 762 | def _check_list_editable_item(self, obj, model, field_name, label): |
802 | 763 | try: |
… |
… |
class ModelAdminChecks(BaseModelAdminChecks):
|
813 | 774 | id='admin.E122', |
814 | 775 | ) |
815 | 776 | ] |
816 | | elif obj.list_display_links and field_name in obj.list_display_links: |
| 777 | if obj.list_display_links and field_name in obj.list_display_links: |
817 | 778 | return [ |
818 | 779 | checks.Error( |
819 | 780 | "The value of '%s' cannot be in both 'list_editable' and 'list_display_links'." % field_name, |
… |
… |
class ModelAdminChecks(BaseModelAdminChecks):
|
823 | 784 | ] |
824 | 785 | # If list_display[0] is in list_editable, check that |
825 | 786 | # list_display_links is set. See #22792 and #26229 for use cases. |
826 | | elif (obj.list_display[0] == field_name and not obj.list_display_links and |
| 787 | if (obj.list_display[0] == field_name and not obj.list_display_links and |
827 | 788 | obj.list_display_links is not None): |
828 | 789 | return [ |
829 | 790 | checks.Error( |
… |
… |
class ModelAdminChecks(BaseModelAdminChecks):
|
835 | 796 | id='admin.E124', |
836 | 797 | ) |
837 | 798 | ] |
838 | | elif not field.editable: |
| 799 | if not field.editable: |
839 | 800 | return [ |
840 | 801 | checks.Error( |
841 | 802 | "The value of '%s' refers to '%s', which is not editable through the admin." % ( |
… |
… |
class ModelAdminChecks(BaseModelAdminChecks):
|
845 | 806 | id='admin.E125', |
846 | 807 | ) |
847 | 808 | ] |
848 | | else: |
849 | | return [] |
| 809 | return [] |
850 | 810 | |
851 | 811 | def _check_search_fields(self, obj): |
852 | 812 | """ Check search_fields is a sequence. """ |
853 | 813 | |
854 | 814 | if not isinstance(obj.search_fields, (list, tuple)): |
855 | 815 | return must_be('a list or tuple', option='search_fields', obj=obj, id='admin.E126') |
856 | | else: |
857 | | return [] |
| 816 | return [] |
858 | 817 | |
859 | 818 | def _check_date_hierarchy(self, obj): |
860 | 819 | """ Check that date_hierarchy refers to DateField or DateTimeField. """ |
861 | 820 | |
862 | 821 | if obj.date_hierarchy is None: |
863 | 822 | return [] |
| 823 | try: |
| 824 | field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1] |
| 825 | except (NotRelationField, FieldDoesNotExist): |
| 826 | return [ |
| 827 | checks.Error( |
| 828 | "The value of 'date_hierarchy' refers to '%s', which " |
| 829 | "does not refer to a Field." % obj.date_hierarchy, |
| 830 | obj=obj.__class__, |
| 831 | id='admin.E127', |
| 832 | ) |
| 833 | ] |
864 | 834 | else: |
865 | | try: |
866 | | field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1] |
867 | | except (NotRelationField, FieldDoesNotExist): |
868 | | return [ |
869 | | checks.Error( |
870 | | "The value of 'date_hierarchy' refers to '%s', which " |
871 | | "does not refer to a Field." % obj.date_hierarchy, |
872 | | obj=obj.__class__, |
873 | | id='admin.E127', |
874 | | ) |
875 | | ] |
876 | | else: |
877 | | if not isinstance(field, (models.DateField, models.DateTimeField)): |
878 | | return must_be('a DateField or DateTimeField', option='date_hierarchy', obj=obj, id='admin.E128') |
879 | | else: |
880 | | return [] |
| 835 | if not isinstance(field, (models.DateField, models.DateTimeField)): |
| 836 | return must_be('a DateField or DateTimeField', option='date_hierarchy', obj=obj, id='admin.E128') |
| 837 | return [] |
881 | 838 | |
882 | 839 | |
883 | 840 | class InlineModelAdminChecks(BaseModelAdminChecks): |
… |
… |
class InlineModelAdminChecks(BaseModelAdminChecks):
|
919 | 876 | id='admin.E201', |
920 | 877 | ) |
921 | 878 | ] |
922 | | else: |
923 | | return [] |
| 879 | return [] |
924 | 880 | |
925 | 881 | def _check_relation(self, obj, parent_model): |
926 | 882 | try: |
… |
… |
class InlineModelAdminChecks(BaseModelAdminChecks):
|
935 | 891 | |
936 | 892 | if not isinstance(obj.extra, int): |
937 | 893 | return must_be('an integer', option='extra', obj=obj, id='admin.E203') |
938 | | else: |
939 | | return [] |
| 894 | return [] |
940 | 895 | |
941 | 896 | def _check_max_num(self, obj): |
942 | 897 | """ Check that max_num is an integer. """ |
943 | 898 | |
944 | 899 | if obj.max_num is None: |
945 | 900 | return [] |
946 | | elif not isinstance(obj.max_num, int): |
| 901 | if not isinstance(obj.max_num, int): |
947 | 902 | return must_be('an integer', option='max_num', obj=obj, id='admin.E204') |
948 | | else: |
949 | | return [] |
| 903 | return [] |
950 | 904 | |
951 | 905 | def _check_min_num(self, obj): |
952 | 906 | """ Check that min_num is an integer. """ |
953 | 907 | |
954 | 908 | if obj.min_num is None: |
955 | 909 | return [] |
956 | | elif not isinstance(obj.min_num, int): |
| 910 | if not isinstance(obj.min_num, int): |
957 | 911 | return must_be('an integer', option='min_num', obj=obj, id='admin.E205') |
958 | | else: |
959 | | return [] |
| 912 | return [] |
960 | 913 | |
961 | 914 | def _check_formset(self, obj): |
962 | 915 | """ Check formset is a subclass of BaseModelFormSet. """ |
963 | 916 | |
964 | 917 | if not issubclass(obj.formset, BaseModelFormSet): |
965 | 918 | return must_inherit_from(parent='BaseModelFormSet', option='formset', obj=obj, id='admin.E206') |
966 | | else: |
967 | | return [] |
| 919 | return [] |
968 | 920 | |
969 | 921 | |
970 | 922 | def must_be(type, option, obj, id): |
-
diff --git a/django/contrib/admin/models.py b/django/contrib/admin/models.py
index 2f8ecc8..893060a 100644
a
|
b
|
class LogEntry(models.Model):
|
68 | 68 | def __str__(self): |
69 | 69 | if self.is_addition(): |
70 | 70 | return gettext('Added "%(object)s".') % {'object': self.object_repr} |
71 | | elif self.is_change(): |
| 71 | if self.is_change(): |
72 | 72 | return gettext('Changed "%(object)s" - %(changes)s') % { |
73 | 73 | 'object': self.object_repr, |
74 | 74 | 'changes': self.get_change_message(), |
75 | 75 | } |
76 | | elif self.is_deletion(): |
| 76 | if self.is_deletion(): |
77 | 77 | return gettext('Deleted "%(object)s."') % {'object': self.object_repr} |
78 | 78 | |
79 | 79 | return gettext('LogEntry Object') |
-
diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py
index 627c76b..5a79bb2 100644
a
|
b
|
class ModelAdmin(BaseModelAdmin):
|
939 | 939 | def construct_search(field_name): |
940 | 940 | if field_name.startswith('^'): |
941 | 941 | return "%s__istartswith" % field_name[1:] |
942 | | elif field_name.startswith('='): |
| 942 | if field_name.startswith('='): |
943 | 943 | return "%s__iexact" % field_name[1:] |
944 | | elif field_name.startswith('@'): |
| 944 | if field_name.startswith('@'): |
945 | 945 | return "%s__search" % field_name[1:] |
946 | 946 | # Use field_name if it includes a lookup. |
947 | 947 | opts = queryset.model._meta |
-
diff --git a/django/contrib/admin/templatetags/admin_list.py b/django/contrib/admin/templatetags/admin_list.py
index 75b117f..a82bd15 100644
a
|
b
|
def paginator_number(cl, i):
|
31 | 31 | """ |
32 | 32 | if i == DOT: |
33 | 33 | return '... ' |
34 | | elif i == cl.page_num: |
| 34 | if i == cl.page_num: |
35 | 35 | return format_html('<span class="this-page">{}</span> ', i + 1) |
36 | | else: |
37 | | return format_html('<a href="{}"{}>{}</a> ', |
38 | | cl.get_query_string({PAGE_VAR: i}), |
39 | | mark_safe(' class="end"' if i == cl.paginator.num_pages - 1 else ''), |
40 | | i + 1) |
| 36 | return format_html('<a href="{}"{}>{}</a> ', |
| 37 | cl.get_query_string({PAGE_VAR: i}), |
| 38 | mark_safe(' class="end"' if i == cl.paginator.num_pages - 1 else ''), |
| 39 | i + 1) |
41 | 40 | |
42 | 41 | |
43 | 42 | @register.inclusion_tag('admin/pagination.html') |
-
diff --git a/django/contrib/admin/utils.py b/django/contrib/admin/utils.py
index f1e2d4e..2165d5a 100644
a
|
b
|
def display_for_field(value, field, empty_value_display):
|
393 | 393 | return dict(field.flatchoices).get(value, empty_value_display) |
394 | 394 | # NullBooleanField needs special-case null-handling, so it comes |
395 | 395 | # before the general null test. |
396 | | elif isinstance(field, (models.BooleanField, models.NullBooleanField)): |
| 396 | if isinstance(field, (models.BooleanField, models.NullBooleanField)): |
397 | 397 | return _boolean_icon(value) |
398 | | elif value is None: |
| 398 | if value is None: |
399 | 399 | return empty_value_display |
400 | | elif isinstance(field, models.DateTimeField): |
| 400 | if isinstance(field, models.DateTimeField): |
401 | 401 | return formats.localize(timezone.template_localtime(value)) |
402 | | elif isinstance(field, (models.DateField, models.TimeField)): |
| 402 | if isinstance(field, (models.DateField, models.TimeField)): |
403 | 403 | return formats.localize(value) |
404 | | elif isinstance(field, models.DecimalField): |
| 404 | if isinstance(field, models.DecimalField): |
405 | 405 | return formats.number_format(value, field.decimal_places) |
406 | | elif isinstance(field, (models.IntegerField, models.FloatField)): |
| 406 | if isinstance(field, (models.IntegerField, models.FloatField)): |
407 | 407 | return formats.number_format(value) |
408 | | elif isinstance(field, models.FileField) and value: |
| 408 | if isinstance(field, models.FileField) and value: |
409 | 409 | return format_html('<a href="{}">{}</a>', value.url, value) |
410 | | else: |
411 | | return display_for_value(value, empty_value_display) |
| 410 | return display_for_value(value, empty_value_display) |
412 | 411 | |
413 | 412 | |
414 | 413 | def display_for_value(value, empty_value_display, boolean=False): |
… |
… |
def display_for_value(value, empty_value_display, boolean=False):
|
416 | 415 | |
417 | 416 | if boolean: |
418 | 417 | return _boolean_icon(value) |
419 | | elif value is None: |
| 418 | if value is None: |
420 | 419 | return empty_value_display |
421 | | elif isinstance(value, datetime.datetime): |
| 420 | if isinstance(value, datetime.datetime): |
422 | 421 | return formats.localize(timezone.template_localtime(value)) |
423 | | elif isinstance(value, (datetime.date, datetime.time)): |
| 422 | if isinstance(value, (datetime.date, datetime.time)): |
424 | 423 | return formats.localize(value) |
425 | | elif isinstance(value, (int, decimal.Decimal, float)): |
| 424 | if isinstance(value, (int, decimal.Decimal, float)): |
426 | 425 | return formats.number_format(value) |
427 | | elif isinstance(value, (list, tuple)): |
| 426 | if isinstance(value, (list, tuple)): |
428 | 427 | return ', '.join(str(v) for v in value) |
429 | | else: |
430 | | return str(value) |
| 428 | return str(value) |
431 | 429 | |
432 | 430 | |
433 | 431 | class NotRelationField(Exception): |
… |
… |
class NotRelationField(Exception):
|
437 | 435 | def get_model_from_relation(field): |
438 | 436 | if hasattr(field, 'get_path_info'): |
439 | 437 | return field.get_path_info()[-1].to_opts.model |
440 | | else: |
441 | | raise NotRelationField |
| 438 | raise NotRelationField |
442 | 439 | |
443 | 440 | |
444 | 441 | def reverse_field_path(model, path): |
-
diff --git a/django/contrib/admindocs/views.py b/django/contrib/admindocs/views.py
index e45898c..504e7b4 100644
a
|
b
|
def get_return_data_type(func_name):
|
372 | 372 | if func_name.startswith('get_'): |
373 | 373 | if func_name.endswith('_list'): |
374 | 374 | return 'List' |
375 | | elif func_name.endswith('_count'): |
| 375 | if func_name.endswith('_count'): |
376 | 376 | return 'Integer' |
377 | 377 | return '' |
378 | 378 | |
-
diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py
index 18fca67..982f973 100644
a
|
b
|
class AuthenticationForm(forms.Form):
|
202 | 202 | else: |
203 | 203 | self.confirm_login_allowed(self.user_cache) |
204 | 204 | raise self.get_invalid_login_error() |
205 | | else: |
206 | | self.confirm_login_allowed(self.user_cache) |
| 205 | self.confirm_login_allowed(self.user_cache) |
207 | 206 | |
208 | 207 | return self.cleaned_data |
209 | 208 | |
-
diff --git a/django/contrib/auth/hashers.py b/django/contrib/auth/hashers.py
index c14ece2..ac8d061 100644
a
|
b
|
def get_hasher(algorithm='default'):
|
115 | 115 | if hasattr(algorithm, 'algorithm'): |
116 | 116 | return algorithm |
117 | 117 | |
118 | | elif algorithm == 'default': |
| 118 | if algorithm == 'default': |
119 | 119 | return get_hashers()[0] |
120 | 120 | |
121 | | else: |
122 | | hashers = get_hashers_by_algorithm() |
123 | | try: |
124 | | return hashers[algorithm] |
125 | | except KeyError: |
126 | | raise ValueError("Unknown password hashing algorithm '%s'. " |
127 | | "Did you specify it in the PASSWORD_HASHERS " |
128 | | "setting?" % algorithm) |
| 121 | hashers = get_hashers_by_algorithm() |
| 122 | try: |
| 123 | return hashers[algorithm] |
| 124 | except KeyError: |
| 125 | raise ValueError("Unknown password hashing algorithm '%s'. " |
| 126 | "Did you specify it in the PASSWORD_HASHERS " |
| 127 | "setting?" % algorithm) |
129 | 128 | |
130 | 129 | |
131 | 130 | def identify_hasher(encoded): |
-
diff --git a/django/contrib/contenttypes/fields.py b/django/contrib/contenttypes/fields.py
index 2227707..650bb12 100644
a
|
b
|
class GenericForeignKey(FieldCacheMixin):
|
138 | 138 | id='contenttypes.E003', |
139 | 139 | ) |
140 | 140 | ] |
141 | | elif field.remote_field.model != ContentType: |
| 141 | if field.remote_field.model != ContentType: |
142 | 142 | return [ |
143 | 143 | checks.Error( |
144 | 144 | "'%s.%s' is not a ForeignKey to 'contenttypes.ContentType'." % ( |
… |
… |
class GenericForeignKey(FieldCacheMixin):
|
152 | 152 | id='contenttypes.E004', |
153 | 153 | ) |
154 | 154 | ] |
155 | | else: |
156 | | return [] |
| 155 | return [] |
157 | 156 | |
158 | 157 | def get_cache_name(self): |
159 | 158 | return self.name |
… |
… |
class GenericForeignKey(FieldCacheMixin):
|
162 | 161 | if obj is not None: |
163 | 162 | return ContentType.objects.db_manager(obj._state.db).get_for_model( |
164 | 163 | obj, for_concrete_model=self.for_concrete_model) |
165 | | elif id is not None: |
| 164 | if id is not None: |
166 | 165 | return ContentType.objects.db_manager(using).get_for_id(id) |
167 | | else: |
168 | | # This should never happen. I love comments like this, don't you? |
169 | | raise Exception("Impossible arguments to GFK.get_content_type!") |
| 166 | # This should never happen. I love comments like this, don't you? |
| 167 | raise Exception("Impossible arguments to GFK.get_content_type!") |
170 | 168 | |
171 | 169 | def get_prefetch_queryset(self, instances, queryset=None): |
172 | 170 | if queryset is not None: |
-
diff --git a/django/contrib/gis/db/backends/base/models.py b/django/contrib/gis/db/backends/base/models.py
index c25c1cc..50ecd97 100644
a
|
b
|
class SpatialRefSysMixin:
|
96 | 96 | "Return a tuple of the units and the name." |
97 | 97 | if self.projected or self.local: |
98 | 98 | return (self.linear_units, self.linear_name) |
99 | | elif self.geographic: |
| 99 | if self.geographic: |
100 | 100 | return (self.angular_units, self.angular_name) |
101 | | else: |
102 | | return (None, None) |
| 101 | return (None, None) |
103 | 102 | |
104 | 103 | @classmethod |
105 | 104 | def get_units(cls, wkt): |
-
diff --git a/django/contrib/gis/db/backends/base/operations.py b/django/contrib/gis/db/backends/base/operations.py
index 1b786f7..3109f73 100644
a
|
b
|
class BaseSpatialOperations:
|
98 | 98 | self.spatial_function_name('Transform'), |
99 | 99 | self.from_text, value.srid, f.srid, |
100 | 100 | ) |
101 | | elif self.connection.features.has_spatialrefsys_table: |
| 101 | if self.connection.features.has_spatialrefsys_table: |
102 | 102 | return '%s(%%s,%s)' % (self.from_text, f.srid) |
103 | | else: |
104 | | # For backwards compatibility on MySQL (#27464). |
105 | | return '%s(%%s)' % self.from_text |
| 103 | # For backwards compatibility on MySQL (#27464). |
| 104 | return '%s(%%s)' % self.from_text |
106 | 105 | |
107 | 106 | def check_expression_support(self, expression): |
108 | 107 | if isinstance(expression, self.disallowed_aggregates): |
… |
… |
class BaseSpatialOperations:
|
145 | 144 | if self.connection.features.supports_area_geodetic: |
146 | 145 | return 'sq_m' |
147 | 146 | raise NotImplementedError('Area on geodetic coordinate systems not supported.') |
148 | | else: |
149 | | units_name = field.units_name(self.connection) |
150 | | if units_name: |
151 | | return AreaMeasure.unit_attname(units_name) |
| 147 | units_name = field.units_name(self.connection) |
| 148 | if units_name: |
| 149 | return AreaMeasure.unit_attname(units_name) |
152 | 150 | |
153 | 151 | def get_distance_att_for_field(self, field): |
154 | 152 | dist_att = None |
-
diff --git a/django/contrib/gis/db/models/lookups.py b/django/contrib/gis/db/models/lookups.py
index d531856..e649a6b 100644
a
|
b
|
class DistanceLookupBase(GISLookup):
|
283 | 283 | def process_rhs_params(self): |
284 | 284 | if not 1 <= len(self.rhs_params) <= 3: |
285 | 285 | raise ValueError("2, 3, or 4-element tuple required for '%s' lookup." % self.lookup_name) |
286 | | elif len(self.rhs_params) == 3 and self.rhs_params[2] != 'spheroid': |
| 286 | if len(self.rhs_params) == 3 and self.rhs_params[2] != 'spheroid': |
287 | 287 | raise ValueError("For 4-element tuples the last argument must be the 'spheroid' directive.") |
288 | 288 | |
289 | 289 | # Check if the second parameter is a band index. |
-
diff --git a/django/contrib/gis/gdal/envelope.py b/django/contrib/gis/gdal/envelope.py
index bbcc5d0..0d3e040 100644
a
|
b
|
class Envelope:
|
48 | 48 | # A tuple was passed in. |
49 | 49 | if len(args[0]) != 4: |
50 | 50 | raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0])) |
51 | | else: |
52 | | self._from_sequence(args[0]) |
| 51 | self._from_sequence(args[0]) |
53 | 52 | else: |
54 | 53 | raise TypeError('Incorrect type of argument: %s' % type(args[0])) |
55 | 54 | elif len(args) == 4: |
… |
… |
class Envelope:
|
73 | 72 | if isinstance(other, Envelope): |
74 | 73 | return (self.min_x == other.min_x) and (self.min_y == other.min_y) and \ |
75 | 74 | (self.max_x == other.max_x) and (self.max_y == other.max_y) |
76 | | elif isinstance(other, tuple) and len(other) == 4: |
| 75 | if isinstance(other, tuple) and len(other) == 4: |
77 | 76 | return (self.min_x == other[0]) and (self.min_y == other[1]) and \ |
78 | 77 | (self.max_x == other[2]) and (self.max_y == other[3]) |
79 | | else: |
80 | | raise GDALException('Equivalence testing only works with other Envelopes.') |
| 78 | raise GDALException('Equivalence testing only works with other Envelopes.') |
81 | 79 | |
82 | 80 | def __str__(self): |
83 | 81 | "Return a string representation of the tuple." |
… |
… |
class Envelope:
|
104 | 102 | if len(args) == 1: |
105 | 103 | if isinstance(args[0], Envelope): |
106 | 104 | return self.expand_to_include(args[0].tuple) |
107 | | elif hasattr(args[0], 'x') and hasattr(args[0], 'y'): |
| 105 | if hasattr(args[0], 'x') and hasattr(args[0], 'y'): |
108 | 106 | return self.expand_to_include(args[0].x, args[0].y, args[0].x, args[0].y) |
109 | | elif isinstance(args[0], (tuple, list)): |
| 107 | if isinstance(args[0], (tuple, list)): |
110 | 108 | # A tuple was passed in. |
111 | 109 | if len(args[0]) == 2: |
112 | 110 | return self.expand_to_include((args[0][0], args[0][1], args[0][0], args[0][1])) |
113 | | elif len(args[0]) == 4: |
| 111 | if len(args[0]) == 4: |
114 | 112 | (minx, miny, maxx, maxy) = args[0] |
115 | 113 | if minx < self._envelope.MinX: |
116 | 114 | self._envelope.MinX = minx |
… |
… |
class Envelope:
|
126 | 124 | raise TypeError('Incorrect type of argument: %s' % type(args[0])) |
127 | 125 | elif len(args) == 2: |
128 | 126 | # An x and an y parameter were passed in |
129 | | return self.expand_to_include((args[0], args[1], args[0], args[1])) |
| 127 | return self.expand_to_include((args[0], args[1], args[0], args[1])) |
130 | 128 | elif len(args) == 4: |
131 | 129 | # Individual parameters passed in. |
132 | 130 | return self.expand_to_include(args) |
-
diff --git a/django/contrib/gis/gdal/error.py b/django/contrib/gis/gdal/error.py
index e394b60..353629a 100644
a
|
b
|
def check_err(code, cpl=False):
|
54 | 54 | |
55 | 55 | if code == ERR_NONE: |
56 | 56 | return |
57 | | elif code in err_dict: |
| 57 | if code in err_dict: |
58 | 58 | e, msg = err_dict[code] |
59 | 59 | raise e(msg) |
60 | | else: |
61 | | raise GDALException('Unknown error code: "%s"' % code) |
| 60 | raise GDALException('Unknown error code: "%s"' % code) |
-
diff --git a/django/contrib/gis/gdal/geometries.py b/django/contrib/gis/gdal/geometries.py
index 42fbeec..3933f12 100644
a
|
b
|
class Point(OGRGeometry):
|
541 | 541 | "Return the tuple of this point." |
542 | 542 | if self.coord_dim == 2: |
543 | 543 | return (self.x, self.y) |
544 | | elif self.coord_dim == 3: |
| 544 | if self.coord_dim == 3: |
545 | 545 | return (self.x, self.y, self.z) |
546 | 546 | coords = tuple |
547 | 547 | |
… |
… |
class LineString(OGRGeometry):
|
556 | 556 | dim = self.coord_dim |
557 | 557 | if dim == 1: |
558 | 558 | return (x.value,) |
559 | | elif dim == 2: |
| 559 | if dim == 2: |
560 | 560 | return (x.value, y.value) |
561 | | elif dim == 3: |
| 561 | if dim == 3: |
562 | 562 | return (x.value, y.value, z.value) |
563 | 563 | else: |
564 | 564 | raise IndexError('Index out of range when accessing points of a line string: %s.' % index) |
-
diff --git a/django/contrib/gis/gdal/geomtype.py b/django/contrib/gis/gdal/geomtype.py
index 2c6798a..3062960 100644
a
|
b
|
class OGRGeomType:
|
61 | 61 | """ |
62 | 62 | if isinstance(other, OGRGeomType): |
63 | 63 | return self.num == other.num |
64 | | elif isinstance(other, str): |
| 64 | if isinstance(other, str): |
65 | 65 | return self.name.lower() == other.lower() |
66 | | elif isinstance(other, int): |
| 66 | if isinstance(other, int): |
67 | 67 | return self.num == other |
68 | | else: |
69 | | return False |
| 68 | return False |
70 | 69 | |
71 | 70 | @property |
72 | 71 | def name(self): |
-
diff --git a/django/contrib/gis/gdal/srs.py b/django/contrib/gis/gdal/srs.py
index b2e0b09..86bf755 100644
a
|
b
|
class SpatialReference(GDALBase):
|
82 | 82 | # If the pointer is NULL, throw an exception. |
83 | 83 | if not srs: |
84 | 84 | raise SRSException('Could not create spatial reference from: %s' % srs_input) |
85 | | else: |
86 | | self.ptr = srs |
| 85 | self.ptr = srs |
87 | 86 | |
88 | 87 | # Importing from either the user input string or an integer SRID. |
89 | 88 | if srs_type == 'user': |
… |
… |
class SpatialReference(GDALBase):
|
170 | 169 | "Return the name of this Spatial Reference." |
171 | 170 | if self.projected: |
172 | 171 | return self.attr_value('PROJCS') |
173 | | elif self.geographic: |
| 172 | if self.geographic: |
174 | 173 | return self.attr_value('GEOGCS') |
175 | | elif self.local: |
| 174 | if self.local: |
176 | 175 | return self.attr_value('LOCAL_CS') |
177 | | else: |
178 | | return None |
| 176 | return None |
179 | 177 | |
180 | 178 | @property |
181 | 179 | def srid(self): |
-
diff --git a/django/contrib/gis/geoip2/base.py b/django/contrib/gis/geoip2/base.py
index b1035ac..620b542 100644
a
|
b
|
class GeoIP2:
|
115 | 115 | |
116 | 116 | @property |
117 | 117 | def _reader(self): |
118 | | if self._country: |
119 | | return self._country |
120 | | else: |
121 | | return self._city |
| 118 | return self._country or self._city |
122 | 119 | |
123 | 120 | @property |
124 | 121 | def _country_or_city(self): |
125 | 122 | if self._country: |
126 | 123 | return self._country.country |
127 | | else: |
128 | | return self._city.city |
| 124 | return self._city.city |
129 | 125 | |
130 | 126 | def __del__(self): |
131 | 127 | # Cleanup any GeoIP file handles lying around. |
… |
… |
class GeoIP2:
|
151 | 147 | # Extra checks for the existence of country and city databases. |
152 | 148 | if city_or_country and not (self._country or self._city): |
153 | 149 | raise GeoIP2Exception('Invalid GeoIP country and city data files.') |
154 | | elif country and not self._country: |
| 150 | if country and not self._country: |
155 | 151 | raise GeoIP2Exception('Invalid GeoIP country data file: %s' % self._country_file) |
156 | | elif city and not self._city: |
| 152 | if city and not self._city: |
157 | 153 | raise GeoIP2Exception('Invalid GeoIP city data file: %s' % self._city_file) |
158 | 154 | |
159 | 155 | # Return the query string back to the caller. GeoIP2 only takes IP addresses. |
-
diff --git a/django/contrib/gis/geos/mutable_list.py b/django/contrib/gis/geos/mutable_list.py
index 90fcc6d..43ff3a9 100644
a
|
b
|
class ListMixin:
|
160 | 160 | return True |
161 | 161 | if c: |
162 | 162 | return c |
163 | | elif other[i] < self[i]: |
| 163 | if other[i] < self[i]: |
164 | 164 | return False |
165 | 165 | return len(self) < olen |
166 | 166 | |
-
diff --git a/django/contrib/gis/geos/point.py b/django/contrib/gis/geos/point.py
index ccf5b9d..eaf7bb6 100644
a
|
b
|
class Point(GEOSGeometry):
|
91 | 91 | return 0 |
92 | 92 | if self.hasz: |
93 | 93 | return 3 |
94 | | else: |
95 | | return 2 |
| 94 | return 2 |
96 | 95 | |
97 | 96 | def _get_single_external(self, index): |
98 | 97 | if index == 0: |
99 | 98 | return self.x |
100 | | elif index == 1: |
| 99 | if index == 1: |
101 | 100 | return self.y |
102 | | elif index == 2: |
| 101 | if index == 2: |
103 | 102 | return self.z |
104 | 103 | |
105 | 104 | _get_single_internal = _get_single_external |
-
diff --git a/django/contrib/gis/geos/prototypes/errcheck.py b/django/contrib/gis/geos/prototypes/errcheck.py
index 7d5f842..b2dac46 100644
a
|
b
|
def check_predicate(result, func, cargs):
|
45 | 45 | "Error checking for unary/binary predicate functions." |
46 | 46 | if result == 1: |
47 | 47 | return True |
48 | | elif result == 0: |
| 48 | if result == 0: |
49 | 49 | return False |
50 | | else: |
51 | | raise GEOSException('Error encountered on GEOS C predicate function "%s".' % func.__name__) |
| 50 | raise GEOSException('Error encountered on GEOS C predicate function "%s".' % func.__name__) |
52 | 51 | |
53 | 52 | |
54 | 53 | def check_sized_string(result, func, cargs): |
-
diff --git a/django/contrib/gis/geos/prototypes/io.py b/django/contrib/gis/geos/prototypes/io.py
index 97f49c2..a2c1772 100644
a
|
b
|
class _WKBReader(IOBase):
|
147 | 147 | if isinstance(wkb, memoryview): |
148 | 148 | wkb_s = bytes(wkb) |
149 | 149 | return wkb_reader_read(self.ptr, wkb_s, len(wkb_s)) |
150 | | elif isinstance(wkb, (bytes, str)): |
| 150 | if isinstance(wkb, (bytes, str)): |
151 | 151 | return wkb_reader_read_hex(self.ptr, wkb, len(wkb)) |
152 | | else: |
153 | | raise TypeError |
| 152 | raise TypeError |
154 | 153 | |
155 | 154 | |
156 | 155 | # ### WKB/WKT Writer Classes ### |
-
diff --git a/django/contrib/gis/measure.py b/django/contrib/gis/measure.py
index 3bb23d9..1d0eb64 100644
a
|
b
|
class MeasureBase:
|
209 | 209 | lower = unit_str.lower() |
210 | 210 | if unit_str in cls.UNITS: |
211 | 211 | return unit_str |
212 | | elif lower in cls.UNITS: |
| 212 | if lower in cls.UNITS: |
213 | 213 | return lower |
214 | | elif lower in cls.LALIAS: |
| 214 | if lower in cls.LALIAS: |
215 | 215 | return cls.LALIAS[lower] |
216 | | else: |
217 | | raise Exception('Could not find a unit keyword associated with "%s"' % unit_str) |
| 216 | raise Exception('Could not find a unit keyword associated with "%s"' % unit_str) |
218 | 217 | |
219 | 218 | |
220 | 219 | class Distance(MeasureBase): |
… |
… |
class Distance(MeasureBase):
|
300 | 299 | default_unit=AREA_PREFIX + self._default_unit, |
301 | 300 | **{AREA_PREFIX + self.STANDARD_UNIT: (self.standard * other.standard)} |
302 | 301 | ) |
303 | | elif isinstance(other, NUMERIC_TYPES): |
| 302 | if isinstance(other, NUMERIC_TYPES): |
304 | 303 | return self.__class__( |
305 | 304 | default_unit=self._default_unit, |
306 | 305 | **{self.STANDARD_UNIT: (self.standard * other)} |
307 | 306 | ) |
308 | | else: |
309 | | raise TypeError('%(distance)s must be multiplied with number or %(distance)s' % { |
310 | | "distance": pretty_name(self.__class__), |
311 | | }) |
| 307 | raise TypeError('%(distance)s must be multiplied with number or %(distance)s' % { |
| 308 | "distance": pretty_name(self.__class__), |
| 309 | }) |
312 | 310 | |
313 | 311 | |
314 | 312 | class Area(MeasureBase): |
-
diff --git a/django/contrib/gis/utils/layermapping.py b/django/contrib/gis/utils/layermapping.py
index e4baf56..5c6fcca 100644
a
|
b
|
class LayerMapping:
|
154 | 154 | if fid_range: |
155 | 155 | if isinstance(fid_range, (tuple, list)): |
156 | 156 | return slice(*fid_range) |
157 | | elif isinstance(fid_range, slice): |
| 157 | if isinstance(fid_range, slice): |
158 | 158 | return fid_range |
159 | | else: |
160 | | raise TypeError |
161 | | else: |
162 | | return None |
| 159 | raise TypeError |
| 160 | return None |
163 | 161 | |
164 | 162 | def check_layer(self): |
165 | 163 | """ |
-
diff --git a/django/contrib/gis/utils/ogrinspect.py b/django/contrib/gis/utils/ogrinspect.py
index 9a09160..d183e8e 100644
a
|
b
|
def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=Non
|
144 | 144 | def process_kwarg(kwarg): |
145 | 145 | if isinstance(kwarg, (list, tuple)): |
146 | 146 | return [s.lower() for s in kwarg] |
147 | | elif kwarg: |
| 147 | if kwarg: |
148 | 148 | return [s.lower() for s in ogr_fields] |
149 | | else: |
150 | | return [] |
| 149 | return [] |
151 | 150 | null_fields = process_kwarg(null) |
152 | 151 | blank_fields = process_kwarg(blank) |
153 | 152 | decimal_fields = process_kwarg(decimal) |
… |
… |
def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=Non
|
161 | 160 | kwlist.append('blank=True') |
162 | 161 | if kwlist: |
163 | 162 | return ', ' + ', '.join(kwlist) |
164 | | else: |
165 | | return '' |
| 163 | return '' |
166 | 164 | |
167 | 165 | # For those wishing to disable the imports. |
168 | 166 | if imports: |
-
diff --git a/django/contrib/humanize/templatetags/humanize.py b/django/contrib/humanize/templatetags/humanize.py
index fa644fd..844992e 100644
a
|
b
|
def naturalday(value, arg=None):
|
173 | 173 | delta = value - today |
174 | 174 | if delta.days == 0: |
175 | 175 | return _('today') |
176 | | elif delta.days == 1: |
| 176 | if delta.days == 1: |
177 | 177 | return _('tomorrow') |
178 | | elif delta.days == -1: |
| 178 | if delta.days == -1: |
179 | 179 | return _('yesterday') |
180 | 180 | return defaultfilters.date(value, arg) |
181 | 181 | |
… |
… |
def naturaltime(value):
|
198 | 198 | return pgettext( |
199 | 199 | 'naturaltime', '%(delta)s ago' |
200 | 200 | ) % {'delta': defaultfilters.timesince(value, now)} |
201 | | elif delta.seconds == 0: |
| 201 | if delta.seconds == 0: |
202 | 202 | return _('now') |
203 | | elif delta.seconds < 60: |
| 203 | if delta.seconds < 60: |
204 | 204 | return ngettext( |
205 | 205 | # Translators: please keep a non-breaking space (U+00A0) |
206 | 206 | # between count and time unit. |
207 | 207 | 'a second ago', '%(count)s seconds ago', delta.seconds |
208 | 208 | ) % {'count': delta.seconds} |
209 | | elif delta.seconds // 60 < 60: |
| 209 | if delta.seconds // 60 < 60: |
210 | 210 | count = delta.seconds // 60 |
211 | 211 | return ngettext( |
212 | 212 | # Translators: please keep a non-breaking space (U+00A0) |
213 | 213 | # between count and time unit. |
214 | 214 | 'a minute ago', '%(count)s minutes ago', count |
215 | 215 | ) % {'count': count} |
216 | | else: |
217 | | count = delta.seconds // 60 // 60 |
218 | | return ngettext( |
219 | | # Translators: please keep a non-breaking space (U+00A0) |
220 | | # between count and time unit. |
221 | | 'an hour ago', '%(count)s hours ago', count |
222 | | ) % {'count': count} |
223 | | else: |
224 | | delta = value - now |
225 | | if delta.days != 0: |
226 | | return pgettext( |
227 | | 'naturaltime', '%(delta)s from now' |
228 | | ) % {'delta': defaultfilters.timeuntil(value, now)} |
229 | | elif delta.seconds == 0: |
230 | | return _('now') |
231 | | elif delta.seconds < 60: |
232 | | return ngettext( |
233 | | # Translators: please keep a non-breaking space (U+00A0) |
234 | | # between count and time unit. |
235 | | 'a second from now', '%(count)s seconds from now', delta.seconds |
236 | | ) % {'count': delta.seconds} |
237 | | elif delta.seconds // 60 < 60: |
238 | | count = delta.seconds // 60 |
239 | | return ngettext( |
240 | | # Translators: please keep a non-breaking space (U+00A0) |
241 | | # between count and time unit. |
242 | | 'a minute from now', '%(count)s minutes from now', count |
243 | | ) % {'count': count} |
244 | | else: |
245 | | count = delta.seconds // 60 // 60 |
246 | | return ngettext( |
247 | | # Translators: please keep a non-breaking space (U+00A0) |
248 | | # between count and time unit. |
249 | | 'an hour from now', '%(count)s hours from now', count |
250 | | ) % {'count': count} |
| 216 | count = delta.seconds // 60 // 60 |
| 217 | return ngettext( |
| 218 | # Translators: please keep a non-breaking space (U+00A0) |
| 219 | # between count and time unit. |
| 220 | 'an hour ago', '%(count)s hours ago', count |
| 221 | ) % {'count': count} |
| 222 | delta = value - now |
| 223 | if delta.days != 0: |
| 224 | return pgettext( |
| 225 | 'naturaltime', '%(delta)s from now' |
| 226 | ) % {'delta': defaultfilters.timeuntil(value, now)} |
| 227 | if delta.seconds == 0: |
| 228 | return _('now') |
| 229 | if delta.seconds < 60: |
| 230 | return ngettext( |
| 231 | # Translators: please keep a non-breaking space (U+00A0) |
| 232 | # between count and time unit. |
| 233 | 'a second from now', '%(count)s seconds from now', delta.seconds |
| 234 | ) % {'count': delta.seconds} |
| 235 | if delta.seconds // 60 < 60: |
| 236 | count = delta.seconds // 60 |
| 237 | return ngettext( |
| 238 | # Translators: please keep a non-breaking space (U+00A0) |
| 239 | # between count and time unit. |
| 240 | 'a minute from now', '%(count)s minutes from now', count |
| 241 | ) % {'count': count} |
| 242 | count = delta.seconds // 60 // 60 |
| 243 | return ngettext( |
| 244 | # Translators: please keep a non-breaking space (U+00A0) |
| 245 | # between count and time unit. |
| 246 | 'an hour from now', '%(count)s hours from now', count |
| 247 | ) % {'count': count} |
-
diff --git a/django/contrib/postgres/fields/ranges.py b/django/contrib/postgres/fields/ranges.py
index 0bb914d..3f0f1fb 100644
a
|
b
|
class RangeField(models.Field):
|
38 | 38 | def get_prep_value(self, value): |
39 | 39 | if value is None: |
40 | 40 | return None |
41 | | elif isinstance(value, Range): |
| 41 | if isinstance(value, Range): |
42 | 42 | return value |
43 | | elif isinstance(value, (list, tuple)): |
| 43 | if isinstance(value, (list, tuple)): |
44 | 44 | return self.range_type(value[0], value[1]) |
45 | 45 | return value |
46 | 46 | |
-
diff --git a/django/contrib/postgres/forms/jsonb.py b/django/contrib/postgres/forms/jsonb.py
index bb681e0..6418f26 100644
a
|
b
|
class JSONField(forms.CharField):
|
25 | 25 | return value |
26 | 26 | if value in self.empty_values: |
27 | 27 | return None |
28 | | elif isinstance(value, (list, dict, int, float, JSONString)): |
| 28 | if isinstance(value, (list, dict, int, float, JSONString)): |
29 | 29 | return value |
30 | 30 | try: |
31 | 31 | converted = json.loads(value) |
… |
… |
class JSONField(forms.CharField):
|
37 | 37 | ) |
38 | 38 | if isinstance(converted, str): |
39 | 39 | return JSONString(converted) |
40 | | else: |
41 | | return converted |
| 40 | return converted |
42 | 41 | |
43 | 42 | def bound_data(self, data, initial): |
44 | 43 | if self.disabled: |
-
diff --git a/django/contrib/sessions/backends/base.py b/django/contrib/sessions/backends/base.py
index 64955b8..e644919 100644
a
|
b
|
class SessionBase:
|
103 | 103 | # could produce ValueError if there is no ':' |
104 | 104 | hash, serialized = encoded_data.split(b':', 1) |
105 | 105 | expected_hash = self._hash(serialized) |
106 | | if not constant_time_compare(hash.decode(), expected_hash): |
107 | | raise SuspiciousSession("Session data corrupted") |
108 | | else: |
| 106 | if constant_time_compare(hash.decode(), expected_hash): |
109 | 107 | return self.serializer().loads(serialized) |
| 108 | raise SuspiciousSession("Session data corrupted") |
110 | 109 | except Exception as e: |
111 | 110 | # ValueError, SuspiciousOperation, unpickling exceptions. If any of |
112 | 111 | # these happen, just return an empty dictionary (an empty session). |
-
diff --git a/django/contrib/sites/models.py b/django/contrib/sites/models.py
index 19f52e4..f67167d 100644
a
|
b
|
class SiteManager(models.Manager):
|
58 | 58 | if getattr(settings, 'SITE_ID', ''): |
59 | 59 | site_id = settings.SITE_ID |
60 | 60 | return self._get_site_by_id(site_id) |
61 | | elif request: |
| 61 | if request: |
62 | 62 | return self._get_site_by_request(request) |
63 | 63 | |
64 | 64 | raise ImproperlyConfigured( |
-
diff --git a/django/core/checks/registry.py b/django/core/checks/registry.py
index c580c80..8c73965 100644
a
|
b
|
class CheckRegistry:
|
50 | 50 | |
51 | 51 | if callable(check): |
52 | 52 | return inner(check) |
53 | | else: |
54 | | if check: |
55 | | tags += (check, ) |
56 | | return inner |
| 53 | if check: |
| 54 | tags += (check, ) |
| 55 | return inner |
57 | 56 | |
58 | 57 | def run_checks(self, app_configs=None, tags=None, include_deployment_checks=False): |
59 | 58 | """ |
-
diff --git a/django/core/checks/urls.py b/django/core/checks/urls.py
index e51ca3f..5cf566b 100644
a
|
b
|
def check_resolver(resolver):
|
21 | 21 | check_method = getattr(resolver, 'check', None) |
22 | 22 | if check_method is not None: |
23 | 23 | return check_method() |
24 | | elif not hasattr(resolver, 'resolve'): |
| 24 | if not hasattr(resolver, 'resolve'): |
25 | 25 | return get_warning_for_invalid_pattern(resolver) |
26 | | else: |
27 | | return [] |
| 26 | return [] |
28 | 27 | |
29 | 28 | |
30 | 29 | @register(Tags.urls) |
-
diff --git a/django/core/management/base.py b/django/core/management/base.py
index 41b6b0f..a2b34b2 100644
a
|
b
|
class BaseCommand:
|
408 | 408 | if any(e.is_serious(fail_level) and not e.is_silenced() for e in all_issues): |
409 | 409 | msg = self.style.ERROR("SystemCheckError: %s" % header) + body + footer |
410 | 410 | raise SystemCheckError(msg) |
411 | | else: |
412 | | msg = header + body + footer |
| 411 | msg = header + body + footer |
413 | 412 | |
414 | 413 | if msg: |
415 | 414 | if visible_issue_count: |
-
diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py
index 5d35440..4a42d40 100644
a
|
b
|
class DjangoJSONEncoder(json.JSONEncoder):
|
87 | 87 | if r.endswith('+00:00'): |
88 | 88 | r = r[:-6] + 'Z' |
89 | 89 | return r |
90 | | elif isinstance(o, datetime.date): |
| 90 | if isinstance(o, datetime.date): |
91 | 91 | return o.isoformat() |
92 | | elif isinstance(o, datetime.time): |
| 92 | if isinstance(o, datetime.time): |
93 | 93 | if is_aware(o): |
94 | 94 | raise ValueError("JSON can't represent timezone-aware times.") |
95 | 95 | r = o.isoformat() |
96 | 96 | if o.microsecond: |
97 | 97 | r = r[:12] |
98 | 98 | return r |
99 | | elif isinstance(o, datetime.timedelta): |
| 99 | if isinstance(o, datetime.timedelta): |
100 | 100 | return duration_iso_string(o) |
101 | | elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)): |
| 101 | if isinstance(o, (decimal.Decimal, uuid.UUID, Promise)): |
102 | 102 | return str(o) |
103 | | else: |
104 | | return super().default(o) |
| 103 | return super().default(o) |
-
diff --git a/django/db/backends/base/base.py b/django/db/backends/base/base.py
index 53c3c30..a0a7eb6 100644
a
|
b
|
class BaseDatabaseWrapper:
|
125 | 125 | """ |
126 | 126 | if not settings.USE_TZ: |
127 | 127 | return None |
128 | | elif self.features.supports_timezones: |
| 128 | if self.features.supports_timezones: |
129 | 129 | return None |
130 | | elif self.settings_dict['TIME_ZONE'] is None: |
| 130 | if self.settings_dict['TIME_ZONE'] is None: |
131 | 131 | return timezone.utc |
132 | | else: |
133 | | return pytz.timezone(self.settings_dict['TIME_ZONE']) |
| 132 | return pytz.timezone(self.settings_dict['TIME_ZONE']) |
134 | 133 | |
135 | 134 | @cached_property |
136 | 135 | def timezone_name(self): |
… |
… |
class BaseDatabaseWrapper:
|
139 | 138 | """ |
140 | 139 | if not settings.USE_TZ: |
141 | 140 | return settings.TIME_ZONE |
142 | | elif self.settings_dict['TIME_ZONE'] is None: |
| 141 | if self.settings_dict['TIME_ZONE'] is None: |
143 | 142 | return 'UTC' |
144 | | else: |
145 | | return self.settings_dict['TIME_ZONE'] |
| 143 | return self.settings_dict['TIME_ZONE'] |
146 | 144 | |
147 | 145 | @property |
148 | 146 | def queries_logged(self): |
… |
… |
class BaseDatabaseWrapper:
|
204 | 202 | raise ImproperlyConfigured( |
205 | 203 | "Connection '%s' cannot set TIME_ZONE because USE_TZ is " |
206 | 204 | "False." % self.alias) |
207 | | elif self.features.supports_timezones: |
| 205 | if self.features.supports_timezones: |
208 | 206 | raise ImproperlyConfigured( |
209 | 207 | "Connection '%s' cannot set TIME_ZONE because its engine " |
210 | 208 | "handles time zones conversions natively." % self.alias) |
-
diff --git a/django/db/backends/base/operations.py b/django/db/backends/base/operations.py
index 6291e00..5576a14 100644
a
|
b
|
class BaseDatabaseOperations:
|
167 | 167 | """ |
168 | 168 | if fields: |
169 | 169 | raise NotSupportedError('DISTINCT ON fields is not supported by this database backend') |
170 | | else: |
171 | | return 'DISTINCT' |
| 170 | return 'DISTINCT' |
172 | 171 | |
173 | 172 | def fetch_returned_insert_id(self, cursor): |
174 | 173 | """ |
… |
… |
class BaseDatabaseOperations:
|
208 | 207 | offset = low_mark or 0 |
209 | 208 | if high_mark is not None: |
210 | 209 | return (high_mark - offset), offset |
211 | | elif offset: |
| 210 | if offset: |
212 | 211 | return self.connection.ops.no_limit_value(), offset |
213 | 212 | return None, offset |
214 | 213 | |
… |
… |
class BaseDatabaseOperations:
|
473 | 472 | """ |
474 | 473 | if isinstance(value, datetime.datetime): # must be before date |
475 | 474 | return self.adapt_datetimefield_value(value) |
476 | | elif isinstance(value, datetime.date): |
| 475 | if isinstance(value, datetime.date): |
477 | 476 | return self.adapt_datefield_value(value) |
478 | | elif isinstance(value, datetime.time): |
| 477 | if isinstance(value, datetime.time): |
479 | 478 | return self.adapt_timefield_value(value) |
480 | | elif isinstance(value, decimal.Decimal): |
| 479 | if isinstance(value, decimal.Decimal): |
481 | 480 | return self.adapt_decimalfield_value(value) |
482 | | else: |
483 | | return value |
| 481 | return value |
484 | 482 | |
485 | 483 | def adapt_datefield_value(self, value): |
486 | 484 | """ |
… |
… |
class BaseDatabaseOperations:
|
629 | 627 | if isinstance(start, int): |
630 | 628 | if start < 0: |
631 | 629 | return '%d %s' % (abs(start), self.PRECEDING) |
632 | | elif start == 0: |
| 630 | if start == 0: |
633 | 631 | return self.CURRENT_ROW |
634 | | elif start is None: |
| 632 | if start is None: |
635 | 633 | return self.UNBOUNDED_PRECEDING |
636 | 634 | raise ValueError("start argument must be a negative integer, zero, or None, but got '%s'." % start) |
637 | 635 | |
… |
… |
class BaseDatabaseOperations:
|
639 | 637 | if isinstance(end, int): |
640 | 638 | if end == 0: |
641 | 639 | return self.CURRENT_ROW |
642 | | elif end > 0: |
| 640 | if end > 0: |
643 | 641 | return '%d %s' % (end, self.FOLLOWING) |
644 | | elif end is None: |
| 642 | if end is None: |
645 | 643 | return self.UNBOUNDED_FOLLOWING |
646 | 644 | raise ValueError("end argument must be a positive integer, zero, or None, but got '%s'." % end) |
647 | 645 | |
-
diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py
index 35b82dc..12dd432 100644
a
|
b
|
class BaseDatabaseSchemaEditor:
|
487 | 487 | "db_type (are you using a badly-written custom field?)" % |
488 | 488 | (old_field, new_field), |
489 | 489 | ) |
490 | | elif old_type is None and new_type is None and ( |
| 490 | if old_type is None and new_type is None and ( |
491 | 491 | old_field.remote_field.through and new_field.remote_field.through and |
492 | 492 | old_field.remote_field.through._meta.auto_created and |
493 | 493 | new_field.remote_field.through._meta.auto_created): |
494 | 494 | return self._alter_many_to_many(model, old_field, new_field, strict) |
495 | | elif old_type is None and new_type is None and ( |
| 495 | if old_type is None and new_type is None and ( |
496 | 496 | old_field.remote_field.through and new_field.remote_field.through and |
497 | 497 | not old_field.remote_field.through._meta.auto_created and |
498 | 498 | not new_field.remote_field.through._meta.auto_created): |
499 | 499 | # Both sides have through models; this is a no-op. |
500 | 500 | return |
501 | | elif old_type is None or new_type is None: |
| 501 | if old_type is None or new_type is None: |
502 | 502 | raise ValueError( |
503 | 503 | "Cannot alter field %s into %s - they are not compatible types " |
504 | 504 | "(you cannot alter to or from M2M fields, or add or remove " |
-
diff --git a/django/db/backends/mysql/introspection.py b/django/db/backends/mysql/introspection.py
index 28dc47f..a945fa1 100644
a
|
b
|
class DatabaseIntrospection(BaseDatabaseIntrospection):
|
41 | 41 | if 'auto_increment' in description.extra: |
42 | 42 | if field_type == 'IntegerField': |
43 | 43 | return 'AutoField' |
44 | | elif field_type == 'BigIntegerField': |
| 44 | if field_type == 'BigIntegerField': |
45 | 45 | return 'BigAutoField' |
46 | 46 | if description.is_unsigned: |
47 | 47 | if field_type == 'IntegerField': |
48 | 48 | return 'PositiveIntegerField' |
49 | | elif field_type == 'SmallIntegerField': |
| 49 | if field_type == 'SmallIntegerField': |
50 | 50 | return 'PositiveSmallIntegerField' |
51 | 51 | return field_type |
52 | 52 | |
-
diff --git a/django/db/backends/mysql/operations.py b/django/db/backends/mysql/operations.py
index 711f18d..bab9fa0 100644
a
|
b
|
class DatabaseOperations(BaseDatabaseOperations):
|
49 | 49 | if lookup_type in fields: |
50 | 50 | format_str = fields[lookup_type] |
51 | 51 | return "CAST(DATE_FORMAT(%s, '%s') AS DATE)" % (field_name, format_str) |
52 | | elif lookup_type == 'quarter': |
| 52 | if lookup_type == 'quarter': |
53 | 53 | return "MAKEDATE(YEAR(%s), 1) + INTERVAL QUARTER(%s) QUARTER - INTERVAL 1 QUARTER" % ( |
54 | 54 | field_name, field_name |
55 | 55 | ) |
56 | | else: |
57 | | return "DATE(%s)" % (field_name) |
| 56 | return "DATE(%s)" % (field_name) |
58 | 57 | |
59 | 58 | def _convert_field_to_tz(self, field_name, tzname): |
60 | 59 | if settings.USE_TZ: |
… |
… |
class DatabaseOperations(BaseDatabaseOperations):
|
204 | 203 | return 'POW(%s)' % ','.join(sub_expressions) |
205 | 204 | # Convert the result to a signed integer since MySQL's binary operators |
206 | 205 | # return an unsigned integer. |
207 | | elif connector in ('&', '|', '<<'): |
| 206 | if connector in ('&', '|', '<<'): |
208 | 207 | return 'CONVERT(%s, SIGNED)' % connector.join(sub_expressions) |
209 | | elif connector == '>>': |
| 208 | if connector == '>>': |
210 | 209 | lhs, rhs = sub_expressions |
211 | 210 | return 'FLOOR(%(lhs)s / POW(2, %(rhs)s))' % {'lhs': lhs, 'rhs': rhs} |
212 | 211 | return super().combine_expression(connector, sub_expressions) |
-
diff --git a/django/db/backends/oracle/introspection.py b/django/db/backends/oracle/introspection.py
index dbd54c2..9dc9aa8 100644
a
|
b
|
class DatabaseIntrospection(BaseDatabaseIntrospection):
|
34 | 34 | if scale == 0: |
35 | 35 | if precision > 11: |
36 | 36 | return 'BigAutoField' if description.is_autofield else 'BigIntegerField' |
37 | | elif precision == 1: |
| 37 | if precision == 1: |
38 | 38 | return 'BooleanField' |
39 | | elif description.is_autofield: |
| 39 | if description.is_autofield: |
40 | 40 | return 'AutoField' |
41 | | else: |
42 | | return 'IntegerField' |
43 | | elif scale == -127: |
| 41 | return 'IntegerField' |
| 42 | if scale == -127: |
44 | 43 | return 'FloatField' |
45 | 44 | |
46 | 45 | return super().get_field_type(data_type, description) |
-
diff --git a/django/db/backends/oracle/operations.py b/django/db/backends/oracle/operations.py
index fa29a89..11955f8 100644
a
|
b
|
END;
|
62 | 62 | if lookup_type == 'week_day': |
63 | 63 | # TO_CHAR(field, 'D') returns an integer from 1-7, where 1=Sunday. |
64 | 64 | return "TO_CHAR(%s, 'D')" % field_name |
65 | | elif lookup_type == 'week': |
| 65 | if lookup_type == 'week': |
66 | 66 | # IW = ISO week number |
67 | 67 | return "TO_CHAR(%s, 'IW')" % field_name |
68 | | elif lookup_type == 'quarter': |
| 68 | if lookup_type == 'quarter': |
69 | 69 | return "TO_CHAR(%s, 'Q')" % field_name |
70 | | else: |
71 | | # https://docs.oracle.com/database/121/SQLRF/functions067.htm#SQLRF00639 |
72 | | return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name) |
| 70 | # https://docs.oracle.com/database/121/SQLRF/functions067.htm#SQLRF00639 |
| 71 | return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name) |
73 | 72 | |
74 | 73 | def date_interval_sql(self, timedelta): |
75 | 74 | """ |
… |
… |
END;
|
81 | 80 | # https://docs.oracle.com/database/121/SQLRF/functions271.htm#SQLRF52058 |
82 | 81 | if lookup_type in ('year', 'month'): |
83 | 82 | return "TRUNC(%s, '%s')" % (field_name, lookup_type.upper()) |
84 | | elif lookup_type == 'quarter': |
| 83 | if lookup_type == 'quarter': |
85 | 84 | return "TRUNC(%s, 'Q')" % field_name |
86 | | else: |
87 | | return "TRUNC(%s)" % field_name |
| 85 | return "TRUNC(%s)" % field_name |
88 | 86 | |
89 | 87 | # Oracle crashes with "ORA-03113: end-of-file on communication channel" |
90 | 88 | # if the time zone name is passed in parameter. Use interpolation instead. |
… |
… |
END;
|
505 | 503 | lhs, rhs = sub_expressions |
506 | 504 | if connector == '%%': |
507 | 505 | return 'MOD(%s)' % ','.join(sub_expressions) |
508 | | elif connector == '&': |
| 506 | if connector == '&': |
509 | 507 | return 'BITAND(%s)' % ','.join(sub_expressions) |
510 | | elif connector == '|': |
| 508 | if connector == '|': |
511 | 509 | return 'BITAND(-%(lhs)s-1,%(rhs)s)+%(lhs)s' % {'lhs': lhs, 'rhs': rhs} |
512 | | elif connector == '<<': |
| 510 | if connector == '<<': |
513 | 511 | return '(%(lhs)s * POWER(2, %(rhs)s))' % {'lhs': lhs, 'rhs': rhs} |
514 | | elif connector == '>>': |
| 512 | if connector == '>>': |
515 | 513 | return 'FLOOR(%(lhs)s / POWER(2, %(rhs)s))' % {'lhs': lhs, 'rhs': rhs} |
516 | | elif connector == '^': |
| 514 | if connector == '^': |
517 | 515 | return 'POWER(%s)' % ','.join(sub_expressions) |
518 | 516 | return super().combine_expression(connector, sub_expressions) |
519 | 517 | |
-
diff --git a/django/db/backends/oracle/schema.py b/django/db/backends/oracle/schema.py
index 39c3b7e..5ab14fb 100644
a
|
b
|
class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
|
20 | 20 | def quote_value(self, value): |
21 | 21 | if isinstance(value, (datetime.date, datetime.time, datetime.datetime)): |
22 | 22 | return "'%s'" % value |
23 | | elif isinstance(value, str): |
| 23 | if isinstance(value, str): |
24 | 24 | return "'%s'" % value.replace("\'", "\'\'") |
25 | | elif isinstance(value, (bytes, bytearray, memoryview)): |
| 25 | if isinstance(value, (bytes, bytearray, memoryview)): |
26 | 26 | return "'%s'" % value.hex() |
27 | | elif isinstance(value, bool): |
| 27 | if isinstance(value, bool): |
28 | 28 | return "1" if value else "0" |
29 | | else: |
30 | | return str(value) |
| 29 | return str(value) |
31 | 30 | |
32 | 31 | def remove_field(self, model, field): |
33 | 32 | # If the column is an identity column, drop the identity before |
-
diff --git a/django/db/backends/postgresql/introspection.py b/django/db/backends/postgresql/introspection.py
index 30f764f..08d9193 100644
a
|
b
|
class DatabaseIntrospection(BaseDatabaseIntrospection):
|
44 | 44 | if description.default and 'nextval' in description.default: |
45 | 45 | if field_type == 'IntegerField': |
46 | 46 | return 'AutoField' |
47 | | elif field_type == 'BigIntegerField': |
| 47 | if field_type == 'BigIntegerField': |
48 | 48 | return 'BigAutoField' |
49 | 49 | return field_type |
50 | 50 | |
-
diff --git a/django/db/backends/postgresql/schema.py b/django/db/backends/postgresql/schema.py
index f957cc3..6b33c14 100644
a
|
b
|
class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
|
50 | 50 | return None |
51 | 51 | if db_type.startswith('varchar'): |
52 | 52 | return self._create_index_sql(model, [field], suffix='_like', sql=self.sql_create_varchar_index) |
53 | | elif db_type.startswith('text'): |
| 53 | if db_type.startswith('text'): |
54 | 54 | return self._create_index_sql(model, [field], suffix='_like', sql=self.sql_create_text_index) |
55 | 55 | return None |
56 | 56 | |
-
diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py
index 13f9a57..c227eb1 100644
a
|
b
|
def _sqlite_date_extract(lookup_type, dt):
|
317 | 317 | return None |
318 | 318 | if lookup_type == 'week_day': |
319 | 319 | return (dt.isoweekday() % 7) + 1 |
320 | | elif lookup_type == 'week': |
| 320 | if lookup_type == 'week': |
321 | 321 | return dt.isocalendar()[1] |
322 | | elif lookup_type == 'quarter': |
| 322 | if lookup_type == 'quarter': |
323 | 323 | return math.ceil(dt.month / 3) |
324 | | else: |
325 | | return getattr(dt, lookup_type) |
| 324 | return getattr(dt, lookup_type) |
326 | 325 | |
327 | 326 | |
328 | 327 | def _sqlite_date_trunc(lookup_type, dt): |
… |
… |
def _sqlite_date_trunc(lookup_type, dt):
|
332 | 331 | return None |
333 | 332 | if lookup_type == 'year': |
334 | 333 | return "%i-01-01" % dt.year |
335 | | elif lookup_type == 'quarter': |
| 334 | if lookup_type == 'quarter': |
336 | 335 | month_in_quarter = dt.month - (dt.month - 1) % 3 |
337 | 336 | return '%i-%02i-01' % (dt.year, month_in_quarter) |
338 | | elif lookup_type == 'month': |
| 337 | if lookup_type == 'month': |
339 | 338 | return "%i-%02i-01" % (dt.year, dt.month) |
340 | | elif lookup_type == 'day': |
| 339 | if lookup_type == 'day': |
341 | 340 | return "%i-%02i-%02i" % (dt.year, dt.month, dt.day) |
342 | 341 | |
343 | 342 | |
… |
… |
def _sqlite_time_trunc(lookup_type, dt):
|
348 | 347 | return None |
349 | 348 | if lookup_type == 'hour': |
350 | 349 | return "%02i:00:00" % dt.hour |
351 | | elif lookup_type == 'minute': |
| 350 | if lookup_type == 'minute': |
352 | 351 | return "%02i:%02i:00" % (dt.hour, dt.minute) |
353 | | elif lookup_type == 'second': |
| 352 | if lookup_type == 'second': |
354 | 353 | return "%02i:%02i:%02i" % (dt.hour, dt.minute, dt.second) |
355 | 354 | |
356 | 355 | |
… |
… |
def _sqlite_datetime_extract(lookup_type, dt, tzname):
|
386 | 385 | return None |
387 | 386 | if lookup_type == 'week_day': |
388 | 387 | return (dt.isoweekday() % 7) + 1 |
389 | | elif lookup_type == 'week': |
| 388 | if lookup_type == 'week': |
390 | 389 | return dt.isocalendar()[1] |
391 | | elif lookup_type == 'quarter': |
| 390 | if lookup_type == 'quarter': |
392 | 391 | return math.ceil(dt.month / 3) |
393 | | else: |
394 | | return getattr(dt, lookup_type) |
| 392 | return getattr(dt, lookup_type) |
395 | 393 | |
396 | 394 | |
397 | 395 | def _sqlite_datetime_trunc(lookup_type, dt, tzname): |
… |
… |
def _sqlite_datetime_trunc(lookup_type, dt, tzname):
|
400 | 398 | return None |
401 | 399 | if lookup_type == 'year': |
402 | 400 | return "%i-01-01 00:00:00" % dt.year |
403 | | elif lookup_type == 'quarter': |
| 401 | if lookup_type == 'quarter': |
404 | 402 | month_in_quarter = dt.month - (dt.month - 1) % 3 |
405 | 403 | return '%i-%02i-01 00:00:00' % (dt.year, month_in_quarter) |
406 | | elif lookup_type == 'month': |
| 404 | if lookup_type == 'month': |
407 | 405 | return "%i-%02i-01 00:00:00" % (dt.year, dt.month) |
408 | | elif lookup_type == 'day': |
| 406 | if lookup_type == 'day': |
409 | 407 | return "%i-%02i-%02i 00:00:00" % (dt.year, dt.month, dt.day) |
410 | | elif lookup_type == 'hour': |
| 408 | if lookup_type == 'hour': |
411 | 409 | return "%i-%02i-%02i %02i:00:00" % (dt.year, dt.month, dt.day, dt.hour) |
412 | | elif lookup_type == 'minute': |
| 410 | if lookup_type == 'minute': |
413 | 411 | return "%i-%02i-%02i %02i:%02i:00" % (dt.year, dt.month, dt.day, dt.hour, dt.minute) |
414 | | elif lookup_type == 'second': |
| 412 | if lookup_type == 'second': |
415 | 413 | return "%i-%02i-%02i %02i:%02i:%02i" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second) |
416 | 414 | |
417 | 415 | |
-
diff --git a/django/db/backends/sqlite3/operations.py b/django/db/backends/sqlite3/operations.py
index f363da0..21668ce 100644
a
|
b
|
class DatabaseOperations(BaseDatabaseOperations):
|
25 | 25 | """ |
26 | 26 | if len(fields) == 1: |
27 | 27 | return 500 |
28 | | elif len(fields) > 1: |
| 28 | if fields: |
29 | 29 | return self.connection.features.max_query_params // len(fields) |
30 | | else: |
31 | | return len(objs) |
| 30 | return len(objs) |
32 | 31 | |
33 | 32 | def check_expression_support(self, expression): |
34 | 33 | bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField) |
-
diff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py
index 71f6c1c..1f9a164 100644
a
|
b
|
class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
|
39 | 39 | # Manual emulation of SQLite parameter quoting |
40 | 40 | if isinstance(value, bool): |
41 | 41 | return str(int(value)) |
42 | | elif isinstance(value, (Decimal, float, int)): |
| 42 | if isinstance(value, (Decimal, float, int)): |
43 | 43 | return str(value) |
44 | | elif isinstance(value, str): |
| 44 | if isinstance(value, str): |
45 | 45 | return "'%s'" % value.replace("\'", "\'\'") |
46 | | elif value is None: |
| 46 | if value is None: |
47 | 47 | return "NULL" |
48 | | elif isinstance(value, (bytes, bytearray, memoryview)): |
| 48 | if isinstance(value, (bytes, bytearray, memoryview)): |
49 | 49 | # Bytes are only allowed for BLOB fields, encoded as string |
50 | 50 | # literals containing hexadecimal data and preceded by a single "X" |
51 | 51 | # character. |
52 | 52 | return "X'%s'" % value.hex() |
53 | | else: |
54 | | raise ValueError("Cannot quote parameter value %r of type %s" % (value, type(value))) |
| 53 | raise ValueError("Cannot quote parameter value %r of type %s" % (value, type(value))) |
55 | 54 | |
56 | 55 | def _remake_table(self, model, create_field=None, delete_field=None, alter_field=None): |
57 | 56 | """ |
-
diff --git a/django/db/backends/utils.py b/django/db/backends/utils.py
index f4641e3..8ffc1a0 100644
a
|
b
|
class CursorWrapper:
|
58 | 58 | with self.db.wrap_database_errors: |
59 | 59 | if params is None and kparams is None: |
60 | 60 | return self.cursor.callproc(procname) |
61 | | elif kparams is None: |
| 61 | if kparams is None: |
62 | 62 | return self.cursor.callproc(procname, params) |
63 | | else: |
64 | | params = params or () |
65 | | return self.cursor.callproc(procname, params, kparams) |
| 63 | params = params or () |
| 64 | return self.cursor.callproc(procname, params, kparams) |
66 | 65 | |
67 | 66 | def execute(self, sql, params=None): |
68 | 67 | return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) |
-
diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py
index ece58b9..a7e5949 100644
a
|
b
|
class MigrationAutodetector:
|
55 | 55 | """ |
56 | 56 | if isinstance(obj, list): |
57 | 57 | return [self.deep_deconstruct(value) for value in obj] |
58 | | elif isinstance(obj, tuple): |
| 58 | if isinstance(obj, tuple): |
59 | 59 | return tuple(self.deep_deconstruct(value) for value in obj) |
60 | | elif isinstance(obj, dict): |
| 60 | if isinstance(obj, dict): |
61 | 61 | return { |
62 | 62 | key: self.deep_deconstruct(value) |
63 | 63 | for key, value in obj.items() |
64 | 64 | } |
65 | | elif isinstance(obj, functools.partial): |
| 65 | if isinstance(obj, functools.partial): |
66 | 66 | return (obj.func, self.deep_deconstruct(obj.args), self.deep_deconstruct(obj.keywords)) |
67 | | elif isinstance(obj, COMPILED_REGEX_TYPE): |
| 67 | if isinstance(obj, COMPILED_REGEX_TYPE): |
68 | 68 | return RegexObject(obj) |
69 | | elif isinstance(obj, type): |
| 69 | if isinstance(obj, type): |
70 | 70 | # If this is a type that implements 'deconstruct' as an instance method, |
71 | 71 | # avoid treating this as being deconstructible itself - see #22951 |
72 | 72 | return obj |
73 | | elif hasattr(obj, 'deconstruct'): |
| 73 | if hasattr(obj, 'deconstruct'): |
74 | 74 | deconstructed = obj.deconstruct() |
75 | 75 | if isinstance(obj, models.Field): |
76 | 76 | # we have a field which also returns a name |
… |
… |
class MigrationAutodetector:
|
84 | 84 | for key, value in kwargs.items() |
85 | 85 | }, |
86 | 86 | ) |
87 | | else: |
88 | | return obj |
| 87 | return obj |
89 | 88 | |
90 | 89 | def only_relation_agnostic_fields(self, fields): |
91 | 90 | """ |
… |
… |
class MigrationAutodetector:
|
370 | 369 | operation.name_lower == dependency[1].lower() |
371 | 370 | ) |
372 | 371 | # Created field |
373 | | elif dependency[2] is not None and dependency[3] is True: |
| 372 | if dependency[2] is not None and dependency[3] is True: |
374 | 373 | return ( |
375 | 374 | ( |
376 | 375 | isinstance(operation, operations.CreateModel) and |
… |
… |
class MigrationAutodetector:
|
384 | 383 | ) |
385 | 384 | ) |
386 | 385 | # Removed field |
387 | | elif dependency[2] is not None and dependency[3] is False: |
| 386 | if dependency[2] is not None and dependency[3] is False: |
388 | 387 | return ( |
389 | 388 | isinstance(operation, operations.RemoveField) and |
390 | 389 | operation.model_name_lower == dependency[1].lower() and |
391 | 390 | operation.name_lower == dependency[2].lower() |
392 | 391 | ) |
393 | 392 | # Removed model |
394 | | elif dependency[2] is None and dependency[3] is False: |
| 393 | if dependency[2] is None and dependency[3] is False: |
395 | 394 | return ( |
396 | 395 | isinstance(operation, operations.DeleteModel) and |
397 | 396 | operation.name_lower == dependency[1].lower() |
398 | 397 | ) |
399 | 398 | # Field being altered |
400 | | elif dependency[2] is not None and dependency[3] == "alter": |
| 399 | if dependency[2] is not None and dependency[3] == "alter": |
401 | 400 | return ( |
402 | 401 | isinstance(operation, operations.AlterField) and |
403 | 402 | operation.model_name_lower == dependency[1].lower() and |
404 | 403 | operation.name_lower == dependency[2].lower() |
405 | 404 | ) |
406 | 405 | # order_with_respect_to being unset for a field |
407 | | elif dependency[2] is not None and dependency[3] == "order_wrt_unset": |
| 406 | if dependency[2] is not None and dependency[3] == "order_wrt_unset": |
408 | 407 | return ( |
409 | 408 | isinstance(operation, operations.AlterOrderWithRespectTo) and |
410 | 409 | operation.name_lower == dependency[1].lower() and |
411 | 410 | (operation.order_with_respect_to or "").lower() != dependency[2].lower() |
412 | 411 | ) |
413 | 412 | # Field is removed and part of an index/unique_together |
414 | | elif dependency[2] is not None and dependency[3] == "foo_together_change": |
| 413 | if dependency[2] is not None and dependency[3] == "foo_together_change": |
415 | 414 | return ( |
416 | 415 | isinstance(operation, (operations.AlterUniqueTogether, |
417 | 416 | operations.AlterIndexTogether)) and |
418 | 417 | operation.name_lower == dependency[1].lower() |
419 | 418 | ) |
420 | 419 | # Unknown dependency. Raise an error. |
421 | | else: |
422 | | raise ValueError("Can't handle dependency %r" % (dependency, )) |
| 420 | raise ValueError("Can't handle dependency %r" % (dependency, )) |
423 | 421 | |
424 | 422 | def add_operation(self, app_label, operation, dependencies=None, beginning=False): |
425 | 423 | # Dependencies are (app_label, model_name, field_name, create/delete as True/False) |
… |
… |
class MigrationAutodetector:
|
1213 | 1211 | if len(ops) == 1: |
1214 | 1212 | if isinstance(ops[0], operations.CreateModel): |
1215 | 1213 | return ops[0].name_lower |
1216 | | elif isinstance(ops[0], operations.DeleteModel): |
| 1214 | if isinstance(ops[0], operations.DeleteModel): |
1217 | 1215 | return "delete_%s" % ops[0].name_lower |
1218 | | elif isinstance(ops[0], operations.AddField): |
| 1216 | if isinstance(ops[0], operations.AddField): |
1219 | 1217 | return "%s_%s" % (ops[0].model_name_lower, ops[0].name_lower) |
1220 | | elif isinstance(ops[0], operations.RemoveField): |
| 1218 | if isinstance(ops[0], operations.RemoveField): |
1221 | 1219 | return "remove_%s_%s" % (ops[0].model_name_lower, ops[0].name_lower) |
1222 | 1220 | elif len(ops) > 1: |
1223 | 1221 | if all(isinstance(o, operations.CreateModel) for o in ops): |
-
diff --git a/django/db/migrations/loader.py b/django/db/migrations/loader.py
index 8a1cf43..ae79777 100644
a
|
b
|
class MigrationLoader:
|
133 | 133 | raise AmbiguityError( |
134 | 134 | "There is more than one migration for '%s' with the prefix '%s'" % (app_label, name_prefix) |
135 | 135 | ) |
136 | | elif len(results) == 0: |
| 136 | if len(results) == 0: |
137 | 137 | raise KeyError("There no migrations for '%s' with the prefix '%s'" % (app_label, name_prefix)) |
138 | | else: |
139 | | return self.disk_migrations[results[0]] |
| 138 | return self.disk_migrations[results[0]] |
140 | 139 | |
141 | 140 | def check_key(self, key, current_app): |
142 | 141 | if (key[1] != "__first__" and key[1] != "__latest__") or key in self.graph: |
-
diff --git a/django/db/migrations/operations/base.py b/django/db/migrations/operations/base.py
index 6ecbfac..c5b2e63 100644
a
|
b
|
class Operation:
|
120 | 120 | """ |
121 | 121 | if self.elidable: |
122 | 122 | return [operation] |
123 | | elif operation.elidable: |
| 123 | if operation.elidable: |
124 | 124 | return [self] |
125 | 125 | return False |
126 | 126 | |
-
diff --git a/django/db/migrations/operations/fields.py b/django/db/migrations/operations/fields.py
index b2c552c..8bcbd72 100644
a
|
b
|
class AddField(FieldOperation):
|
103 | 103 | field=operation.field, |
104 | 104 | ), |
105 | 105 | ] |
106 | | elif isinstance(operation, RemoveField): |
| 106 | if isinstance(operation, RemoveField): |
107 | 107 | return [] |
108 | | elif isinstance(operation, RenameField): |
| 108 | if isinstance(operation, RenameField): |
109 | 109 | return [ |
110 | 110 | AddField( |
111 | 111 | model_name=self.model_name, |
… |
… |
class AlterField(FieldOperation):
|
221 | 221 | def reduce(self, operation, in_between, app_label=None): |
222 | 222 | if isinstance(operation, RemoveField) and self.is_same_field_operation(operation): |
223 | 223 | return [operation] |
224 | | elif isinstance(operation, RenameField) and self.is_same_field_operation(operation): |
| 224 | if isinstance(operation, RenameField) and self.is_same_field_operation(operation): |
225 | 225 | return [ |
226 | 226 | operation, |
227 | 227 | AlterField( |
-
diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py
index a1ff594..d56c0a5 100644
a
|
b
|
class CreateModel(ModelOperation):
|
128 | 128 | """ |
129 | 129 | if isinstance(model, str): |
130 | 130 | return model.split(".", 1) |
131 | | else: |
132 | | return model._meta.app_label, model._meta.object_name |
| 131 | return model._meta.app_label, model._meta.object_name |
133 | 132 | |
134 | 133 | def reduce(self, operation, in_between, app_label=None): |
135 | 134 | if (isinstance(operation, DeleteModel) and |
136 | 135 | self.name_lower == operation.name_lower and |
137 | 136 | not self.options.get("proxy", False)): |
138 | 137 | return [] |
139 | | elif isinstance(operation, RenameModel) and self.name_lower == operation.old_name_lower: |
| 138 | if isinstance(operation, RenameModel) and self.name_lower == operation.old_name_lower: |
140 | 139 | return [ |
141 | 140 | CreateModel( |
142 | 141 | operation.new_name, |
… |
… |
class CreateModel(ModelOperation):
|
146 | 145 | managers=self.managers, |
147 | 146 | ), |
148 | 147 | ] |
149 | | elif isinstance(operation, AlterModelOptions) and self.name_lower == operation.name_lower: |
| 148 | if isinstance(operation, AlterModelOptions) and self.name_lower == operation.name_lower: |
150 | 149 | new_options = self.options.copy() |
151 | 150 | new_options.update(operation.options) |
152 | 151 | return [ |
… |
… |
class CreateModel(ModelOperation):
|
158 | 157 | managers=self.managers, |
159 | 158 | ), |
160 | 159 | ] |
161 | | elif isinstance(operation, FieldOperation) and self.name_lower == operation.model_name_lower: |
| 160 | if isinstance(operation, FieldOperation) and self.name_lower == operation.model_name_lower: |
162 | 161 | if isinstance(operation, AddField): |
163 | 162 | # Don't allow optimizations of FKs through models they reference |
164 | 163 | if hasattr(operation.field, "remote_field") and operation.field.remote_field: |
… |
… |
class CreateModel(ModelOperation):
|
181 | 180 | managers=self.managers, |
182 | 181 | ), |
183 | 182 | ] |
184 | | elif isinstance(operation, AlterField): |
| 183 | if isinstance(operation, AlterField): |
185 | 184 | return [ |
186 | 185 | CreateModel( |
187 | 186 | self.name, |
… |
… |
class CreateModel(ModelOperation):
|
194 | 193 | managers=self.managers, |
195 | 194 | ), |
196 | 195 | ] |
197 | | elif isinstance(operation, RemoveField): |
| 196 | if isinstance(operation, RemoveField): |
198 | 197 | return [ |
199 | 198 | CreateModel( |
200 | 199 | self.name, |
… |
… |
class CreateModel(ModelOperation):
|
208 | 207 | managers=self.managers, |
209 | 208 | ), |
210 | 209 | ] |
211 | | elif isinstance(operation, RenameField): |
| 210 | if isinstance(operation, RenameField): |
212 | 211 | return [ |
213 | 212 | CreateModel( |
214 | 213 | self.name, |
… |
… |
class RenameModel(ModelOperation):
|
284 | 283 | def _get_model_tuple(self, remote_model, app_label, model_name): |
285 | 284 | if remote_model == RECURSIVE_RELATIONSHIP_CONSTANT: |
286 | 285 | return app_label, model_name.lower() |
287 | | elif '.' in remote_model: |
| 286 | if '.' in remote_model: |
288 | 287 | return tuple(remote_model.lower().split('.')) |
289 | | else: |
290 | | return app_label, remote_model.lower() |
| 288 | return app_label, remote_model.lower() |
291 | 289 | |
292 | 290 | def state_forwards(self, app_label, state): |
293 | 291 | # Add a new model. |
-
diff --git a/django/db/migrations/state.py b/django/db/migrations/state.py
index 4dfa3dd..b734598 100644
a
|
b
|
def _get_app_label_and_model_name(model, app_label=''):
|
21 | 21 | if isinstance(model, str): |
22 | 22 | split = model.split('.', 1) |
23 | 23 | return tuple(split) if len(split) == 2 else (app_label, split[0]) |
24 | | else: |
25 | | return model._meta.app_label, model._meta.model_name |
| 24 | return model._meta.app_label, model._meta.model_name |
26 | 25 | |
27 | 26 | |
28 | 27 | def _get_related_models(m): |
-
diff --git a/django/db/models/base.py b/django/db/models/base.py
index 3f4d655..09e5b62 100644
a
|
b
|
class Model(metaclass=ModelBase):
|
1434 | 1434 | ) |
1435 | 1435 | ] |
1436 | 1436 | |
1437 | | elif any(not isinstance(fields, (tuple, list)) for fields in cls._meta.index_together): |
| 1437 | if any(not isinstance(fields, (tuple, list)) for fields in cls._meta.index_together): |
1438 | 1438 | return [ |
1439 | 1439 | checks.Error( |
1440 | 1440 | "All 'index_together' elements must be lists or tuples.", |
… |
… |
class Model(metaclass=ModelBase):
|
1443 | 1443 | ) |
1444 | 1444 | ] |
1445 | 1445 | |
1446 | | else: |
1447 | | errors = [] |
1448 | | for fields in cls._meta.index_together: |
1449 | | errors.extend(cls._check_local_fields(fields, "index_together")) |
1450 | | return errors |
| 1446 | errors = [] |
| 1447 | for fields in cls._meta.index_together: |
| 1448 | errors.extend(cls._check_local_fields(fields, "index_together")) |
| 1449 | return errors |
1451 | 1450 | |
1452 | 1451 | @classmethod |
1453 | 1452 | def _check_unique_together(cls): |
… |
… |
class Model(metaclass=ModelBase):
|
1461 | 1460 | ) |
1462 | 1461 | ] |
1463 | 1462 | |
1464 | | elif any(not isinstance(fields, (tuple, list)) for fields in cls._meta.unique_together): |
| 1463 | if any(not isinstance(fields, (tuple, list)) for fields in cls._meta.unique_together): |
1465 | 1464 | return [ |
1466 | 1465 | checks.Error( |
1467 | 1466 | "All 'unique_together' elements must be lists or tuples.", |
… |
… |
class Model(metaclass=ModelBase):
|
1470 | 1469 | ) |
1471 | 1470 | ] |
1472 | 1471 | |
1473 | | else: |
1474 | | errors = [] |
1475 | | for fields in cls._meta.unique_together: |
1476 | | errors.extend(cls._check_local_fields(fields, "unique_together")) |
1477 | | return errors |
| 1472 | errors = [] |
| 1473 | for fields in cls._meta.unique_together: |
| 1474 | errors.extend(cls._check_local_fields(fields, "unique_together")) |
| 1475 | return errors |
1478 | 1476 | |
1479 | 1477 | @classmethod |
1480 | 1478 | def _check_local_fields(cls, fields, option): |
-
diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
index 82db5c8..dadbce6 100644
a
|
b
|
class BaseExpression:
|
307 | 307 | internal_type = field.get_internal_type() |
308 | 308 | if internal_type == 'FloatField': |
309 | 309 | return lambda value, expression, connection: None if value is None else float(value) |
310 | | elif internal_type.endswith('IntegerField'): |
| 310 | if internal_type.endswith('IntegerField'): |
311 | 311 | return lambda value, expression, connection: None if value is None else int(value) |
312 | | elif internal_type == 'DecimalField': |
| 312 | if internal_type == 'DecimalField': |
313 | 313 | return lambda value, expression, connection: None if value is None else Decimal(value) |
314 | 314 | return self._convert_value_noop |
315 | 315 | |
-
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
index 4a006bc..a40eb6a 100644
a
|
b
|
class Field(RegisterLookupMixin):
|
222 | 222 | id='fields.E001', |
223 | 223 | ) |
224 | 224 | ] |
225 | | elif LOOKUP_SEP in self.name: |
| 225 | if LOOKUP_SEP in self.name: |
226 | 226 | return [ |
227 | 227 | checks.Error( |
228 | 228 | 'Field names must not contain "%s".' % (LOOKUP_SEP,), |
… |
… |
class Field(RegisterLookupMixin):
|
230 | 230 | id='fields.E002', |
231 | 231 | ) |
232 | 232 | ] |
233 | | elif self.name == 'pk': |
| 233 | if self.name == 'pk': |
234 | 234 | return [ |
235 | 235 | checks.Error( |
236 | 236 | "'pk' is a reserved word that cannot be used as a field name.", |
… |
… |
class Field(RegisterLookupMixin):
|
238 | 238 | id='fields.E003', |
239 | 239 | ) |
240 | 240 | ] |
241 | | else: |
242 | | return [] |
| 241 | return [] |
243 | 242 | |
244 | 243 | def _check_choices(self): |
245 | 244 | if self.choices: |
… |
… |
class Field(RegisterLookupMixin):
|
251 | 250 | id='fields.E004', |
252 | 251 | ) |
253 | 252 | ] |
254 | | elif any(isinstance(choice, str) or |
| 253 | if any(isinstance(choice, str) or |
255 | 254 | not is_iterable(choice) or len(choice) != 2 |
256 | 255 | for choice in self.choices): |
257 | 256 | return [ |
… |
… |
class Field(RegisterLookupMixin):
|
262 | 261 | id='fields.E005', |
263 | 262 | ) |
264 | 263 | ] |
265 | | else: |
266 | | return [] |
267 | | else: |
268 | | return [] |
| 264 | return [] |
269 | 265 | |
270 | 266 | def _check_db_index(self): |
271 | 267 | if self.db_index not in (None, True, False): |
… |
… |
class Field(RegisterLookupMixin):
|
276 | 272 | id='fields.E006', |
277 | 273 | ) |
278 | 274 | ] |
279 | | else: |
280 | | return [] |
| 275 | return [] |
281 | 276 | |
282 | 277 | def _check_null_allowed_for_primary_keys(self): |
283 | 278 | if (self.primary_key and self.null and |
… |
… |
class Field(RegisterLookupMixin):
|
294 | 289 | id='fields.E007', |
295 | 290 | ) |
296 | 291 | ] |
297 | | else: |
298 | | return [] |
| 292 | return [] |
299 | 293 | |
300 | 294 | def _check_backend_specific_checks(self, **kwargs): |
301 | 295 | app_label = self.model._meta.app_label |
… |
… |
class Field(RegisterLookupMixin):
|
337 | 331 | id=self.system_check_removed_details.get('id', 'fields.EXXX'), |
338 | 332 | ) |
339 | 333 | ] |
340 | | elif self.system_check_deprecated_details is not None: |
| 334 | if self.system_check_deprecated_details is not None: |
341 | 335 | return [ |
342 | 336 | checks.Warning( |
343 | 337 | self.system_check_deprecated_details.get( |
… |
… |
class CharField(Field):
|
1051 | 1045 | id='fields.E120', |
1052 | 1046 | ) |
1053 | 1047 | ] |
1054 | | elif (not isinstance(self.max_length, int) or isinstance(self.max_length, bool) or |
| 1048 | if (not isinstance(self.max_length, int) or isinstance(self.max_length, bool) or |
1055 | 1049 | self.max_length <= 0): |
1056 | 1050 | return [ |
1057 | 1051 | checks.Error( |
… |
… |
class CharField(Field):
|
1060 | 1054 | id='fields.E121', |
1061 | 1055 | ) |
1062 | 1056 | ] |
1063 | | else: |
1064 | | return [] |
| 1057 | return [] |
1065 | 1058 | |
1066 | 1059 | def cast_db_type(self, connection): |
1067 | 1060 | if self.max_length is None: |
… |
… |
class DateTimeField(DateField):
|
1344 | 1337 | |
1345 | 1338 | def to_python(self, value): |
1346 | 1339 | if value is None: |
1347 | | return value |
| 1340 | return None |
1348 | 1341 | if isinstance(value, datetime.datetime): |
1349 | 1342 | return value |
1350 | 1343 | if isinstance(value, datetime.date): |
-
diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
index 34123fd..2ffbc67 100644
a
|
b
|
class RelatedField(FieldCacheMixin, Field):
|
357 | 357 | base_q = Q(**base_filter) |
358 | 358 | if isinstance(descriptor_filter, dict): |
359 | 359 | return base_q & Q(**descriptor_filter) |
360 | | elif descriptor_filter: |
| 360 | if descriptor_filter: |
361 | 361 | return base_q & descriptor_filter |
362 | 362 | return base_q |
363 | 363 | |
… |
… |
class ForeignKey(ForeignObject):
|
832 | 832 | id='fields.E320', |
833 | 833 | ) |
834 | 834 | ] |
835 | | elif on_delete == SET_DEFAULT and not self.has_default(): |
| 835 | if on_delete == SET_DEFAULT and not self.has_default(): |
836 | 836 | return [ |
837 | 837 | checks.Error( |
838 | 838 | 'Field specifies on_delete=SET_DEFAULT, but has no default value.', |
… |
… |
class ForeignKey(ForeignObject):
|
841 | 841 | id='fields.E321', |
842 | 842 | ) |
843 | 843 | ] |
844 | | else: |
845 | | return [] |
| 844 | return [] |
846 | 845 | |
847 | 846 | def _check_unique(self, **kwargs): |
848 | 847 | return [ |
… |
… |
class ManyToManyField(RelatedField):
|
1500 | 1499 | """ |
1501 | 1500 | if self.remote_field.through is not None: |
1502 | 1501 | return self.remote_field.through._meta.db_table |
1503 | | elif self.db_table: |
| 1502 | if self.db_table: |
1504 | 1503 | return self.db_table |
1505 | | else: |
1506 | | m2m_table_name = '%s_%s' % (utils.strip_quotes(opts.db_table), self.name) |
1507 | | return utils.truncate_name(m2m_table_name, connection.ops.max_name_length()) |
| 1504 | m2m_table_name = '%s_%s' % (utils.strip_quotes(opts.db_table), self.name) |
| 1505 | return utils.truncate_name(m2m_table_name, connection.ops.max_name_length()) |
1508 | 1506 | |
1509 | 1507 | def _get_m2m_attr(self, related, attr): |
1510 | 1508 | """ |
-
diff --git a/django/db/models/functions/datetime.py b/django/db/models/functions/datetime.py
index 44bcb73..ced659c 100644
a
|
b
|
class TruncBase(TimezoneMixin, Transform):
|
198 | 198 | raise ValueError("Cannot truncate DateField '%s' to %s. " % ( |
199 | 199 | field.name, output_field.__class__.__name__ if has_explicit_output_field else 'DateTimeField' |
200 | 200 | )) |
201 | | elif isinstance(field, TimeField) and ( |
| 201 | if isinstance(field, TimeField) and ( |
202 | 202 | isinstance(output_field, DateTimeField) or copy.kind in ('year', 'quarter', 'month', 'day', 'date')): |
203 | 203 | raise ValueError("Cannot truncate TimeField '%s' to %s. " % ( |
204 | 204 | field.name, output_field.__class__.__name__ if has_explicit_output_field else 'DateTimeField' |
-
diff --git a/django/db/models/query.py b/django/db/models/query.py
index 39a8d3a..9261f73 100644
a
|
b
|
class QuerySet:
|
1102 | 1102 | """ |
1103 | 1103 | if self.query.extra_order_by or self.query.order_by: |
1104 | 1104 | return True |
1105 | | elif self.query.default_ordering and self.query.get_meta().ordering: |
| 1105 | if self.query.default_ordering and self.query.get_meta().ordering: |
1106 | 1106 | return True |
1107 | | else: |
1108 | | return False |
| 1107 | return False |
1109 | 1108 | |
1110 | 1109 | @property |
1111 | 1110 | def db(self): |
-
diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py
index 8a88926..2f29fa7 100644
a
|
b
|
class Q(tree.Node):
|
67 | 67 | if not other: |
68 | 68 | return copy.deepcopy(self) |
69 | 69 | # Or if this Q is empty, ignore it and just use `other`. |
70 | | elif not self: |
| 70 | if not self: |
71 | 71 | return copy.deepcopy(other) |
72 | 72 | |
73 | 73 | obj = type(self)() |
-
diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py
index 46559ff..0de137d 100644
a
|
b
|
class SQLCompiler:
|
499 | 499 | # possible deadlock. |
500 | 500 | if nowait and not self.connection.features.has_select_for_update_nowait: |
501 | 501 | raise NotSupportedError('NOWAIT is not supported on this database backend.') |
502 | | elif skip_locked and not self.connection.features.has_select_for_update_skip_locked: |
| 502 | if skip_locked and not self.connection.features.has_select_for_update_skip_locked: |
503 | 503 | raise NotSupportedError('SKIP LOCKED is not supported on this database backend.') |
504 | | elif of and not self.connection.features.has_select_for_update_of: |
| 504 | if of and not self.connection.features.has_select_for_update_of: |
505 | 505 | raise NotSupportedError('FOR UPDATE OF is not supported on this database backend.') |
506 | 506 | for_update_part = self.connection.ops.for_update_sql( |
507 | 507 | nowait=nowait, |
… |
… |
class SQLInsertCompiler(SQLCompiler):
|
1161 | 1161 | raise FieldError("Aggregate functions are not allowed in this query") |
1162 | 1162 | if value.contains_over_clause: |
1163 | 1163 | raise FieldError('Window expressions are not allowed in this query.') |
1164 | | else: |
1165 | | value = field.get_db_prep_save(value, connection=self.connection) |
1166 | | return value |
| 1164 | return value |
| 1165 | return field.get_db_prep_save(value, connection=self.connection) |
1167 | 1166 | |
1168 | 1167 | def pre_save_val(self, field, obj): |
1169 | 1168 | """ |
-
diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
index e7456de..1e26d25 100644
a
|
b
|
class Query:
|
1940 | 1940 | """ |
1941 | 1941 | if self._annotation_select_cache is not None: |
1942 | 1942 | return self._annotation_select_cache |
1943 | | elif not self._annotations: |
| 1943 | if not self._annotations: |
1944 | 1944 | return {} |
1945 | | elif self.annotation_select_mask is not None: |
| 1945 | if self.annotation_select_mask is not None: |
1946 | 1946 | self._annotation_select_cache = OrderedDict( |
1947 | 1947 | (k, v) for k, v in self.annotations.items() |
1948 | 1948 | if k in self.annotation_select_mask |
1949 | 1949 | ) |
1950 | 1950 | return self._annotation_select_cache |
1951 | | else: |
1952 | | return self.annotations |
| 1951 | return self.annotations |
1953 | 1952 | |
1954 | 1953 | @property |
1955 | 1954 | def extra_select(self): |
… |
… |
class Query:
|
1957 | 1956 | return self._extra_select_cache |
1958 | 1957 | if not self._extra: |
1959 | 1958 | return {} |
1960 | | elif self.extra_select_mask is not None: |
| 1959 | if self.extra_select_mask is not None: |
1961 | 1960 | self._extra_select_cache = OrderedDict( |
1962 | 1961 | (k, v) for k, v in self.extra.items() |
1963 | 1962 | if k in self.extra_select_mask |
1964 | 1963 | ) |
1965 | 1964 | return self._extra_select_cache |
1966 | | else: |
1967 | | return self.extra |
| 1965 | return self.extra |
1968 | 1966 | |
1969 | 1967 | def trim_start(self, names_with_path): |
1970 | 1968 | """ |
-
diff --git a/django/db/models/sql/where.py b/django/db/models/sql/where.py
index 0ca95f7..137d2e5 100644
a
|
b
|
class WhereNode(tree.Node):
|
93 | 93 | if empty_needed == 0: |
94 | 94 | if self.negated: |
95 | 95 | return '', [] |
96 | | else: |
97 | | raise EmptyResultSet |
| 96 | raise EmptyResultSet |
98 | 97 | if full_needed == 0: |
99 | 98 | if self.negated: |
100 | 99 | raise EmptyResultSet |
101 | | else: |
102 | | return '', [] |
| 100 | return '', [] |
103 | 101 | conn = ' %s ' % self.connector |
104 | 102 | sql_string = conn.join(result) |
105 | 103 | if sql_string: |
-
diff --git a/django/forms/boundfield.py b/django/forms/boundfield.py
index dba54e5..93156ed 100644
a
|
b
|
class BoundField:
|
193 | 193 | auto_id = self.form.auto_id # Boolean or string |
194 | 194 | if auto_id and '%s' in str(auto_id): |
195 | 195 | return auto_id % self.html_name |
196 | | elif auto_id: |
| 196 | if auto_id: |
197 | 197 | return self.html_name |
198 | 198 | return '' |
199 | 199 | |
-
diff --git a/django/forms/fields.py b/django/forms/fields.py
index 6412484..fa0bd75 100644
a
|
b
|
class NullBooleanField(BooleanField):
|
739 | 739 | """ |
740 | 740 | if value in (True, 'True', 'true', '1'): |
741 | 741 | return True |
742 | | elif value in (False, 'False', 'false', '0'): |
| 742 | if value in (False, 'False', 'false', '0'): |
743 | 743 | return False |
744 | | else: |
745 | | return None |
| 744 | return None |
746 | 745 | |
747 | 746 | def validate(self, value): |
748 | 747 | pass |
… |
… |
class MultipleChoiceField(ChoiceField):
|
856 | 855 | def to_python(self, value): |
857 | 856 | if not value: |
858 | 857 | return [] |
859 | | elif not isinstance(value, (list, tuple)): |
| 858 | if not isinstance(value, (list, tuple)): |
860 | 859 | raise ValidationError(self.error_messages['invalid_list'], code='invalid_list') |
861 | 860 | return [str(val) for val in value] |
862 | 861 | |
… |
… |
class MultiValueField(Field):
|
1005 | 1004 | if not value or not [v for v in value if v not in self.empty_values]: |
1006 | 1005 | if self.required: |
1007 | 1006 | raise ValidationError(self.error_messages['required'], code='required') |
1008 | | else: |
1009 | | return self.compress([]) |
| 1007 | return self.compress([]) |
1010 | 1008 | else: |
1011 | 1009 | raise ValidationError(self.error_messages['invalid'], code='invalid') |
1012 | 1010 | for i, field in enumerate(self.fields): |
-
diff --git a/django/forms/models.py b/django/forms/models.py
index 84a0c97..81ebd5f 100644
a
|
b
|
class ModelMultipleChoiceField(ModelChoiceField):
|
1281 | 1281 | value = self.prepare_value(value) |
1282 | 1282 | if self.required and not value: |
1283 | 1283 | raise ValidationError(self.error_messages['required'], code='required') |
1284 | | elif not self.required and not value: |
| 1284 | if not self.required and not value: |
1285 | 1285 | return self.queryset.none() |
1286 | 1286 | if not isinstance(value, (list, tuple)): |
1287 | 1287 | raise ValidationError(self.error_messages['list'], code='list') |
-
diff --git a/django/middleware/csrf.py b/django/middleware/csrf.py
index ce1329b..f5f43ba 100644
a
|
b
|
def _sanitize_token(token):
|
106 | 106 | # Allow only ASCII alphanumerics |
107 | 107 | if re.search('[^a-zA-Z0-9]', token): |
108 | 108 | return _get_new_csrf_token() |
109 | | elif len(token) == CSRF_TOKEN_LENGTH: |
| 109 | if len(token) == CSRF_TOKEN_LENGTH: |
110 | 110 | return token |
111 | | elif len(token) == CSRF_SECRET_LENGTH: |
| 111 | if len(token) == CSRF_SECRET_LENGTH: |
112 | 112 | # Older Django versions set cookies to values of CSRF_SECRET_LENGTH |
113 | 113 | # alphanumeric characters. For backwards compatibility, accept |
114 | 114 | # such values as unsalted secrets. |
-
diff --git a/django/template/base.py b/django/template/base.py
index 9c81a36..f5f6121 100644
a
|
b
|
class Variable:
|
806 | 806 | msgid = mark_safe(msgid) if is_safe else msgid |
807 | 807 | if self.message_context: |
808 | 808 | return pgettext_lazy(self.message_context, msgid) |
809 | | else: |
810 | | return gettext_lazy(msgid) |
| 809 | return gettext_lazy(msgid) |
811 | 810 | return value |
812 | 811 | |
813 | 812 | def __repr__(self): |
-
diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py
index 143082c..a872ffd 100644
a
|
b
|
class IfChangedNode(Node):
|
241 | 241 | state_frame[self] = compare_to |
242 | 242 | # render true block if not already rendered |
243 | 243 | return nodelist_true_output or self.nodelist_true.render(context) |
244 | | elif self.nodelist_false: |
| 244 | if self.nodelist_false: |
245 | 245 | return self.nodelist_false.render(context) |
246 | 246 | return '' |
247 | 247 | |
-
diff --git a/django/template/loader.py b/django/template/loader.py
index 2492aee..245e6ba 100644
a
|
b
|
def select_template(template_name_list, using=None):
|
45 | 45 | |
46 | 46 | if template_name_list: |
47 | 47 | raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) |
48 | | else: |
49 | | raise TemplateDoesNotExist("No template names provided") |
| 48 | raise TemplateDoesNotExist("No template names provided") |
50 | 49 | |
51 | 50 | |
52 | 51 | def render_to_string(template_name, context=None, request=None, using=None): |
-
diff --git a/django/template/loaders/cached.py b/django/template/loaders/cached.py
index b0799a2..8eb71bc 100644
a
|
b
|
class Loader(BaseLoader):
|
47 | 47 | if cached: |
48 | 48 | if isinstance(cached, type) and issubclass(cached, TemplateDoesNotExist): |
49 | 49 | raise cached(template_name) |
50 | | elif isinstance(cached, TemplateDoesNotExist): |
| 50 | if isinstance(cached, TemplateDoesNotExist): |
51 | 51 | raise copy_exception(cached) |
52 | 52 | return cached |
53 | 53 | |
… |
… |
class Loader(BaseLoader):
|
56 | 56 | except TemplateDoesNotExist as e: |
57 | 57 | self.get_template_cache[key] = copy_exception(e) if self.engine.debug else TemplateDoesNotExist |
58 | 58 | raise |
59 | | else: |
60 | | self.get_template_cache[key] = template |
| 59 | self.get_template_cache[key] = template |
61 | 60 | |
62 | 61 | return template |
63 | 62 | |
-
diff --git a/django/template/response.py b/django/template/response.py
index 5631c78..ec1dd8a 100644
a
|
b
|
class SimpleTemplateResponse(HttpResponse):
|
61 | 61 | """Accept a template object, path-to-template, or list of paths.""" |
62 | 62 | if isinstance(template, (list, tuple)): |
63 | 63 | return select_template(template, using=self.using) |
64 | | elif isinstance(template, str): |
| 64 | if isinstance(template, str): |
65 | 65 | return get_template(template, using=self.using) |
66 | | else: |
67 | | return template |
| 66 | return template |
68 | 67 | |
69 | 68 | def resolve_context(self, context): |
70 | 69 | return context |
-
diff --git a/django/test/utils.py b/django/test/utils.py
index fc783a4..5412a46 100644
a
|
b
|
class ContextList(list):
|
66 | 66 | if key in subcontext: |
67 | 67 | return subcontext[key] |
68 | 68 | raise KeyError(key) |
69 | | else: |
70 | | return super().__getitem__(key) |
| 69 | return super().__getitem__(key) |
71 | 70 | |
72 | 71 | def get(self, key, default=None): |
73 | 72 | try: |
… |
… |
class TestContextDecorator:
|
374 | 373 | def __call__(self, decorated): |
375 | 374 | if isinstance(decorated, type): |
376 | 375 | return self.decorate_class(decorated) |
377 | | elif callable(decorated): |
| 376 | if callable(decorated): |
378 | 377 | return self.decorate_callable(decorated) |
379 | 378 | raise TypeError('Cannot decorate object of type %s' % type(decorated)) |
380 | 379 | |
-
diff --git a/django/utils/archive.py b/django/utils/archive.py
index 879f3c4..fa984f6 100644
a
|
b
|
class BaseArchive:
|
112 | 112 | path = path.lstrip('/').lstrip('\\') |
113 | 113 | if '/' in path and (('\\' in path and path.find('/') < path.find('\\')) or '\\' not in path): |
114 | 114 | return path.split('/', 1) |
115 | | elif '\\' in path: |
| 115 | if '\\' in path: |
116 | 116 | return path.split('\\', 1) |
117 | | else: |
118 | | return path, '' |
| 117 | return path, '' |
119 | 118 | |
120 | 119 | def has_leading_dir(self, paths): |
121 | 120 | """ |
… |
… |
class BaseArchive:
|
127 | 126 | prefix, rest = self.split_leading_dir(path) |
128 | 127 | if not prefix: |
129 | 128 | return False |
130 | | elif common_prefix is None: |
| 129 | if common_prefix is None: |
131 | 130 | common_prefix = prefix |
132 | 131 | elif prefix != common_prefix: |
133 | 132 | return False |
-
diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py
index 127c6dc7..973a1d7 100644
a
|
b
|
class ImmutableList(tuple):
|
236 | 236 | def complain(self, *wargs, **kwargs): |
237 | 237 | if isinstance(self.warning, Exception): |
238 | 238 | raise self.warning |
239 | | else: |
240 | | raise AttributeError(self.warning) |
| 239 | raise AttributeError(self.warning) |
241 | 240 | |
242 | 241 | # All list mutation functions complain. |
243 | 242 | __delitem__ = complain |
-
diff --git a/django/utils/formats.py b/django/utils/formats.py
index bba45e3..bec9fb1 100644
a
|
b
|
def localize(value, use_l10n=None):
|
193 | 193 | """ |
194 | 194 | if isinstance(value, str): # Handle strings first for performance reasons. |
195 | 195 | return value |
196 | | elif isinstance(value, bool): # Make sure booleans don't get treated as numbers |
| 196 | if isinstance(value, bool): # Make sure booleans don't get treated as numbers |
197 | 197 | return str(value) |
198 | | elif isinstance(value, (decimal.Decimal, float, int)): |
| 198 | if isinstance(value, (decimal.Decimal, float, int)): |
199 | 199 | return number_format(value, use_l10n=use_l10n) |
200 | | elif isinstance(value, datetime.datetime): |
| 200 | if isinstance(value, datetime.datetime): |
201 | 201 | return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n) |
202 | | elif isinstance(value, datetime.date): |
| 202 | if isinstance(value, datetime.date): |
203 | 203 | return date_format(value, use_l10n=use_l10n) |
204 | | elif isinstance(value, datetime.time): |
| 204 | if isinstance(value, datetime.time): |
205 | 205 | return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n) |
206 | 206 | return value |
207 | 207 | |
… |
… |
def localize_input(value, default=None):
|
213 | 213 | """ |
214 | 214 | if isinstance(value, str): # Handle strings first for performance reasons. |
215 | 215 | return value |
216 | | elif isinstance(value, bool): # Don't treat booleans as numbers. |
| 216 | if isinstance(value, bool): # Don't treat booleans as numbers. |
217 | 217 | return str(value) |
218 | | elif isinstance(value, (decimal.Decimal, float, int)): |
| 218 | if isinstance(value, (decimal.Decimal, float, int)): |
219 | 219 | return number_format(value) |
220 | | elif isinstance(value, datetime.datetime): |
| 220 | if isinstance(value, datetime.datetime): |
221 | 221 | value = datetime_safe.new_datetime(value) |
222 | 222 | format = default or get_format('DATETIME_INPUT_FORMATS')[0] |
223 | 223 | return value.strftime(format) |
224 | | elif isinstance(value, datetime.date): |
| 224 | if isinstance(value, datetime.date): |
225 | 225 | value = datetime_safe.new_date(value) |
226 | 226 | format = default or get_format('DATE_INPUT_FORMATS')[0] |
227 | 227 | return value.strftime(format) |
228 | | elif isinstance(value, datetime.time): |
| 228 | if isinstance(value, datetime.time): |
229 | 229 | format = default or get_format('TIME_INPUT_FORMATS')[0] |
230 | 230 | return value.strftime(format) |
231 | 231 | return value |
-
diff --git a/django/utils/functional.py b/django/utils/functional.py
index af49322..ef7eed6 100644
a
|
b
|
def lazy(func, *resultclasses):
|
121 | 121 | def __cast(self): |
122 | 122 | if self._delegate_bytes: |
123 | 123 | return self.__bytes_cast() |
124 | | elif self._delegate_text: |
| 124 | if self._delegate_text: |
125 | 125 | return self.__text_cast() |
126 | | else: |
127 | | return func(*self.__args, **self.__kw) |
| 126 | return func(*self.__args, **self.__kw) |
128 | 127 | |
129 | 128 | def __str__(self): |
130 | 129 | # object defines __str__(), so __prepare_class__() won't overload |
-
diff --git a/django/utils/ipv6.py b/django/utils/ipv6.py
index ddb8c80..224c39c 100644
a
|
b
|
def clean_ipv6_address(ip_str, unpack_ipv4=False,
|
29 | 29 | |
30 | 30 | if unpack_ipv4 and addr.ipv4_mapped: |
31 | 31 | return str(addr.ipv4_mapped) |
32 | | elif addr.ipv4_mapped: |
| 32 | if addr.ipv4_mapped: |
33 | 33 | return '::ffff:%s' % str(addr.ipv4_mapped) |
34 | 34 | |
35 | 35 | return str(addr) |
-
diff --git a/django/utils/safestring.py b/django/utils/safestring.py
index 2da467a..b6fa2cf 100644
a
|
b
|
class SafeBytes(bytes, SafeData):
|
34 | 34 | t = super().__add__(rhs) |
35 | 35 | if isinstance(rhs, SafeText): |
36 | 36 | return SafeText(t) |
37 | | elif isinstance(rhs, SafeBytes): |
| 37 | if isinstance(rhs, SafeBytes): |
38 | 38 | return SafeBytes(t) |
39 | 39 | return t |
40 | 40 | |
-
diff --git a/django/views/generic/dates.py b/django/views/generic/dates.py
index 2aedf3a..bcd5be5 100644
a
|
b
|
class MonthMixin:
|
109 | 109 | return date.replace(year=date.year + 1, month=1, day=1) |
110 | 110 | except ValueError: |
111 | 111 | raise Http404(_("Date out of range")) |
112 | | else: |
113 | | return date.replace(month=date.month + 1, day=1) |
| 112 | return date.replace(month=date.month + 1, day=1) |
114 | 113 | |
115 | 114 | def _get_current_month(self, date): |
116 | 115 | """Return the start date of the previous interval.""" |
-
diff --git a/django/views/generic/detail.py b/django/views/generic/detail.py
index 82599bd..17d91f4 100644
a
|
b
|
class SingleObjectMixin(ContextMixin):
|
82 | 82 | """Get the name to use for the object.""" |
83 | 83 | if self.context_object_name: |
84 | 84 | return self.context_object_name |
85 | | elif isinstance(obj, models.Model): |
| 85 | if isinstance(obj, models.Model): |
86 | 86 | return obj._meta.model_name |
87 | | else: |
88 | | return None |
| 87 | return None |
89 | 88 | |
90 | 89 | def get_context_data(self, **kwargs): |
91 | 90 | """Insert the single object into the context dict.""" |
-
diff --git a/django/views/generic/list.py b/django/views/generic/list.py
index 6753c1a..6fdcd81 100644
a
|
b
|
class MultipleObjectMixin(ContextMixin):
|
105 | 105 | """Get the name of the item to be used in the context.""" |
106 | 106 | if self.context_object_name: |
107 | 107 | return self.context_object_name |
108 | | elif hasattr(object_list, 'model'): |
| 108 | if hasattr(object_list, 'model'): |
109 | 109 | return '%s_list' % object_list.model._meta.model_name |
110 | | else: |
111 | | return None |
| 110 | return None |
112 | 111 | |
113 | 112 | def get_context_data(self, *, object_list=None, **kwargs): |
114 | 113 | """Get the context for this view.""" |
-
diff --git a/scripts/manage_translations.py b/scripts/manage_translations.py
index 5397d35..8381568 100644
a
|
b
|
def _tx_resource_for_name(name):
|
63 | 63 | """ Return the Transifex resource name """ |
64 | 64 | if name == 'core': |
65 | 65 | return "django.core" |
66 | | else: |
67 | | return "django.contrib-%s" % name |
| 66 | return "django.contrib-%s" % name |
68 | 67 | |
69 | 68 | |
70 | 69 | def _check_diff(cat_name, base_path): |
-
diff --git a/tests/admin_filters/tests.py b/tests/admin_filters/tests.py
index 4a11c1a..6bdb0c8 100644
a
|
b
|
class NotNinetiesListFilter(SimpleListFilter):
|
51 | 51 | def queryset(self, request, queryset): |
52 | 52 | if self.value() == 'the 90s': |
53 | 53 | return queryset.filter(year__gte=1990, year__lte=1999) |
54 | | else: |
55 | | return queryset.exclude(year__gte=1990, year__lte=1999) |
| 54 | return queryset.exclude(year__gte=1990, year__lte=1999) |
56 | 55 | |
57 | 56 | |
58 | 57 | class DecadeListFilterWithTitleAndParameter(DecadeListFilter): |
… |
… |
class DepartmentListFilterLookupWithDynamicValue(DecadeListFilterWithTitleAndPar
|
127 | 126 | def lookups(self, request, model_admin): |
128 | 127 | if self.value() == 'the 80s': |
129 | 128 | return (('the 90s', "the 1990's"),) |
130 | | elif self.value() == 'the 90s': |
| 129 | if self.value() == 'the 90s': |
131 | 130 | return (('the 80s', "the 1980's"),) |
132 | | else: |
133 | | return (('the 80s', "the 1980's"), ('the 90s', "the 1990's"),) |
| 131 | return (('the 80s', "the 1980's"), ('the 90s', "the 1990's"),) |
134 | 132 | |
135 | 133 | |
136 | 134 | class CustomUserAdmin(UserAdmin): |
-
diff --git a/tests/admin_ordering/models.py b/tests/admin_ordering/models.py
index b8098b9..3c091a0 100644
a
|
b
|
class DynOrderingBandAdmin(admin.ModelAdmin):
|
35 | 35 | def get_ordering(self, request): |
36 | 36 | if request.user.is_superuser: |
37 | 37 | return ['rank'] |
38 | | else: |
39 | | return ['name'] |
| 38 | return ['name'] |
-
diff --git a/tests/admin_views/admin.py b/tests/admin_views/admin.py
index 2c58bae..ffea097 100644
a
|
b
|
class PostAdmin(admin.ModelAdmin):
|
450 | 450 | def coolness(self, instance): |
451 | 451 | if instance.pk: |
452 | 452 | return "%d amount of cool." % instance.pk |
453 | | else: |
454 | | return "Unknown coolness." |
| 453 | return "Unknown coolness." |
455 | 454 | |
456 | 455 | def value(self, instance): |
457 | 456 | return 1000 |
-
diff --git a/tests/auth_tests/test_auth_backends.py b/tests/auth_tests/test_auth_backends.py
index 86d5357..1c2d2c5 100644
a
|
b
|
class SimpleRowlevelBackend:
|
332 | 332 | if isinstance(obj, TestObj): |
333 | 333 | if user.username == 'test2': |
334 | 334 | return True |
335 | | elif user.is_anonymous and perm == 'anon': |
| 335 | if user.is_anonymous and perm == 'anon': |
336 | 336 | return True |
337 | | elif not user.is_active and perm == 'inactive': |
| 337 | if not user.is_active and perm == 'inactive': |
338 | 338 | return True |
339 | 339 | return False |
340 | 340 | |
… |
… |
class SimpleRowlevelBackend:
|
354 | 354 | return ['anon'] |
355 | 355 | if user.username == 'test2': |
356 | 356 | return ['simple', 'advanced'] |
357 | | else: |
358 | | return ['simple'] |
| 357 | return ['simple'] |
359 | 358 | |
360 | 359 | def get_group_permissions(self, user, obj=None): |
361 | 360 | if not obj: |
… |
… |
class SimpleRowlevelBackend:
|
366 | 365 | |
367 | 366 | if 'test_group' in [group.name for group in user.groups.all()]: |
368 | 367 | return ['group_perm'] |
369 | | else: |
370 | | return ['none'] |
| 368 | return ['none'] |
371 | 369 | |
372 | 370 | |
373 | 371 | @modify_settings(AUTHENTICATION_BACKENDS={ |
-
diff --git a/tests/builtin_server/tests.py b/tests/builtin_server/tests.py
index 73e3d0c..8c6ce80 100644
a
|
b
|
class ServerHandler(simple_server.ServerHandler):
|
20 | 20 | if not self.status: |
21 | 21 | raise AssertionError("write() before start_response()") |
22 | 22 | |
23 | | elif not self.headers_sent: |
| 23 | if not self.headers_sent: |
24 | 24 | # Before the first output, send the stored headers |
25 | 25 | self.bytes_sent = len(data) # make sure we know content-length |
26 | 26 | self.send_headers() |
-
diff --git a/tests/contenttypes_tests/operations_migrations/0002_rename_foo.py b/tests/contenttypes_tests/operations_migrations/0002_rename_foo.py
index 3a1527d..62464ea 100644
a
|
b
|
def assert_foo_contenttype_not_cached(apps, schema_editor):
|
10 | 10 | else: |
11 | 11 | if not ContentType.objects.filter(app_label='contenttypes_tests', model='foo').exists(): |
12 | 12 | raise AssertionError('The contenttypes_tests.Foo ContentType should not be cached.') |
13 | | elif content_type.model != 'foo': |
| 13 | if content_type.model != 'foo': |
14 | 14 | raise AssertionError( |
15 | 15 | "The cached contenttypes_tests.Foo ContentType should have " |
16 | 16 | "its model set to 'foo'." |
-
diff --git a/tests/file_uploads/views.py b/tests/file_uploads/views.py
index 5c35a5a..c1cefbf 100644
a
|
b
|
def file_upload_view(request):
|
22 | 22 | if os.path.dirname(form_data['file_field'].name) != '': |
23 | 23 | return HttpResponseServerError() |
24 | 24 | return HttpResponse('') |
25 | | else: |
26 | | return HttpResponseServerError() |
| 25 | return HttpResponseServerError() |
27 | 26 | |
28 | 27 | |
29 | 28 | def file_upload_view_verify(request): |
… |
… |
def file_upload_unicode_name(request):
|
77 | 76 | obj.delete() |
78 | 77 | os.unlink(full_name) |
79 | 78 | |
80 | | if response: |
81 | | return response |
82 | | else: |
83 | | return HttpResponse('') |
| 79 | return response or HttpResponse('') |
84 | 80 | |
85 | 81 | |
86 | 82 | def file_upload_echo(request): |
-
diff --git a/tests/forms_tests/field_tests/test_filepathfield.py b/tests/forms_tests/field_tests/test_filepathfield.py
index 44f6aff..dff1597 100644
a
|
b
|
def fix_os_paths(x):
|
11 | 11 | if x.startswith(PATH): |
12 | 12 | x = x[len(PATH):] |
13 | 13 | return x.replace('\\', '/') |
14 | | elif isinstance(x, tuple): |
| 14 | if isinstance(x, tuple): |
15 | 15 | return tuple(fix_os_paths(list(x))) |
16 | | elif isinstance(x, list): |
| 16 | if isinstance(x, list): |
17 | 17 | return [fix_os_paths(y) for y in x] |
18 | | else: |
19 | | return x |
| 18 | return x |
20 | 19 | |
21 | 20 | |
22 | 21 | class FilePathFieldTest(SimpleTestCase): |
-
diff --git a/tests/gis_tests/tests.py b/tests/gis_tests/tests.py
index 20b66cd..7e0a5dc 100644
a
|
b
|
if HAS_POSTGRES:
|
26 | 26 | if func == 'postgis_lib_version': |
27 | 27 | if self.version is None: |
28 | 28 | raise ProgrammingError |
29 | | else: |
30 | | return self.version |
| 29 | return self.version |
31 | 30 | elif func == 'version': |
32 | 31 | pass |
33 | 32 | else: |
-
diff --git a/tests/gis_tests/utils.py b/tests/gis_tests/utils.py
index b30da7e..ad44274 100644
a
|
b
|
def no_backend(test_func, backend):
|
31 | 31 | def inner(): |
32 | 32 | pass |
33 | 33 | return inner |
34 | | else: |
35 | | return test_func |
| 34 | return test_func |
36 | 35 | |
37 | 36 | |
38 | 37 | # Decorators to disable entire test functions for specific |
-
diff --git a/tests/humanize_tests/tests.py b/tests/humanize_tests/tests.py
index df9ae4f..4a202ba 100644
a
|
b
|
class HumanizeTests(SimpleTestCase):
|
277 | 277 | def now(cls, tz=None): |
278 | 278 | if tz is None or tz.utcoffset(documented_now) is None: |
279 | 279 | return documented_now |
280 | | else: |
281 | | return documented_now.replace(tzinfo=tz) + tz.utcoffset(now) |
| 280 | return documented_now.replace(tzinfo=tz) + tz.utcoffset(now) |
282 | 281 | |
283 | 282 | orig_humanize_datetime = humanize.datetime |
284 | 283 | humanize.datetime = DocumentedMockDateTime |
-
diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py
index fc8eaa2..b2fcfce 100644
a
|
b
|
class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase):
|
79 | 79 | pattern = re.compile(r'^\#\:.*' + re.escape(needle), re.MULTILINE) |
80 | 80 | if assert_presence: |
81 | 81 | return self.assertRegex(po_contents, pattern, '"%s" not found in final .po file.' % needle) |
82 | | else: |
83 | | return self.assertNotRegex(po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle) |
| 82 | return self.assertNotRegex(po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle) |
84 | 83 | |
85 | 84 | def _get_token_line_number(self, path, token): |
86 | 85 | with open(path) as f: |
-
diff --git a/tests/introspection/tests.py b/tests/introspection/tests.py
index 63817a5..fb2f5c1 100644
a
|
b
|
def datatype(dbtype, description):
|
211 | 211 | dt = connection.introspection.get_field_type(dbtype, description) |
212 | 212 | if type(dt) is tuple: |
213 | 213 | return dt[0] |
214 | | else: |
215 | | return dt |
| 214 | return dt |
-
diff --git a/tests/migrations/routers.py b/tests/migrations/routers.py
index 21dfc56..91c17c5 100644
a
|
b
|
class TestRouter:
|
9 | 9 | """ |
10 | 10 | if model_name == 'tribble': |
11 | 11 | return db == 'other' |
12 | | elif db == 'other': |
| 12 | if db == 'other': |
13 | 13 | return False |
-
diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py
index 8caa0b5..46e720f 100644
a
|
b
|
class MakeMigrationsTests(MigrationTestBase):
|
698 | 698 | def patched_has_table(migration_recorder): |
699 | 699 | if migration_recorder.connection is connections['other']: |
700 | 700 | raise Exception('Other connection') |
701 | | else: |
702 | | return mock.DEFAULT |
| 701 | return mock.DEFAULT |
703 | 702 | |
704 | 703 | self.assertTableNotExists('migrations_unicodemodel') |
705 | 704 | apps.register_model('migrations', UnicodeModel) |
-
diff --git a/tests/model_forms/models.py b/tests/model_forms/models.py
index aecbeb1..74d6fa6 100644
a
|
b
|
class CustomErrorMessage(models.Model):
|
377 | 377 | def clean(self): |
378 | 378 | if self.name1 == 'FORBIDDEN_VALUE': |
379 | 379 | raise ValidationError({'name1': [ValidationError('Model.clean() error messages.')]}) |
380 | | elif self.name1 == 'FORBIDDEN_VALUE2': |
| 380 | if self.name1 == 'FORBIDDEN_VALUE2': |
381 | 381 | raise ValidationError({'name1': 'Model.clean() error messages (simpler syntax).'}) |
382 | | elif self.name1 == 'GLOBAL_ERROR': |
| 382 | if self.name1 == 'GLOBAL_ERROR': |
383 | 383 | raise ValidationError("Global error message.") |
384 | 384 | |
385 | 385 | |
-
diff --git a/tests/multiple_database/tests.py b/tests/multiple_database/tests.py
index 50859a3..c1cdb40 100644
a
|
b
|
class AntiPetRouter:
|
1568 | 1568 | def allow_migrate(self, db, app_label, model_name=None, **hints): |
1569 | 1569 | if db == 'other': |
1570 | 1570 | return model_name == 'pet' |
1571 | | else: |
1572 | | return model_name != 'pet' |
| 1571 | return model_name != 'pet' |
1573 | 1572 | |
1574 | 1573 | |
1575 | 1574 | class FixtureTestCase(TestCase): |
-
diff --git a/tests/runtests.py b/tests/runtests.py
index ae2d693..f825357 100755
a
|
b
|
def actual_test_processes(parallel):
|
236 | 236 | # This doesn't work before django.setup() on some databases. |
237 | 237 | if all(conn.features.can_clone_databases for conn in connections.all()): |
238 | 238 | return default_test_processes() |
239 | | else: |
240 | | return 1 |
241 | | else: |
242 | | return parallel |
| 239 | return 1 |
| 240 | return parallel |
243 | 241 | |
244 | 242 | |
245 | 243 | class ActionSelenium(argparse.Action): |
-
diff --git a/tests/servers/test_basehttp.py b/tests/servers/test_basehttp.py
index 8372336..5ddc3ac 100644
a
|
b
|
class WSGIRequestHandlerTestCase(SimpleTestCase):
|
101 | 101 | def makefile(mode, *a, **kw): |
102 | 102 | if mode == 'rb': |
103 | 103 | return rfile |
104 | | elif mode == 'wb': |
| 104 | if mode == 'wb': |
105 | 105 | return wfile |
106 | 106 | |
107 | 107 | request = Stub(makefile=makefile) |
-
diff --git a/tests/template_tests/utils.py b/tests/template_tests/utils.py
index 66a1733..b0cae08 100644
a
|
b
|
class SomeClass:
|
115 | 115 | def __getitem__(self, key): |
116 | 116 | if key == 'silent_fail_key': |
117 | 117 | raise SomeException |
118 | | elif key == 'noisy_fail_key': |
| 118 | if key == 'noisy_fail_key': |
119 | 119 | raise SomeOtherException |
120 | 120 | raise KeyError |
121 | 121 | |
-
diff --git a/tests/test_client/views.py b/tests/test_client/views.py
index 3387008..bb6eb2e 100644
a
|
b
|
def trace_view(request):
|
33 | 33 | """ |
34 | 34 | if request.method.upper() != "TRACE": |
35 | 35 | return HttpResponseNotAllowed("TRACE") |
36 | | elif request.body: |
| 36 | if request.body: |
37 | 37 | return HttpResponseBadRequest("TRACE requests MUST NOT include an entity") |
38 | | else: |
39 | | protocol = request.META["SERVER_PROTOCOL"] |
40 | | t = Template( |
41 | | '{{ method }} {{ uri }} {{ version }}', |
42 | | name="TRACE Template", |
43 | | ) |
44 | | c = Context({ |
45 | | 'method': request.method, |
46 | | 'uri': request.path, |
47 | | 'version': protocol, |
48 | | }) |
49 | | return HttpResponse(t.render(c)) |
| 38 | protocol = request.META["SERVER_PROTOCOL"] |
| 39 | t = Template( |
| 40 | '{{ method }} {{ uri }} {{ version }}', |
| 41 | name="TRACE Template", |
| 42 | ) |
| 43 | c = Context({ |
| 44 | 'method': request.method, |
| 45 | 'uri': request.path, |
| 46 | 'version': protocol, |
| 47 | }) |
| 48 | return HttpResponse(t.render(c)) |
50 | 49 | |
51 | 50 | |
52 | 51 | def post_view(request): |
-
diff --git a/tests/test_client_regress/views.py b/tests/test_client_regress/views.py
index 5e4c996..e03f0e4 100644
a
|
b
|
def view_with_argument(request, name):
|
52 | 52 | """ |
53 | 53 | if name == 'Arthur Dent': |
54 | 54 | return HttpResponse('Hi, Arthur') |
55 | | else: |
56 | | return HttpResponse('Howdy, %s' % name) |
| 55 | return HttpResponse('Howdy, %s' % name) |
57 | 56 | |
58 | 57 | |
59 | 58 | def nested_view(request): |
-
diff --git a/tests/utils_tests/test_lazyobject.py b/tests/utils_tests/test_lazyobject.py
index 2bba558..b6c8919 100644
a
|
b
|
class BaseBaz:
|
376 | 376 | for attr in ['bar', 'baz', 'quux']: |
377 | 377 | if hasattr(self, attr) != hasattr(other, attr): |
378 | 378 | return False |
379 | | elif getattr(self, attr, None) != getattr(other, attr, None): |
| 379 | if getattr(self, attr, None) != getattr(other, attr, None): |
380 | 380 | return False |
381 | 381 | return True |
382 | 382 | |