repo stringclasses 11
values | instance_id stringlengths 18 32 | base_commit stringlengths 40 40 | patch stringlengths 314 3.81k | test_patch stringlengths 394 11.9k | problem_statement stringlengths 143 10.2k | hints_text stringlengths 0 8.86k | created_at stringdate 2013-01-25 05:19:16 2023-07-17 20:28:41 | version stringlengths 3 7 | FAIL_TO_PASS stringlengths 13 32.6k | PASS_TO_PASS stringlengths 2 271k | environment_setup_commit stringlengths 40 40 | difficulty stringclasses 1
value | target_file stringlengths 194 332k | patch_range listlengths 1 6 | file_path stringlengths 15 50 | image_name stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
astropy/astropy | astropy__astropy-14309 | cdb66059a2feb44ee49021874605ba90801f9986 | diff --git a/astropy/io/fits/connect.py b/astropy/io/fits/connect.py
--- a/astropy/io/fits/connect.py
+++ b/astropy/io/fits/connect.py
@@ -65,10 +65,9 @@ def is_fits(origin, filepath, fileobj, *args, **kwargs):
fileobj.seek(pos)
return sig == FITS_SIGNATURE
elif filepath is not None:
- if ... | diff --git a/astropy/io/fits/tests/test_connect.py b/astropy/io/fits/tests/test_connect.py
--- a/astropy/io/fits/tests/test_connect.py
+++ b/astropy/io/fits/tests/test_connect.py
@@ -7,7 +7,14 @@
from astropy import units as u
from astropy.io import fits
-from astropy.io.fits import BinTableHDU, HDUList, ImageHDU, ... | IndexError: tuple index out of range in identify_format (io.registry)
<!-- This comments are hidden when you submit the issue,
so you do not need to remove them! -->
<!-- Please be sure to check out our contributing guidelines,
https://github.com/astropy/astropy/blob/main/CONTRIBUTING.md .
Please be sure to check... | cc @nstarman from #14274 | 2023-01-23T22:34:01Z | 5.1 | ["astropy/io/fits/tests/test_connect.py::test_is_fits_gh_14305"] | ["astropy/io/fits/tests/test_connect.py::TestSingleTable::test_simple", "astropy/io/fits/tests/test_connect.py::TestSingleTable::test_simple_pathlib", "astropy/io/fits/tests/test_connect.py::TestSingleTable::test_simple_meta", "astropy/io/fits/tests/test_connect.py::TestSingleTable::test_simple_meta_conflicting", "astr... | 5f74eacbcc7fff707a44d8eb58adaa514cb7dcb5 | <15 min fix | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
import re
import warnings
from copy import deepcopy
import numpy as np
from astropy import units as u
from astropy.io import registry as io_registry
from astropy.table import Column, MaskedColumn, Table, meta, serialize
from astropy.time impo... | [
[
65,
73
]
] | astropy/io/fits/connect.py | python:3.11 |
astropy/astropy | astropy__astropy-14995 | b16c7d12ccbc7b2d20364b89fb44285bcbfede54 | diff --git a/astropy/nddata/mixins/ndarithmetic.py b/astropy/nddata/mixins/ndarithmetic.py
--- a/astropy/nddata/mixins/ndarithmetic.py
+++ b/astropy/nddata/mixins/ndarithmetic.py
@@ -520,10 +520,10 @@ def _arithmetic_mask(self, operation, operand, handle_mask, axis=None, **kwds):
elif self.mask is None and ope... | diff --git a/astropy/nddata/mixins/tests/test_ndarithmetic.py b/astropy/nddata/mixins/tests/test_ndarithmetic.py
--- a/astropy/nddata/mixins/tests/test_ndarithmetic.py
+++ b/astropy/nddata/mixins/tests/test_ndarithmetic.py
@@ -1310,3 +1310,42 @@ def test_raise_method_not_supported():
# raise error for unsupported ... | In v5.3, NDDataRef mask propagation fails when one of the operand does not have a mask
### Description
This applies to v5.3.
It looks like when one of the operand does not have a mask, the mask propagation when doing arithmetic, in particular with `handle_mask=np.bitwise_or` fails. This is not a problem in v5.2.
... | Welcome to Astropy 👋 and thank you for your first issue!
A project member will respond to you as soon as possible; in the meantime, please double-check the [guidelines for submitting issues](https://github.com/astropy/astropy/blob/main/CONTRIBUTING.md#reporting-issues) and make sure you've provided the requested deta... | 2023-06-27T19:48:18Z | 5.2 | ["astropy/nddata/mixins/tests/test_ndarithmetic.py::test_nddata_bitmask_arithmetic"] | ["astropy/nddata/mixins/tests/test_ndarithmetic.py::test_arithmetics_data[data10-data20]", "astropy/nddata/mixins/tests/test_ndarithmetic.py::test_arithmetics_data[data11-data21]", "astropy/nddata/mixins/tests/test_ndarithmetic.py::test_arithmetics_data[data12-data22]", "astropy/nddata/mixins/tests/test_ndarithmetic.py... | 362f6df12abf9bd769d4915fabf955c993ea22cf | <15 min fix | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# This module implements the Arithmetic mixin to the NDData class.
import warnings
from copy import deepcopy
import numpy as np
from astropy.nddata.nduncertainty import NDUncertainty
from astropy.units import dimensionless_unscaled
from astropy.utils im... | [
[
520,
529
]
] | astropy/nddata/mixins/ndarithmetic.py | python:3.11 |
astropy/astropy | astropy__astropy-7166 | 26d147868f8a891a6009a25cd6a8576d2e1bd747 | diff --git a/astropy/utils/misc.py b/astropy/utils/misc.py
--- a/astropy/utils/misc.py
+++ b/astropy/utils/misc.py
@@ -4,9 +4,6 @@
A "grab bag" of relatively small general-purpose utilities that don't have
a clear module/package to live in.
"""
-
-
-
import abc
import contextlib
import difflib
@@ -27,7 +24,6 @@
... | diff --git a/astropy/utils/tests/test_misc.py b/astropy/utils/tests/test_misc.py
--- a/astropy/utils/tests/test_misc.py
+++ b/astropy/utils/tests/test_misc.py
@@ -80,14 +80,26 @@ def __call__(self, *args):
"FOO"
pass
+ @property
+ def bar(self):
+ "BAR"
+ ... | InheritDocstrings metaclass doesn't work for properties
Inside the InheritDocstrings metaclass it uses `inspect.isfunction` which returns `False` for properties.
| This was as implemented back in #2159. I don't see any `inspect.isproperty`. Do you have any suggestions?
I guess it should work with [inspect.isdatadescriptor](https://docs.python.org/3/library/inspect.html#inspect.isdatadescriptor).
And I wonder if this class is still needed, it seems that it started with #2136 for... | 2018-02-07T15:05:31Z | 1.3 | ["astropy/utils/tests/test_misc.py::test_inherit_docstrings"] | ["astropy/utils/tests/test_misc.py::test_isiterable", "astropy/utils/tests/test_misc.py::test_signal_number_to_name_no_failure", "astropy/utils/tests/test_misc.py::test_skip_hidden", "astropy/utils/tests/test_misc.py::test_JsonCustomEncoder", "astropy/utils/tests/test_misc.py::test_check_broadcast", "astropy/utils/test... | 848c8fa21332abd66b44efe3cb48b72377fb32cc | <15 min fix | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
A "grab bag" of relatively small general-purpose utilities that don't have
a clear module/package to live in.
"""
import abc
import contextlib
import difflib
import inspect
import json
import os
import signal
import sys
impor... | [
[
4,
9
],
[
24,
29
],
[
524,
532
]
] | astropy/utils/misc.py | python:3.11 |
astropy/astropy | astropy__astropy-7336 | 732d89c2940156bdc0e200bb36dc38b5e424bcba | diff --git a/astropy/units/decorators.py b/astropy/units/decorators.py
--- a/astropy/units/decorators.py
+++ b/astropy/units/decorators.py
@@ -220,7 +220,7 @@ def wrapper(*func_args, **func_kwargs):
# Call the original function with any equivalencies in force.
with add_enabled_equivalencies(se... | diff --git a/astropy/units/tests/py3_test_quantity_annotations.py b/astropy/units/tests/test_quantity_annotations.py
similarity index 60%
rename from astropy/units/tests/py3_test_quantity_annotations.py
rename to astropy/units/tests/test_quantity_annotations.py
--- a/astropy/units/tests/py3_test_quantity_annotations.py... | units.quantity_input decorator fails for constructors with type hinted return value -> None
### Summary
I am using the `units.quantity_input` decorator with typing hints for constructors, however when I add the correct return value for the constructor (`None`) then I get an exception, because `None` has no attribute `... | `git blame` says #3072 -- @Cadair !
yeah, I did add this feature... | 2018-03-28T15:31:32Z | 1.3 | ["astropy/units/tests/test_quantity_annotations.py::test_return_annotation_none"] | ["astropy/units/tests/test_quantity_annotations.py::test_args3[solarx_unit0-solary_unit0]", "astropy/units/tests/test_quantity_annotations.py::test_args3[angle-angle]", "astropy/units/tests/test_quantity_annotations.py::test_args_noconvert3[solarx_unit0-solary_unit0]", "astropy/units/tests/test_quantity_annotations.py:... | 848c8fa21332abd66b44efe3cb48b72377fb32cc | <15 min fix | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ['quantity_input']
import inspect
from ..utils.decorators import wraps
from ..utils.misc import isiterable
from .core import Unit, UnitsError, add_enabled_equivalencies
from .physical import _unit_physical_mapping
def... | [
[
220,
226
]
] | astropy/units/decorators.py | python:3.11 |
django/django | django__django-10097 | b9cf764be62e77b4777b3a75ec256f6209a57671 | diff --git a/django/core/validators.py b/django/core/validators.py
--- a/django/core/validators.py
+++ b/django/core/validators.py
@@ -94,7 +94,7 @@ class URLValidator(RegexValidator):
regex = _lazy_re_compile(
r'^(?:[a-z0-9\.\-\+]*)://' # scheme is validated separately
- r'(?:\S+(?::\S*)?@)?' ... | diff --git a/tests/validators/invalid_urls.txt b/tests/validators/invalid_urls.txt
--- a/tests/validators/invalid_urls.txt
+++ b/tests/validators/invalid_urls.txt
@@ -57,3 +57,9 @@ http://example.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.
http://example.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... | Make URLValidator reject invalid characters in the username and password
Description
(last modified by Tim Bell)
Since #20003, core.validators.URLValidator accepts URLs with usernames and passwords. RFC 1738 section 3.1 requires "Within the user and password field, any ":", "@", or "/" must be encoded"; however... | 2018-06-26T23:30:51Z | 2.2 | ["test_ascii_validator (auth_tests.test_validators.UsernameValidatorsTests)", "test_unicode_validator (auth_tests.test_validators.UsernameValidatorsTests)", "test_help_text (auth_tests.test_validators.UserAttributeSimilarityValidatorTest)", "test_validate (auth_tests.test_validators.UserAttributeSimilarityValidatorTest... | ["test_defaults (str.tests.SimpleTests)", "test_international (str.tests.SimpleTests)", "test_default (model_fields.test_decimalfield.DecimalFieldTests)", "test_filter_with_strings (model_fields.test_decimalfield.DecimalFieldTests)", "test_get_prep_value (model_fields.test_decimalfield.DecimalFieldTests)", "test_lookup... | 4fc35a9c3efdc9154efce28cb23cb84f8834517e | <15 min fix | import ipaddress
import re
from pathlib import Path
from urllib.parse import urlsplit, urlunsplit
from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.functional import SimpleLazyObject
from django.utils.ipv6 import is_valid_ipv6_address
from django.... | [
[
94,
100
]
] | django/core/validators.py | python:3.11 | |
django/django | django__django-10880 | 838e432e3e5519c5383d12018e6c78f8ec7833c1 | diff --git a/django/db/models/aggregates.py b/django/db/models/aggregates.py
--- a/django/db/models/aggregates.py
+++ b/django/db/models/aggregates.py
@@ -68,7 +68,7 @@ def get_group_by_cols(self):
return []
def as_sql(self, compiler, connection, **extra_context):
- extra_context['distinct'] = 'D... | diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py
--- a/tests/aggregation/tests.py
+++ b/tests/aggregation/tests.py
@@ -8,6 +8,7 @@
Avg, Count, DecimalField, DurationField, F, FloatField, Func, IntegerField,
Max, Min, Sum, Value,
)
+from django.db.models.expressions import Case, When
from... | Query syntax error with condition and distinct combination
Description
A Count annotation containing both a Case condition and a distinct=True param produces a query error on Django 2.2 (whatever the db backend). A space is missing at least (... COUNT(DISTINCTCASE WHEN ...).
| Failing test example
Bisected to [bc05547cd8c1dd511c6b6a6c873a1bc63417b111] Fixed #28658 -- Added DISTINCT handling to the Aggregate class. | 2019-01-21T00:22:36Z | 3.0 | ["test_count_distinct_expression (aggregation.tests.AggregateTestCase)"] | ["test_add_implementation (aggregation.tests.AggregateTestCase)", "test_aggregate_alias (aggregation.tests.AggregateTestCase)", "test_aggregate_annotation (aggregation.tests.AggregateTestCase)", "test_aggregate_in_order_by (aggregation.tests.AggregateTestCase)", "test_aggregate_multi_join (aggregation.tests.AggregateTe... | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | """
Classes to represent the definitions of aggregate functions.
"""
from django.core.exceptions import FieldError
from django.db.models.expressions import Case, Func, Star, When
from django.db.models.fields import IntegerField
from django.db.models.functions.mixins import (
FixDurationInputMixin, NumericOutputFiel... | [
[
68,
74
]
] | django/db/models/aggregates.py | python:3.11 |
django/django | django__django-10914 | e7fd69d051eaa67cb17f172a39b57253e9cb831a | diff --git a/django/conf/global_settings.py b/django/conf/global_settings.py
--- a/django/conf/global_settings.py
+++ b/django/conf/global_settings.py
@@ -304,7 +304,7 @@ def gettext_noop(s):
# The numeric mode to set newly-uploaded files to. The value should be a mode
# you'd pass directly to os.chmod; see https:/... | diff --git a/tests/test_utils/tests.py b/tests/test_utils/tests.py
--- a/tests/test_utils/tests.py
+++ b/tests/test_utils/tests.py
@@ -1099,7 +1099,7 @@ def test_override_file_upload_permissions(self):
the file_permissions_mode attribute of
django.core.files.storage.default_storage.
"""
- ... | Set default FILE_UPLOAD_PERMISSION to 0o644.
Description
Hello,
As far as I can see, the File Uploads documentation page does not mention any permission issues.
What I would like to see is a warning that in absence of explicitly configured FILE_UPLOAD_PERMISSIONS, the permissions for a file uploaded to FileSystemSto... | I think you're talking about ef70af77ec53160d5ffa060c1bdf5ed93322d84f (#28540). I guess the question is whether or not that documentation should be duplicated elsewhere.
Thank you Tim, this is precisely what I was looking for! I can only see one issue with the current docs (if you excuse me for bothering you with such ... | 2019-01-30T13:13:20Z | 3.0 | ["test_override_file_upload_permissions (test_utils.tests.OverrideSettingsTests)"] | ["test_allowed_database_chunked_cursor_queries (test_utils.tests.AllowedDatabaseQueriesTests)", "test_allowed_database_queries (test_utils.tests.AllowedDatabaseQueriesTests)", "test_skip_if_db_feature (test_utils.tests.SkippingTestCase)", "test_skip_unless_db_feature (test_utils.tests.SkippingTestCase)", "test_equal_pa... | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | """
Default Django settings. Override these with settings in the module pointed to
by the DJANGO_SETTINGS_MODULE environment variable.
"""
# This is defined here as a do-nothing function because we can't import
# django.utils.translation -- that module depends on the settings.
def gettext_noop(s):
return s
####... | [
[
304,
310
]
] | django/conf/global_settings.py | python:3.11 |
django/django | django__django-10999 | 36300ef336e3f130a0dadc1143163ff3d23dc843 | diff --git a/django/utils/dateparse.py b/django/utils/dateparse.py
--- a/django/utils/dateparse.py
+++ b/django/utils/dateparse.py
@@ -29,9 +29,10 @@
standard_duration_re = re.compile(
r'^'
r'(?:(?P<days>-?\d+) (days?, )?)?'
- r'((?:(?P<hours>-?\d+):)(?=\d+:\d+))?'
- r'(?:(?P<minutes>-?\d+):)?'
- r'... | diff --git a/tests/utils_tests/test_dateparse.py b/tests/utils_tests/test_dateparse.py
--- a/tests/utils_tests/test_dateparse.py
+++ b/tests/utils_tests/test_dateparse.py
@@ -113,9 +113,12 @@ def test_negative(self):
test_values = (
('-4 15:30', timedelta(days=-4, minutes=15, seconds=30)),
... | Fix parse_duration() for some negative durations
Description
The https://docs.djangoproject.com/en/2.1/_modules/django/utils/dateparse/ defines:
standard_duration_re = re.compile(
r'^'
r'(?:(?P<days>-?\d+) (days?, )?)?'
r'((?:(?P<hours>-?\d+):)(?=\d+:\d+))?'
r'(?:(?P<minutes>-?\d+):)?'
r'(?P<seconds>-?\d+)'
r'... | Please give an example valid that's not working. There are some tests for negative values.
Right, this should have been fixed by #27699 which is included in 1.11.x.
Example cases, can be discussed: parse_duration('-00:01:01') => plus 61 seconds, so it is not -(00:01:01) but (-00):(+01):(+01) parse_duration('00:-01:-01... | 2019-02-16T07:44:50Z | 3.0 | ["test_negative (utils_tests.test_dateparse.DurationParseTests)", "test_parse_postgresql_format (utils_tests.test_dateparse.DurationParseTests)"] | ["test_parse_date (utils_tests.test_dateparse.DateParseTests)", "test_parse_datetime (utils_tests.test_dateparse.DateParseTests)", "test_parse_time (utils_tests.test_dateparse.DateParseTests)", "test_days (utils_tests.test_dateparse.DurationParseTests)", "test_fractions_of_seconds (utils_tests.test_dateparse.DurationPa... | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | """Functions to parse datetime objects."""
# We're using regular expressions rather than time.strptime because:
# - They provide both validation and parsing.
# - They're more flexible for datetimes.
# - The date/datetime/time constructors produce friendlier error messages.
import datetime
import re
from django.utils... | [
[
29,
38
]
] | django/utils/dateparse.py | python:3.11 |
django/django | django__django-11066 | 4b45b6c8e4d7c9701a332e80d3b1c84209dc36e2 | diff --git a/django/contrib/contenttypes/management/__init__.py b/django/contrib/contenttypes/management/__init__.py
--- a/django/contrib/contenttypes/management/__init__.py
+++ b/django/contrib/contenttypes/management/__init__.py
@@ -24,7 +24,7 @@ def _rename(self, apps, schema_editor, old_model, new_model):
... | diff --git a/tests/contenttypes_tests/test_operations.py b/tests/contenttypes_tests/test_operations.py
--- a/tests/contenttypes_tests/test_operations.py
+++ b/tests/contenttypes_tests/test_operations.py
@@ -14,11 +14,16 @@
),
)
class ContentTypeOperationsTests(TransactionTestCase):
+ databases = {'default', '... | RenameContentType._rename() doesn't save the content type on the correct database
Description
The commit in question:
https://github.com/django/django/commit/f179113e6cbc8ba0a8d4e87e1d4410fb61d63e75
The specific lines in question:
https://github.com/django/django/blob/586a9dc4295357de1f5ad0590ad34bf2bc008f79/django... | Added a pull request with the fix. https://github.com/django/django/pull/10332
Hi, I spent all afternoon into this ticket. As I am a newbie I failed to make a test for it. And the fix can really be 'using=db' in the .save() method. But I found a StackOverflow answer about transaction.atomic(using=db) that is interesti... | 2019-03-09T13:03:14Z | 3.0 | ["test_existing_content_type_rename_other_database (contenttypes_tests.test_operations.ContentTypeOperationsTests)"] | ["test_content_type_rename_conflict (contenttypes_tests.test_operations.ContentTypeOperationsTests)", "test_existing_content_type_rename (contenttypes_tests.test_operations.ContentTypeOperationsTests)", "test_missing_content_type_rename_ignore (contenttypes_tests.test_operations.ContentTypeOperationsTests)"] | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | from django.apps import apps as global_apps
from django.db import DEFAULT_DB_ALIAS, migrations, router, transaction
from django.db.utils import IntegrityError
class RenameContentType(migrations.RunPython):
def __init__(self, app_label, old_model, new_model):
self.app_label = app_label
self.old_mod... | [
[
24,
30
]
] | django/contrib/contenttypes/management/__init__.py | python:3.11 |
django/django | django__django-11099 | d26b2424437dabeeca94d7900b37d2df4410da0c | diff --git a/django/contrib/auth/validators.py b/django/contrib/auth/validators.py
--- a/django/contrib/auth/validators.py
+++ b/django/contrib/auth/validators.py
@@ -7,7 +7,7 @@
@deconstructible
class ASCIIUsernameValidator(validators.RegexValidator):
- regex = r'^[\w.@+-]+$'
+ regex = r'^[\w.@+-]+\Z'
m... | diff --git a/tests/auth_tests/test_validators.py b/tests/auth_tests/test_validators.py
--- a/tests/auth_tests/test_validators.py
+++ b/tests/auth_tests/test_validators.py
@@ -237,7 +237,7 @@ def test_unicode_validator(self):
invalid_usernames = [
"o'connell", "عبد ال",
"zerowidth\u200... | UsernameValidator allows trailing newline in usernames
Description
ASCIIUsernameValidator and UnicodeUsernameValidator use the regex
r'^[\w.@+-]+$'
The intent is to only allow alphanumeric characters as well as ., @, +, and -. However, a little known quirk of Python regexes is that $ will also match a trailing newli... | 2019-03-20T03:46:18Z | 3.0 | ["test_ascii_validator (auth_tests.test_validators.UsernameValidatorsTests)", "test_unicode_validator (auth_tests.test_validators.UsernameValidatorsTests)", "test_help_text (auth_tests.test_validators.UserAttributeSimilarityValidatorTest)"] | ["test_help_text (auth_tests.test_validators.MinimumLengthValidatorTest)", "test_validate (auth_tests.test_validators.MinimumLengthValidatorTest)", "test_help_text (auth_tests.test_validators.NumericPasswordValidatorTest)", "test_validate (auth_tests.test_validators.NumericPasswordValidatorTest)", "test_validate (auth_... | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | import re
from django.core import validators
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy as _
@deconstructible
class ASCIIUsernameValidator(validators.RegexValidator):
regex = r'^[\w.@+-]+$'
message = _(
'Enter a valid username. This value ma... | [
[
7,
13
],
[
17,
23
]
] | django/contrib/auth/validators.py | python:3.11 | |
django/django | django__django-11119 | d4df5e1b0b1c643fe0fc521add0236764ec8e92a | diff --git a/django/template/engine.py b/django/template/engine.py
--- a/django/template/engine.py
+++ b/django/template/engine.py
@@ -160,7 +160,7 @@ def render_to_string(self, template_name, context=None):
if isinstance(context, Context):
return t.render(context)
else:
- retu... | diff --git a/tests/template_tests/test_engine.py b/tests/template_tests/test_engine.py
--- a/tests/template_tests/test_engine.py
+++ b/tests/template_tests/test_engine.py
@@ -21,6 +21,13 @@ def test_basic_context(self):
'obj:test\n',
)
+ def test_autoescape_off(self):
+ engine = Engine... | Engine.render_to_string() should honor the autoescape attribute
Description
In Engine.render_to_string, a Context is created without specifying the engine autoescape attribute. So if you create en engine with autoescape=False and then call its render_to_string() method, the result will always be autoescaped. It was p... | I'd like to reserve this for an event I'll attend on Oct 4th. | 2019-03-24T21:17:05Z | 3.0 | ["test_autoescape_off (template_tests.test_engine.RenderToStringTest)"] | ["test_cached_loader_priority (template_tests.test_engine.LoaderTests)", "test_loader_priority (template_tests.test_engine.LoaderTests)", "test_origin (template_tests.test_engine.LoaderTests)", "test_basic_context (template_tests.test_engine.RenderToStringTest)", "test_multiple_engines_configured (template_tests.test_e... | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | import functools
from django.core.exceptions import ImproperlyConfigured
from django.utils.functional import cached_property
from django.utils.module_loading import import_string
from .base import Context, Template
from .context import _builtin_context_processors
from .exceptions import TemplateDoesNotExist
from .lib... | [
[
160,
166
]
] | django/template/engine.py | python:3.11 |
django/django | django__django-11133 | 879cc3da6249e920b8d54518a0ae06de835d7373 | diff --git a/django/http/response.py b/django/http/response.py
--- a/django/http/response.py
+++ b/django/http/response.py
@@ -229,7 +229,7 @@ def make_bytes(self, value):
# Handle string types -- we can't rely on force_bytes here because:
# - Python attempts str conversion first
# - when sel... | diff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py
--- a/tests/httpwrappers/tests.py
+++ b/tests/httpwrappers/tests.py
@@ -366,6 +366,10 @@ def test_non_string_content(self):
r.content = 12345
self.assertEqual(r.content, b'12345')
+ def test_memoryview_content(self):
+ ... | HttpResponse doesn't handle memoryview objects
Description
I am trying to write a BinaryField retrieved from the database into a HttpResponse. When the database is Sqlite this works correctly, but Postgresql returns the contents of the field as a memoryview object and it seems like current Django doesn't like this co... | I guess HttpResponseBase.make_bytes could be adapted to deal with memoryview objects by casting them to bytes. In all cases simply wrapping the memoryview in bytes works as a workaround HttpResponse(bytes(model.binary_field)).
The fact make_bytes would still use force_bytes if da56e1bac6449daef9aeab8d076d2594d9fd5b44 ... | 2019-03-27T06:48:09Z | 3.0 | ["test_memoryview_content (httpwrappers.tests.HttpResponseTests)"] | ["test_streaming_response (httpwrappers.tests.StreamingHttpResponseTests)", "test_cookie_edgecases (httpwrappers.tests.CookieTests)", "Semicolons and commas are decoded.", "Semicolons and commas are encoded.", "test_httponly_after_load (httpwrappers.tests.CookieTests)", "test_invalid_cookies (httpwrappers.tests.CookieT... | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | import datetime
import json
import mimetypes
import os
import re
import sys
import time
from email.header import Header
from http.client import responses
from urllib.parse import quote, urlparse
from django.conf import settings
from django.core import signals, signing
from django.core.exceptions import DisallowedRedir... | [
[
229,
235
]
] | django/http/response.py | python:3.11 |
django/django | django__django-11163 | e6588aa4e793b7f56f4cadbfa155b581e0efc59a | diff --git a/django/forms/models.py b/django/forms/models.py
--- a/django/forms/models.py
+++ b/django/forms/models.py
@@ -83,7 +83,7 @@ def model_to_dict(instance, fields=None, exclude=None):
for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many):
if not getattr(f, 'editable', False... | diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py
--- a/tests/model_forms/tests.py
+++ b/tests/model_forms/tests.py
@@ -1814,6 +1814,10 @@ class Meta:
bw = BetterWriter.objects.create(name='Joe Better', score=10)
self.assertEqual(sorted(model_to_dict(bw)), ['id', 'name', 'score', ... | model_to_dict() should return an empty dict for an empty list of fields.
Description
Been called as model_to_dict(instance, fields=[]) function should return empty dict, because no fields were requested. But it returns all fields
The problem point is
if fields and f.name not in fields:
which should be
if fields is no... | model_to_dict() is a part of private API. Do you have any real use case for passing empty list to this method?
PR
This method is comfortable to fetch instance fields values without touching ForeignKey fields. List of fields to be fetched is an attr of the class, which can be overridden in subclasses and is empty list ... | 2019-04-02T21:46:42Z | 3.0 | ["test_modelform_subclassed_model (model_forms.tests.ModelOneToOneFieldTests)"] | ["test_modelform_factory_metaclass (model_forms.tests.CustomMetaclassTestCase)", "test_setattr_raises_validation_error_field_specific (model_forms.tests.StrictAssignmentTests)", "test_setattr_raises_validation_error_non_field (model_forms.tests.StrictAssignmentTests)", "test_notrequired_overrides_notblank (model_forms.... | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | """
Helper functions for creating Form classes from Django models
and database field objects.
"""
from itertools import chain
from django.core.exceptions import (
NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError,
)
from django.forms.fields import ChoiceField, Field
from django.forms.forms impor... | [
[
83,
89
]
] | django/forms/models.py | python:3.11 |
django/django | django__django-11179 | 19fc6376ce67d01ca37a91ef2f55ef769f50513a | diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py
--- a/django/db/models/deletion.py
+++ b/django/db/models/deletion.py
@@ -277,6 +277,7 @@ def delete(self):
if self.can_fast_delete(instance):
with transaction.mark_for_rollback_on_error():
count ... | diff --git a/tests/delete/tests.py b/tests/delete/tests.py
--- a/tests/delete/tests.py
+++ b/tests/delete/tests.py
@@ -1,6 +1,7 @@
from math import ceil
from django.db import IntegrityError, connection, models
+from django.db.models.deletion import Collector
from django.db.models.sql.constants import GET_ITERATOR_... | delete() on instances of models without any dependencies doesn't clear PKs.
Description
Deleting any model with no dependencies not updates the PK on the model. It should be set to None after .delete() call.
See Django.db.models.deletion:276-281. Should update the model line 280.
| Reproduced at 1ffddfc233e2d5139cc6ec31a4ec6ef70b10f87f. Regression in bc7dd8490b882b2cefdc7faf431dc64c532b79c9. Thanks for the report.
Regression test.
I have attached a simple fix which mimics what https://github.com/django/django/blob/master/django/db/models/deletion.py#L324-L326 does for multiple objects. I am not ... | 2019-04-05T15:54:39Z | 3.0 | ["test_fast_delete_instance_set_pk_none (delete.tests.FastDeleteTests)"] | ["test_fast_delete_empty_no_update_can_self_select (delete.tests.FastDeleteTests)", "test_fast_delete_fk (delete.tests.FastDeleteTests)", "test_fast_delete_inheritance (delete.tests.FastDeleteTests)", "test_fast_delete_joined_qs (delete.tests.FastDeleteTests)", "test_fast_delete_large_batch (delete.tests.FastDeleteTest... | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | from collections import Counter
from operator import attrgetter
from django.db import IntegrityError, connections, transaction
from django.db.models import signals, sql
class ProtectedError(IntegrityError):
def __init__(self, msg, protected_objects):
self.protected_objects = protected_objects
sup... | [
[
277,
283
]
] | django/db/models/deletion.py | python:3.11 |
django/django | django__django-11239 | d87bd29c4f8dfcdf3f4a4eb8340e6770a2416fe3 | diff --git a/django/db/backends/postgresql/client.py b/django/db/backends/postgresql/client.py
--- a/django/db/backends/postgresql/client.py
+++ b/django/db/backends/postgresql/client.py
@@ -17,6 +17,10 @@ def runshell_db(cls, conn_params):
dbname = conn_params.get('database', '')
user = conn_params.g... | diff --git a/tests/dbshell/test_postgresql.py b/tests/dbshell/test_postgresql.py
--- a/tests/dbshell/test_postgresql.py
+++ b/tests/dbshell/test_postgresql.py
@@ -14,15 +14,16 @@ def _run_it(self, dbinfo):
That function invokes the runshell command, while mocking
subprocess.run(). It returns a 2-tuple... | Add support for postgresql client certificates and key to dbshell.
Description
This bug is very similar to the #28322
A common security procedure for DB access is to require mutual TLS for the DB connection.
This involves specifying a server certificate, client certificate, and client key when connecting.
Django alre... | 2019-04-16T09:44:54Z | 3.0 | ["test_ssl_certificate (dbshell.test_postgresql.PostgreSqlDbshellCommandTestCase)"] | ["test_accent (dbshell.test_postgresql.PostgreSqlDbshellCommandTestCase)", "test_basic (dbshell.test_postgresql.PostgreSqlDbshellCommandTestCase)", "test_column (dbshell.test_postgresql.PostgreSqlDbshellCommandTestCase)", "test_nopass (dbshell.test_postgresql.PostgreSqlDbshellCommandTestCase)", "SIGINT is ignored in Py... | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | import os
import signal
import subprocess
from django.db.backends.base.client import BaseDatabaseClient
class DatabaseClient(BaseDatabaseClient):
executable_name = 'psql'
@classmethod
def runshell_db(cls, conn_params):
args = [cls.executable_name]
host = conn_params.get('host', '')
... | [
[
17,
26
],
[
34,
47
]
] | django/db/backends/postgresql/client.py | python:3.11 | |
django/django | django__django-11299 | 6866c91b638de5368c18713fa851bfe56253ea55 | diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
--- a/django/db/models/sql/query.py
+++ b/django/db/models/sql/query.py
@@ -1338,7 +1338,7 @@ def _add_q(self, q_object, used_aliases, branch_negated=False,
if isinstance(child, Node):
child_clause, needed_inner = s... | diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py
--- a/tests/migrations/test_operations.py
+++ b/tests/migrations/test_operations.py
@@ -1898,6 +1898,29 @@ def test_add_constraint_percent_escaping(self):
author = Author.objects.create(name='Albert', rebate='10%')
... | CheckConstraint with OR operator generates incorrect SQL on SQLite and Oracle.
Description
(last modified by Michael Spallino)
Django is incorrectly including the fully qualified field name(e.g. “my_table”.”my_field”) in part of the check constraint. This only appears to happen when there is a combination of OR... | Could you confirm this also happens on other backends than SQLite?
PR
The patch changes are looking great. I left a suggestion to simply one the tests assertions to make them easier to parse by a human but they are testing the right thing. | 2019-04-28T11:15:08Z | 3.0 | ["test_simplecol_query (queries.test_query.TestQuery)"] | ["test_reference_field_by_through_fields (migrations.test_operations.FieldOperationTests)", "test_references_field_by_from_fields (migrations.test_operations.FieldOperationTests)", "test_references_field_by_name (migrations.test_operations.FieldOperationTests)", "test_references_field_by_remote_field_model (migrations.... | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | """
Create SQL statements for QuerySets.
The code in here encapsulates all of the SQL construction so that QuerySets
themselves do not have to (and could be backed by things other than SQL
databases). The abstraction barrier only works one way: this module has to know
all about the internals of models in order to get ... | [
[
1338,
1344
]
] | django/db/models/sql/query.py | python:3.11 |
django/django | django__django-11433 | 21b1d239125f1228e579b1ce8d94d4d5feadd2a6 | diff --git a/django/forms/models.py b/django/forms/models.py
--- a/django/forms/models.py
+++ b/django/forms/models.py
@@ -48,8 +48,11 @@ def construct_instance(form, instance, fields=None, exclude=None):
continue
# Leave defaults for fields that aren't in POST data, except for
# checkbox... | diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py
--- a/tests/model_forms/tests.py
+++ b/tests/model_forms/tests.py
@@ -585,6 +585,32 @@ class Meta:
m2 = mf2.save(commit=False)
self.assertEqual(m2.mode, '')
+ def test_default_not_populated_on_non_empty_value_in_cleaned_data(sel... | Allow `cleaned_data` to overwrite fields' default values.
Description
See comments here: https://github.com/django/django/pull/7068/files#r289432409
Currently, when submitting a form, if 'some_field' isn't in the data payload (e.g. it wasn't included in the form, perhaps because its value is derived from another fie... | 2019-05-31T17:06:20Z | 3.0 | ["test_default_not_populated_on_non_empty_value_in_cleaned_data (model_forms.tests.ModelFormBaseTest)"] | ["test_model_form_clean_applies_to_model (model_forms.tests.CustomCleanTests)", "test_override_clean (model_forms.tests.CustomCleanTests)", "test_model_form_applies_localize_to_all_fields (model_forms.tests.LocalizedModelFormTest)", "test_model_form_applies_localize_to_some_fields (model_forms.tests.LocalizedModelFormT... | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | """
Helper functions for creating Form classes from Django models
and database field objects.
"""
from itertools import chain
from django.core.exceptions import (
NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError,
)
from django.forms.fields import ChoiceField, Field
from django.forms.forms impor... | [
[
48,
58
]
] | django/forms/models.py | python:3.11 | |
django/django | django__django-11451 | e065b293878b1e3ea56655aa9d33e87576cd77ff | diff --git a/django/contrib/auth/backends.py b/django/contrib/auth/backends.py
--- a/django/contrib/auth/backends.py
+++ b/django/contrib/auth/backends.py
@@ -39,6 +39,8 @@ class ModelBackend(BaseBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
if username is None:
... | diff --git a/tests/auth_tests/test_auth_backends.py b/tests/auth_tests/test_auth_backends.py
--- a/tests/auth_tests/test_auth_backends.py
+++ b/tests/auth_tests/test_auth_backends.py
@@ -226,6 +226,19 @@ def test_authentication_timing(self):
authenticate(username='no_such_user', password='test')
self.... | ModelBackend.authenticate() shouldn't make a database query when username is None
Description
It's easier to explain my issue by adding a comment in the current implementation of ModelBackend.authenticate():
def authenticate(self, request, username=None, password=None, **kwargs):
if username is None:
username =... | 2019-06-08T19:11:42Z | 3.0 | ["test_authentication_without_credentials (auth_tests.test_auth_backends.ModelBackendTest)", "test_custom_perms (auth_tests.test_auth_backends.ModelBackendTest)", "test_authentication_without_credentials (auth_tests.test_auth_backends.CustomPermissionsUserModelBackendTest)", "test_custom_perms (auth_tests.test_auth_bac... | ["test_raises_exception (auth_tests.test_auth_backends.NoBackendsTest)", "test_get_all_permissions (auth_tests.test_auth_backends.BaseBackendTest)", "test_get_group_permissions (auth_tests.test_auth_backends.BaseBackendTest)", "test_get_user_permissions (auth_tests.test_auth_backends.BaseBackendTest)", "test_has_perm (... | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | import inspect
import warnings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.utils.deprecation import RemovedInDjango31Warning
UserModel = get_user_model()
class BaseBackend:
def authenticate(self, request, **kwargs):
return None
def ge... | [
[
39,
46
]
] | django/contrib/auth/backends.py | python:3.11 | |
django/django | django__django-11490 | a7038adbd02c916315b16939b835f021c2ee8880 | diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py
--- a/django/db/models/sql/compiler.py
+++ b/django/db/models/sql/compiler.py
@@ -426,6 +426,7 @@ def get_combinator_sql(self, combinator, all):
# must have the same columns list. Set the selects defined on
... | diff --git a/tests/queries/test_qs_combinators.py b/tests/queries/test_qs_combinators.py
--- a/tests/queries/test_qs_combinators.py
+++ b/tests/queries/test_qs_combinators.py
@@ -123,6 +123,9 @@ def test_union_with_values(self):
self.assertEqual(reserved_name['order'], 2)
reserved_name = qs1.union(qs1... | Composed queries cannot change the list of columns with values()/values_list().
Description
Composed queries cannot change the list of columns when values()/values_list() is evaluated multiple times, e.g.
>>> ReservedName.objects.create(name='a', order=2)
>>> qs1 = ReservedName.objects.all()
>>> print(qs1.union(qs1).... | 2019-06-19T07:47:46Z | 3.0 | ["test_union_with_values (queries.test_qs_combinators.QuerySetSetOperationTests)"] | ["test_combining_multiple_models (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_count_difference (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_count_intersection (queries.test_qs_combinators.QuerySetSetOperationTests)", "test_count_union (queries.test_qs_combinators.QuerySetSetOperati... | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | import collections
import re
import warnings
from itertools import chain
from django.core.exceptions import EmptyResultSet, FieldError
from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import OrderBy, Random, RawSQL, Ref, Value
from django.db.models.functions import Cast
from django.d... | [
[
426,
432
]
] | django/db/models/sql/compiler.py | python:3.11 | |
django/django | django__django-11555 | 8dd5877f58f84f2b11126afbd0813e24545919ed | diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py
--- a/django/db/models/sql/compiler.py
+++ b/django/db/models/sql/compiler.py
@@ -722,6 +722,9 @@ def find_ordering_name(self, name, opts, alias=None, default_order='ASC',
results = []
for item in opts.ordering:... | diff --git a/tests/ordering/models.py b/tests/ordering/models.py
--- a/tests/ordering/models.py
+++ b/tests/ordering/models.py
@@ -54,6 +54,10 @@ class Meta:
ordering = (models.F('author').asc(nulls_first=True), 'id')
+class ChildArticle(Article):
+ pass
+
+
class Reference(models.Model):
article ... | order_by() a parent model crash when Meta.ordering contains expressions.
Description
(last modified by Jonny Fuller)
Hi friends,
During testing I discovered a strange bug when using a query expression for ordering during multi-table inheritance. You can find the full write up as well as reproducible test reposi... | Thanks for the report. I attached a regression test. Reproduced at c498f088c584ec3aff97409fdc11b39b28240de9.
Regression test.
I *think* I'm getting a similar (or same) error when adding lowercased ordering to a model via meta: class Recipe(models.Model): # ... class Meta: ordering = (Lower('name'),) This works fine in ... | 2019-07-10T18:07:07Z | 3.0 | ["test_order_by_ptr_field_with_default_ordering_by_expression (ordering.tests.OrderingTests)"] | ["test_default_ordering (ordering.tests.OrderingTests)", "F expressions can be used in Meta.ordering.", "test_default_ordering_override (ordering.tests.OrderingTests)", "test_deprecated_values_annotate (ordering.tests.OrderingTests)", "test_extra_ordering (ordering.tests.OrderingTests)", "test_extra_ordering_quoting (o... | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | import collections
import re
import warnings
from itertools import chain
from django.core.exceptions import EmptyResultSet, FieldError
from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import OrderBy, Random, RawSQL, Ref, Value
from django.db.models.functions import Cast
from django.d... | [
[
722,
730
]
] | django/db/models/sql/compiler.py | python:3.11 |
django/django | django__django-11603 | f618e033acd37d59b536d6e6126e6c5be18037f6 | diff --git a/django/db/models/aggregates.py b/django/db/models/aggregates.py
--- a/django/db/models/aggregates.py
+++ b/django/db/models/aggregates.py
@@ -99,6 +99,7 @@ def _get_repr_options(self):
class Avg(FixDurationInputMixin, NumericOutputFieldMixin, Aggregate):
function = 'AVG'
name = 'Avg'
+ allow_... | diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py
--- a/tests/aggregation/tests.py
+++ b/tests/aggregation/tests.py
@@ -388,9 +388,6 @@ def test_count(self):
vals = Book.objects.aggregate(Count("rating"))
self.assertEqual(vals, {"rating__count": 6})
- vals = Book.objects.ag... | Add DISTINCT support for Avg and Sum aggregates.
Description
As an extension of #28658, aggregates should be supported for other general aggregates such as Avg and Sum. Before 2.2, these aggregations just ignored the parameter, but now throw an exception.
This change would just involve setting these classes as allowi... | PR | 2019-07-28T18:14:23Z | 3.0 | ["test_distinct_on_aggregate (aggregation.tests.AggregateTestCase)", "test_empty_aggregate (aggregation.tests.AggregateTestCase)"] | ["test_add_implementation (aggregation.tests.AggregateTestCase)", "test_aggregate_alias (aggregation.tests.AggregateTestCase)", "test_aggregate_annotation (aggregation.tests.AggregateTestCase)", "test_aggregate_in_order_by (aggregation.tests.AggregateTestCase)", "test_aggregate_multi_join (aggregation.tests.AggregateTe... | 419a78300f7cd27611196e1e464d50fd0385ff27 | <15 min fix | """
Classes to represent the definitions of aggregate functions.
"""
from django.core.exceptions import FieldError
from django.db.models.expressions import Case, Func, Star, When
from django.db.models.fields import IntegerField
from django.db.models.functions.mixins import (
FixDurationInputMixin, NumericOutputFiel... | [
[
99,
105
],
[
143,
149
]
] | django/db/models/aggregates.py | python:3.11 |
django/django | django__django-11820 | c2678e49759e5c4c329bff0eeca2886267005d21 | diff --git a/django/db/models/base.py b/django/db/models/base.py
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -1708,9 +1708,15 @@ def _check_ordering(cls):
fld = None
for part in field.split(LOOKUP_SEP):
try:
- fld = _cls._meta.get_field(... | diff --git a/tests/invalid_models_tests/test_models.py b/tests/invalid_models_tests/test_models.py
--- a/tests/invalid_models_tests/test_models.py
+++ b/tests/invalid_models_tests/test_models.py
@@ -814,6 +814,26 @@ class Meta:
)
])
+ def test_ordering_pointing_multiple_times_to_model_fields(... | models.E015 is raised when Meta.ordering contains "pk" of a related field.
Description
models.E015 is raised when Meta.ordering contains __pk of a related field, e.g.:
test_app.SomeModel: (models.E015) 'ordering' refers to the nonexistent field, related field, or lookup 'option__pk'.
Regression in 440505cb2cadbe1a5b9... | Regression test.
Thanks @felixxm for the test. I will prepare a fix for it. | 2019-09-26T08:37:14Z | 3.1 | ["test_ordering_pointing_multiple_times_to_model_fields (invalid_models_tests.test_models.OtherModelTests)", "test_ordering_pointing_to_related_model_pk (invalid_models_tests.test_models.OtherModelTests)"] | ["test_check_constraints (invalid_models_tests.test_models.ConstraintsTests)", "test_check_constraints_required_db_features (invalid_models_tests.test_models.ConstraintsTests)", "test_db_column_clash (invalid_models_tests.test_models.FieldNamesTests)", "test_ending_with_underscore (invalid_models_tests.test_models.Fiel... | 0668164b4ac93a5be79f5b87fae83c657124d9ab | <15 min fix | import copy
import inspect
import warnings
from functools import partialmethod
from itertools import chain
from django.apps import apps
from django.conf import settings
from django.core import checks
from django.core.exceptions import (
NON_FIELD_ERRORS, FieldDoesNotExist, FieldError, MultipleObjectsReturned,
... | [
[
1708,
1722
]
] | django/db/models/base.py | python:3.11 |
django/django | django__django-11880 | 06909fe084f87a65459a83bd69d7cdbe4fce9a7c | diff --git a/django/forms/fields.py b/django/forms/fields.py
--- a/django/forms/fields.py
+++ b/django/forms/fields.py
@@ -199,6 +199,7 @@ def __deepcopy__(self, memo):
result = copy.copy(self)
memo[id(self)] = result
result.widget = copy.deepcopy(self.widget, memo)
+ result.error_mess... | diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py
--- a/tests/forms_tests/tests/test_forms.py
+++ b/tests/forms_tests/tests/test_forms.py
@@ -3685,6 +3685,17 @@ def test_empty_data_files_multi_value_dict(self):
self.assertIsInstance(p.data, MultiValueDict)
self... | Form Field’s __deepcopy__ does not (deep)copy the error messages.
Description
The __deepcopy__ method defined for the formfields (https://github.com/django/django/blob/146086f219d01dbb1cd8c089b5a5667e396e1cc4/django/forms/fields.py#L200) performs a shallow copy of self and does not include additional treatment for t... | Thanks for this report. I attached a simple test. Reproduced at f52022ad96356d4b1061610f2b74ea4d1956a608.
Simple test.
PR | 2019-10-07T19:10:59Z | 3.1 | ["test_field_deep_copy_error_messages (forms_tests.tests.test_forms.FormsTestCase)"] | ["test_attribute_class (forms_tests.tests.test_forms.RendererTests)", "test_attribute_instance (forms_tests.tests.test_forms.RendererTests)", "test_attribute_override (forms_tests.tests.test_forms.RendererTests)", "test_default (forms_tests.tests.test_forms.RendererTests)", "test_kwarg_class (forms_tests.tests.test_for... | 0668164b4ac93a5be79f5b87fae83c657124d9ab | <15 min fix | """
Field classes.
"""
import copy
import datetime
import math
import operator
import os
import re
import uuid
from decimal import Decimal, DecimalException
from io import BytesIO
from urllib.parse import urlsplit, urlunsplit
from django.core import validators
from django.core.exceptions import ValidationError
from d... | [
[
199,
205
]
] | django/forms/fields.py | python:3.11 |
django/django | django__django-11951 | 312049091288dbba2299de8d07ea3e3311ed7238 | diff --git a/django/db/models/query.py b/django/db/models/query.py
--- a/django/db/models/query.py
+++ b/django/db/models/query.py
@@ -1209,7 +1209,8 @@ def _batched_insert(self, objs, fields, batch_size, ignore_conflicts=False):
if ignore_conflicts and not connections[self.db].features.supports_ignore_conflic... | diff --git a/tests/bulk_create/tests.py b/tests/bulk_create/tests.py
--- a/tests/bulk_create/tests.py
+++ b/tests/bulk_create/tests.py
@@ -1,3 +1,4 @@
+from math import ceil
from operator import attrgetter
from django.db import IntegrityError, NotSupportedError, connection
@@ -214,6 +215,14 @@ def test_explicit_bat... | bulk_create batch_size param overrides the compatible batch size calculation
Description
(last modified by Ahmet Kucuk)
At this line: https://github.com/django/django/blob/stable/2.2.x/django/db/models/query.py#L1197
batch_size param overrides compatible batch size calculation. This looks like a bug as bulk_up... | 2019-10-21T09:35:46Z | 3.1 | ["test_explicit_batch_size_respects_max_batch_size (bulk_create.tests.BulkCreateTests)"] | ["test_batch_same_vals (bulk_create.tests.BulkCreateTests)", "test_bulk_insert_expressions (bulk_create.tests.BulkCreateTests)", "test_bulk_insert_nullable_fields (bulk_create.tests.BulkCreateTests)", "test_efficiency (bulk_create.tests.BulkCreateTests)", "test_empty_model (bulk_create.tests.BulkCreateTests)", "test_ex... | 0668164b4ac93a5be79f5b87fae83c657124d9ab | <15 min fix | """
The main QuerySet implementation. This provides the public API for the ORM.
"""
import copy
import operator
import warnings
from collections import namedtuple
from functools import lru_cache
from itertools import chain
from django.conf import settings
from django.core import exceptions
from django.db import (
... | [
[
1209,
1216
]
] | django/db/models/query.py | python:3.11 | |
django/django | django__django-11964 | fc2b1cc926e34041953738e58fa6ad3053059b22 | diff --git a/django/db/models/enums.py b/django/db/models/enums.py
--- a/django/db/models/enums.py
+++ b/django/db/models/enums.py
@@ -60,7 +60,13 @@ def values(cls):
class Choices(enum.Enum, metaclass=ChoicesMeta):
"""Class for creating enumerated choices."""
- pass
+
+ def __str__(self):
+ """
+ ... | diff --git a/tests/model_enums/tests.py b/tests/model_enums/tests.py
--- a/tests/model_enums/tests.py
+++ b/tests/model_enums/tests.py
@@ -143,6 +143,12 @@ class Fruit(models.IntegerChoices):
APPLE = 1, 'Apple'
PINEAPPLE = 1, 'Pineapple'
+ def test_str(self):
+ for test in ... | The value of a TextChoices/IntegerChoices field has a differing type
Description
If we create an instance of a model having a CharField or IntegerField with the keyword choices pointing to IntegerChoices or TextChoices, the value returned by the getter of the field will be of the same type as the one created by enum.... | Hi NyanKiyoshi, what a lovely report. Thank you. Clearly :) the expected behaviour is that test_created_object_is_str should pass. It's interesting that the underlying __dict__ values differ, which explains all I guess: Created: {'_state': <django.db.models.base.ModelState object at 0x10730efd0>, 'id': 1, 'my_str_value... | 2019-10-23T14:16:45Z | 3.1 | ["test_str (model_enums.tests.ChoicesTests)", "test_textchoices (model_enums.tests.ChoicesTests)"] | ["test_integerchoices (model_enums.tests.ChoicesTests)", "test_integerchoices_auto_label (model_enums.tests.ChoicesTests)", "test_integerchoices_containment (model_enums.tests.ChoicesTests)", "test_integerchoices_empty_label (model_enums.tests.ChoicesTests)", "test_integerchoices_functional_api (model_enums.tests.Choic... | 0668164b4ac93a5be79f5b87fae83c657124d9ab | <15 min fix | import enum
from django.utils.functional import Promise
__all__ = ['Choices', 'IntegerChoices', 'TextChoices']
class ChoicesMeta(enum.EnumMeta):
"""A metaclass for creating a enum choices."""
def __new__(metacls, classname, bases, classdict):
labels = []
for key in classdict._member_names:
... | [
[
60,
72
]
] | django/db/models/enums.py | python:3.11 |
django/django | django__django-12125 | 89d41cba392b759732ba9f1db4ff29ed47da6a56 | diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py
--- a/django/db/migrations/serializer.py
+++ b/django/db/migrations/serializer.py
@@ -269,7 +269,7 @@ def serialize(self):
if module == builtins.__name__:
return self.value.__name__, set()
els... | diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py
--- a/tests/migrations/test_writer.py
+++ b/tests/migrations/test_writer.py
@@ -26,6 +26,11 @@
from .models import FoodManager, FoodQuerySet
+class DeconstructibleInstances:
+ def deconstruct(self):
+ return ('DeconstructibleI... | makemigrations produces incorrect path for inner classes
Description
When you define a subclass from django.db.models.Field as an inner class of some other class, and use this field inside a django.db.models.Model class, then when you run manage.py makemigrations, a migrations file is created which refers to the inne... | This should be possible to do by relying on __qualname__ (instead of __name__) now that master is Python 3 only.
PR
I think we should focus on using __qualname__ during migration serialization as well instead of simply solving the field subclasses case.
In fb0f987: Fixed #27914 -- Added support for nested classes in F... | 2019-11-22T12:55:45Z | 3.1 | ["test_serialize_nested_class (migrations.test_writer.WriterTests)", "test_serialize_numbers (migrations.test_writer.WriterTests)"] | ["test_args_kwargs_signature (migrations.test_writer.OperationWriterTests)", "test_args_signature (migrations.test_writer.OperationWriterTests)", "test_empty_signature (migrations.test_writer.OperationWriterTests)", "test_expand_args_signature (migrations.test_writer.OperationWriterTests)", "test_kwargs_signature (migr... | 0668164b4ac93a5be79f5b87fae83c657124d9ab | <15 min fix | import builtins
import collections.abc
import datetime
import decimal
import enum
import functools
import math
import re
import types
import uuid
from django.conf import SettingsReference
from django.db import models
from django.db.migrations.operations.base import Operation
from django.db.migrations.utils import COMP... | [
[
269,
275
]
] | django/db/migrations/serializer.py | python:3.11 |
django/django | django__django-12193 | 3fb7c12158a2402f0f80824f6778112071235803 | diff --git a/django/forms/widgets.py b/django/forms/widgets.py
--- a/django/forms/widgets.py
+++ b/django/forms/widgets.py
@@ -522,9 +522,7 @@ def format_value(self, value):
def get_context(self, name, value, attrs):
if self.check_test(value):
- if attrs is None:
- attrs = {}
-... | diff --git a/tests/forms_tests/widget_tests/test_checkboxinput.py b/tests/forms_tests/widget_tests/test_checkboxinput.py
--- a/tests/forms_tests/widget_tests/test_checkboxinput.py
+++ b/tests/forms_tests/widget_tests/test_checkboxinput.py
@@ -89,3 +89,8 @@ def test_value_from_datadict_string_int(self):
def test_va... | SplitArrayField with BooleanField always has widgets checked after the first True value.
Description
(last modified by Peter Andersen)
When providing a SplitArrayField BooleanField with preexisting data, the final_attrs dict is updated to include 'checked': True after the for loop has reached the first True val... | Changes available here: https://github.com/django/django/pull/12193
Thanks for the report. Reproduced at 5708327c3769262b845730996ca2784245ada4d1. | 2019-12-08T01:38:25Z | 3.1 | ["test_get_context_does_not_mutate_attrs (forms_tests.widget_tests.test_checkboxinput.CheckboxInputTest)"] | ["test_render_check_exception (forms_tests.widget_tests.test_checkboxinput.CheckboxInputTest)", "test_render_check_test (forms_tests.widget_tests.test_checkboxinput.CheckboxInputTest)", "test_render_empty (forms_tests.widget_tests.test_checkboxinput.CheckboxInputTest)", "test_render_false (forms_tests.widget_tests.test... | 0668164b4ac93a5be79f5b87fae83c657124d9ab | <15 min fix | """
HTML Widget classes
"""
import copy
import datetime
import warnings
from collections import defaultdict
from itertools import chain
from django.conf import settings
from django.forms.utils import to_current_timezone
from django.templatetags.static import static
from django.utils import datetime_safe, formats
from... | [
[
522,
528
]
] | django/forms/widgets.py | python:3.11 |
django/django | django__django-12209 | 5a68f024987e6d16c2626a31bf653a2edddea579 | diff --git a/django/db/models/base.py b/django/db/models/base.py
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -849,6 +849,7 @@ def _save_table(self, raw=False, cls=None, force_insert=False,
updated = False
# Skip an UPDATE when adding an instance and primary key has a default.
... | diff --git a/tests/serializers/models/data.py b/tests/serializers/models/data.py
--- a/tests/serializers/models/data.py
+++ b/tests/serializers/models/data.py
@@ -4,6 +4,8 @@
NULL values, where allowed.
The basic idea is to have a model for each Django data type.
"""
+import uuid
+
from django.contrib.contenttypes.... | Change in behaviour when saving a model instance with an explcit pk value if the pk field has a default
Description
(last modified by Reupen Shah)
Consider the following model:
from uuid import uuid4
from django.db import models
class Sample(models.Model):
id = models.UUIDField(primary_key=True, default=uuid4)... | It looks like the logic in _save_table should not force an insert if an explicit pk value is provided. The logic should likely take pk_set into account if ( not pk_set and self._state.adding and self._meta.pk.default and self._meta.pk.default is not NOT_PROVIDED ): force_insert = True I'm surprised this was not caught... | 2019-12-12T04:11:05Z | 3.1 | ["partial(func, *args, **keywords) - new function with partial application"] | [] | 0668164b4ac93a5be79f5b87fae83c657124d9ab | <15 min fix | import copy
import inspect
import warnings
from functools import partialmethod
from itertools import chain
from django.apps import apps
from django.conf import settings
from django.core import checks
from django.core.exceptions import (
NON_FIELD_ERRORS, FieldDoesNotExist, FieldError, MultipleObjectsReturned,
... | [
[
849,
855
]
] | django/db/models/base.py | python:3.11 |
django/django | django__django-12276 | 53d8646f799de7f92ab9defe9dc56c6125448102 | diff --git a/django/forms/widgets.py b/django/forms/widgets.py
--- a/django/forms/widgets.py
+++ b/django/forms/widgets.py
@@ -387,6 +387,9 @@ def value_from_datadict(self, data, files, name):
def value_omitted_from_data(self, data, files, name):
return name not in files
+ def use_required_attribute(... | diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py
--- a/tests/forms_tests/tests/test_forms.py
+++ b/tests/forms_tests/tests/test_forms.py
@@ -8,11 +8,11 @@
from django.core.validators import MaxValueValidator, RegexValidator
from django.forms import (
BooleanField, CharFi... | FileInput shouldn't display required attribute when initial data exists.
Description
(last modified by thenewguy)
I think that ClearableFileInput.use_required_attribute() (https://github.com/django/django/blob/e703b93a656b78b9b444bb3a9980e305ed002a70/django/forms/widgets.py#L454) should be moved to FileInput.u... | This might explain better: from django import forms from django.core.files.base import ContentFile from django.test import SimpleTestCase class FileForm(forms.Form): file = forms.FileField(widget=forms.FileInput) class FileInputRenderTest(SimpleTestCase): def test_file_input(self): form = FileForm() field = form['file'... | 2020-01-05T08:04:40Z | 3.1 | ["test_use_required_attribute (forms_tests.widget_tests.test_fileinput.FileInputTest)", "test_filefield_with_fileinput_required (forms_tests.tests.test_forms.FormsTestCase)"] | ["test_attribute_class (forms_tests.tests.test_forms.RendererTests)", "test_attribute_instance (forms_tests.tests.test_forms.RendererTests)", "test_attribute_override (forms_tests.tests.test_forms.RendererTests)", "test_default (forms_tests.tests.test_forms.RendererTests)", "test_kwarg_class (forms_tests.tests.test_for... | 0668164b4ac93a5be79f5b87fae83c657124d9ab | <15 min fix | """
HTML Widget classes
"""
import copy
import datetime
import warnings
from collections import defaultdict
from itertools import chain
from django.conf import settings
from django.forms.utils import to_current_timezone
from django.templatetags.static import static
from django.utils import datetime_safe, formats
from... | [
[
387,
395
],
[
454,
459
]
] | django/forms/widgets.py | python:3.11 |
django/django | django__django-12304 | 4c1b401e8250f9f520b3c7dc369554477ce8b15a | diff --git a/django/db/models/enums.py b/django/db/models/enums.py
--- a/django/db/models/enums.py
+++ b/django/db/models/enums.py
@@ -31,6 +31,7 @@ def __new__(metacls, classname, bases, classdict):
# that is passed in as "self" as the value to use when looking up the
# label in the choices.
... | diff --git a/tests/model_enums/tests.py b/tests/model_enums/tests.py
--- a/tests/model_enums/tests.py
+++ b/tests/model_enums/tests.py
@@ -4,6 +4,7 @@
import uuid
from django.db import models
+from django.template import Context, Template
from django.test import SimpleTestCase
from django.utils.functional import ... | Enumeration Types are not usable in templates.
Description
(last modified by Mariusz Felisiak)
The new enumeration types are great but can't be used in Django templates due to their being callable. For example this doesn't work:
{% if student.year_in_school == YearInSchool.FRESHMAN %}
This is because YearInSch... | 2020-01-09T15:43:51Z | 3.1 | ["test_templates (model_enums.tests.ChoicesTests)"] | ["test_integerchoices (model_enums.tests.ChoicesTests)", "test_integerchoices_auto_label (model_enums.tests.ChoicesTests)", "test_integerchoices_containment (model_enums.tests.ChoicesTests)", "test_integerchoices_empty_label (model_enums.tests.ChoicesTests)", "test_integerchoices_functional_api (model_enums.tests.Choic... | 0668164b4ac93a5be79f5b87fae83c657124d9ab | <15 min fix | import enum
from django.utils.functional import Promise
__all__ = ['Choices', 'IntegerChoices', 'TextChoices']
class ChoicesMeta(enum.EnumMeta):
"""A metaclass for creating a enum choices."""
def __new__(metacls, classname, bases, classdict):
labels = []
for key in classdict._member_names:
... | [
[
31,
37
]
] | django/db/models/enums.py | python:3.11 | |
django/django | django__django-12308 | 2e0f04507b17362239ba49830d26fec504d46978 | diff --git a/django/contrib/admin/utils.py b/django/contrib/admin/utils.py
--- a/django/contrib/admin/utils.py
+++ b/django/contrib/admin/utils.py
@@ -398,6 +398,11 @@ def display_for_field(value, field, empty_value_display):
return formats.number_format(value)
elif isinstance(field, models.FileField) and... | diff --git a/tests/admin_utils/tests.py b/tests/admin_utils/tests.py
--- a/tests/admin_utils/tests.py
+++ b/tests/admin_utils/tests.py
@@ -176,6 +176,23 @@ def test_null_display_for_field(self):
display_value = display_for_field(None, models.FloatField(), self.empty_value)
self.assertEqual(display_val... | JSONField are not properly displayed in admin when they are readonly.
Description
JSONField values are displayed as dict when readonly in the admin.
For example, {"foo": "bar"} would be displayed as {'foo': 'bar'}, which is not valid JSON.
I believe the fix would be to add a special case in django.contrib.admin.utils... | PR
The proposed patch is problematic as the first version coupled contrib.postgres with .admin and the current one is based off the type name which is brittle and doesn't account for inheritance. It might be worth waiting for #12990 to land before proceeding here as the patch will be able to simply rely of django.db.m... | 2020-01-12T04:21:15Z | 3.1 | ["test_json_display_for_field (admin_utils.tests.UtilsTests)", "test_label_for_field (admin_utils.tests.UtilsTests)"] | ["test_cyclic (admin_utils.tests.NestedObjectsTests)", "test_non_added_parent (admin_utils.tests.NestedObjectsTests)", "test_on_delete_do_nothing (admin_utils.tests.NestedObjectsTests)", "test_queries (admin_utils.tests.NestedObjectsTests)", "test_relation_on_abstract (admin_utils.tests.NestedObjectsTests)", "test_sibl... | 0668164b4ac93a5be79f5b87fae83c657124d9ab | <15 min fix | import datetime
import decimal
from collections import defaultdict
from django.core.exceptions import FieldDoesNotExist
from django.db import models, router
from django.db.models.constants import LOOKUP_SEP
from django.db.models.deletion import Collector
from django.forms.utils import pretty_name
from django.urls impo... | [
[
398,
408
]
] | django/contrib/admin/utils.py | python:3.11 |
django/django | django__django-12419 | 7fa1a93c6c8109010a6ff3f604fda83b604e0e97 | diff --git a/django/conf/global_settings.py b/django/conf/global_settings.py
--- a/django/conf/global_settings.py
+++ b/django/conf/global_settings.py
@@ -637,6 +637,6 @@ def gettext_noop(s):
SECURE_HSTS_PRELOAD = False
SECURE_HSTS_SECONDS = 0
SECURE_REDIRECT_EXEMPT = []
-SECURE_REFERRER_POLICY = None
+SECURE_REFERR... | diff --git a/tests/project_template/test_settings.py b/tests/project_template/test_settings.py
--- a/tests/project_template/test_settings.py
+++ b/tests/project_template/test_settings.py
@@ -38,6 +38,7 @@ def test_middleware_headers(self):
self.assertEqual(headers, [
b'Content-Length: 0',
... | Add secure default SECURE_REFERRER_POLICY / Referrer-policy header
Description
#29406 added the ability for the SECURE_REFERRER_POLICY setting to set Referrer-Policy, released in Django 3.0.
I propose we change the default for this to "same-origin" to make Django applications leak less information to third party site... | Hi Adam, Yes, I think this fits our secure by default philosophy. As long as the BC is documented in the release notes I think we should have this. | 2020-02-05T10:02:56Z | 3.1 | ["test_middleware_headers (project_template.test_settings.TestStartProjectSettings)"] | [] | 0668164b4ac93a5be79f5b87fae83c657124d9ab | <15 min fix | """
Default Django settings. Override these with settings in the module pointed to
by the DJANGO_SETTINGS_MODULE environment variable.
"""
# This is defined here as a do-nothing function because we can't import
# django.utils.translation -- that module depends on the settings.
def gettext_noop(s):
return s
####... | [
[
637,
642
]
] | django/conf/global_settings.py | python:3.11 |
django/django | django__django-13023 | f83b44075dafa429d59e8755aa47e15577cc49f9 | diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
--- a/django/db/models/fields/__init__.py
+++ b/django/db/models/fields/__init__.py
@@ -1501,7 +1501,7 @@ def to_python(self, value):
return self.context.create_decimal_from_float(value)
try:
return... | diff --git a/tests/model_fields/test_decimalfield.py b/tests/model_fields/test_decimalfield.py
--- a/tests/model_fields/test_decimalfield.py
+++ b/tests/model_fields/test_decimalfield.py
@@ -21,9 +21,24 @@ def test_to_python(self):
# Uses default rounding of ROUND_HALF_EVEN.
self.assertEqual(f.to_pyth... | DecimalField.to_python() raises TypeError on dict values.
Description
A call to DecimalField.to_python() with a dictionary as the value parameter produces TypeError instead of ValidationError. This is a problem, for example, when you try to save a model object, and a decimal field got set to a dictionary by mistake. ... | 2020-06-04T20:40:44Z | 3.2 | ["test_invalid_value (model_fields.test_decimalfield.DecimalFieldTests)", "test_lookup_really_big_value (model_fields.test_decimalfield.DecimalFieldTests)"] | ["test_default (model_fields.test_decimalfield.DecimalFieldTests)", "test_filter_with_strings (model_fields.test_decimalfield.DecimalFieldTests)", "test_get_prep_value (model_fields.test_decimalfield.DecimalFieldTests)", "test_max_decimal_places_validation (model_fields.test_decimalfield.DecimalFieldTests)", "test_max_... | 65dfb06a1ab56c238cc80f5e1c31f61210c4577d | <15 min fix | import collections.abc
import copy
import datetime
import decimal
import operator
import uuid
import warnings
from base64 import b64decode, b64encode
from functools import partialmethod, total_ordering
from django import forms
from django.apps import apps
from django.conf import settings
from django.core import checks... | [
[
1501,
1507
]
] | django/db/models/fields/__init__.py | python:3.11 | |
django/django | django__django-13089 | 27c09043da52ca1f02605bf28600bfd5ace95ae4 | diff --git a/django/core/cache/backends/db.py b/django/core/cache/backends/db.py
--- a/django/core/cache/backends/db.py
+++ b/django/core/cache/backends/db.py
@@ -267,9 +267,12 @@ def _cull(self, db, cursor, now):
cursor.execute(
connection.ops.cache_key_culling_sql() % table,
... | diff --git a/tests/cache/tests.py b/tests/cache/tests.py
--- a/tests/cache/tests.py
+++ b/tests/cache/tests.py
@@ -621,6 +621,20 @@ def test_cull(self):
def test_zero_cull(self):
self._perform_cull_test('zero_cull', 50, 19)
+ def test_cull_delete_when_store_empty(self):
+ try:
+ cul... | cache.backends.db._cull sometimes fails with 'NoneType' object is not subscriptable
Description
(last modified by Guillermo Bonvehí)
I'm sporadically getting some cache errors using database backend.
The error is: 'NoneType' object is not subscriptable
And the backtrace:
/usr/local/lib/python3.7/site-packages/d... | 2020-06-20T07:36:10Z | 3.2 | ["test_cull_delete_when_store_empty (cache.tests.DBCacheTests)", "test_cull_delete_when_store_empty (cache.tests.DBCacheWithTimeZoneTests)"] | ["If None is cached, get() returns it instead of the default.", "Nonexistent cache keys return as None/default.", "set_many() returns an empty list when all keys are inserted.", "test_custom_key_validation (cache.tests.CustomCacheKeyValidationTests)", "test_long_vary_on (cache.tests.TestMakeTemplateFragmentKey)", "test... | 65dfb06a1ab56c238cc80f5e1c31f61210c4577d | <15 min fix | "Database cache backend."
import base64
import pickle
from datetime import datetime
from django.conf import settings
from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache
from django.db import DatabaseError, connections, models, router, transaction
from django.utils import timezone
class Options:
... | [
[
267,
278
]
] | django/core/cache/backends/db.py | python:3.11 | |
django/django | django__django-13109 | fbe82f82555bc25dccb476c749ca062f0b522be3 | diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
--- a/django/db/models/fields/related.py
+++ b/django/db/models/fields/related.py
@@ -914,7 +914,7 @@ def validate(self, value, model_instance):
return
using = router.db_for_read(self.remote_field.model, instanc... | diff --git a/tests/model_forms/models.py b/tests/model_forms/models.py
--- a/tests/model_forms/models.py
+++ b/tests/model_forms/models.py
@@ -28,8 +28,17 @@ def __repr__(self):
return self.__str__()
+class WriterManager(models.Manager):
+ def get_queryset(self):
+ qs = super().get_queryset()
+ ... | ForeignKey.validate() should validate using the base manager.
Description
ForeignKey.validate() should validate using the base manager instead of the default manager.
Consider the models:
class ArticleManager(models.Manage):
def get_queryset(self):
qs = super().get_queryset()
return qs.filter(archived=False)
cla... | https://github.com/django/django/pull/12923
OK, yes, let's provisionally Accept this: I think it's probably correct. (At this level we're avoiding DB errors, not business logic errors, like "was this archived", which properly belong to the form layer...)
I take it the change here is ORM rather than forms per se.
I tak... | 2020-06-25T08:36:45Z | 3.2 | ["test_FK_validates_using_base_manager (validation.tests.BaseModelValidationTests)", "test_validate_foreign_key_to_model_with_overridden_manager (model_forms.tests.ModelFormBasicTests)"] | ["test_model_form_clean_applies_to_model (model_forms.tests.CustomCleanTests)", "test_override_clean (model_forms.tests.CustomCleanTests)", "test_setattr_raises_validation_error_field_specific (model_forms.tests.StrictAssignmentTests)", "test_setattr_raises_validation_error_non_field (model_forms.tests.StrictAssignment... | 65dfb06a1ab56c238cc80f5e1c31f61210c4577d | <15 min fix | import functools
import inspect
from functools import partial
from django import forms
from django.apps import apps
from django.conf import SettingsReference, settings
from django.core import checks, exceptions
from django.db import connection, router
from django.db.backends import utils
from django.db.models import Q... | [
[
914,
920
]
] | django/db/models/fields/related.py | python:3.11 |
django/django | django__django-13112 | 09914ccf688974e068941f55412b930729bafa06 | diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
--- a/django/db/models/fields/related.py
+++ b/django/db/models/fields/related.py
@@ -582,7 +582,11 @@ def deconstruct(self):
if self.remote_field.parent_link:
kwargs['parent_link'] = self.remote_field.parent_link... | diff --git a/tests/migrations/test_state.py b/tests/migrations/test_state.py
--- a/tests/migrations/test_state.py
+++ b/tests/migrations/test_state.py
@@ -867,6 +867,34 @@ class Meta:
with self.assertRaisesMessage(ValueError, msg):
project_state.apps
+ def test_reference_mixed_case_app_label(... | makemigrations crashes for ForeignKey with mixed-case app name.
Description
When i run "python3 manage.py migrate" on Django 3.1b1 shows me that error (Please, note that the code works well in 3.0)
ValueError: The field DJ_RegLogin.Content.category was declared with a lazy reference to 'dj_reglogin.category', but app... | Thanks for the report. Regression in 9e1b6b8a66af4c2197e5b1b41eb9dbb36e4f6502. Reproduced at fbe82f82555bc25dccb476c749ca062f0b522be3.
Potential fix: diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index d517d7269b..894d931d50 100644 --- a/django/db/models/fields/related.py +++ b/dj... | 2020-06-26T04:51:38Z | 3.2 | ["test_reference_mixed_case_app_label (migrations.test_state.StateTests)"] | ["test_abstract_model_children_inherit_indexes (migrations.test_state.ModelStateTests)", "test_bound_field_sanity_check (migrations.test_state.ModelStateTests)", "test_create_swappable (migrations.test_state.ModelStateTests)", "test_create_swappable_from_abstract (migrations.test_state.ModelStateTests)", "test_custom_m... | 65dfb06a1ab56c238cc80f5e1c31f61210c4577d | <15 min fix | import functools
import inspect
from functools import partial
from django import forms
from django.apps import apps
from django.conf import SettingsReference, settings
from django.core import checks, exceptions
from django.db import connection, router
from django.db.backends import utils
from django.db.models import Q... | [
[
582,
592
]
] | django/db/models/fields/related.py | python:3.11 |
django/django | django__django-13297 | 8954f255bbf5f4ee997fd6de62cb50fc9b5dd697 | diff --git a/django/views/generic/base.py b/django/views/generic/base.py
--- a/django/views/generic/base.py
+++ b/django/views/generic/base.py
@@ -11,7 +11,7 @@
from django.urls import reverse
from django.utils.decorators import classonlymethod
from django.utils.deprecation import RemovedInDjango40Warning
-from djan... | diff --git a/tests/generic_views/test_base.py b/tests/generic_views/test_base.py
--- a/tests/generic_views/test_base.py
+++ b/tests/generic_views/test_base.py
@@ -3,7 +3,8 @@
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponse
from django.test import (
- RequestFactory, Si... | TemplateView.get_context_data()'s kwargs returns SimpleLazyObjects that causes a crash when filtering.
Description
Example Code that works in 3.0, but not in 3.1:
class OfferView(TemplateView):
template_name = "offers/offer.html"
def get_context_data(self, **kwargs):
offer_slug = kwargs.get("offer_slug", "")
of... | Thanks for the report. get_object_or_404() and QuerySet.filter() with SimpleLazyObject throw the same exception in Django 2.2 or 3.0. TemplateView.get_context_data()'s kwargs returns SimpleLazyObjects in Django 3.1 which causes a crash. Passing URL kwargs into context is deprecated (see #19878) but should still work in... | 2020-08-12T11:20:33Z | 3.2 | ["test_template_params_filtering (generic_views.test_base.DeprecationTests)"] | ["test_get_context_data_super (generic_views.test_base.GetContextDataTest)", "test_object_at_custom_name_in_context_data (generic_views.test_base.GetContextDataTest)", "test_object_in_get_context_data (generic_views.test_base.GetContextDataTest)", "test_overwrite_queryset (generic_views.test_base.UseMultipleObjectMixin... | 65dfb06a1ab56c238cc80f5e1c31f61210c4577d | <15 min fix | import logging
import warnings
from functools import update_wrapper
from django.core.exceptions import ImproperlyConfigured
from django.http import (
HttpResponse, HttpResponseGone, HttpResponseNotAllowed,
HttpResponsePermanentRedirect, HttpResponseRedirect,
)
from django.template.response import TemplateRespo... | [
[
11,
17
],
[
169,
174
],
[
177,
183
]
] | django/views/generic/base.py | python:3.11 |
django/django | django__django-13363 | 76e0151ea0e0f56dca66cee846a78b89346d2c4c | diff --git a/django/db/models/functions/datetime.py b/django/db/models/functions/datetime.py
--- a/django/db/models/functions/datetime.py
+++ b/django/db/models/functions/datetime.py
@@ -292,7 +292,7 @@ class TruncDate(TruncBase):
def as_sql(self, compiler, connection):
# Cast to date rather than truncate... | diff --git a/tests/db_functions/datetime/test_extract_trunc.py b/tests/db_functions/datetime/test_extract_trunc.py
--- a/tests/db_functions/datetime/test_extract_trunc.py
+++ b/tests/db_functions/datetime/test_extract_trunc.py
@@ -1124,14 +1124,24 @@ def test_trunc_timezone_applied_before_truncation(self):
mod... | Add support for tzinfo parameter to TruncDate() and TruncTime().
Description
(last modified by Joe Jackson)
Description
TruncDate inherits from TruncBase, which includes the TimeZone mixin. This should allow a developer to pass in a tzinfo object to be used when converting TruncDate, but it actually uses the re... | Please check https://code.djangoproject.com/ticket/31640 Is it related to your issue?
Replying to Serhii Romanov: Please check https://code.djangoproject.com/ticket/31640 Is it related to your issue? It is related, but not exactly my issue. That patch updates the TruncBase as_sql method, and world work. But the TruncDa... | 2020-08-29T18:59:41Z | 3.2 | ["test_trunc_timezone_applied_before_truncation (db_functions.datetime.test_extract_trunc.DateFunctionWithTimeZoneTests)"] | ["test_extract_day_func (db_functions.datetime.test_extract_trunc.DateFunctionTests)", "test_extract_duration_unsupported_lookups (db_functions.datetime.test_extract_trunc.DateFunctionTests)", "test_extract_duration_without_native_duration_field (db_functions.datetime.test_extract_trunc.DateFunctionTests)", "test_extra... | 65dfb06a1ab56c238cc80f5e1c31f61210c4577d | <15 min fix | from datetime import datetime
from django.conf import settings
from django.db.models.expressions import Func
from django.db.models.fields import (
DateField, DateTimeField, DurationField, Field, IntegerField, TimeField,
)
from django.db.models.lookups import (
Transform, YearExact, YearGt, YearGte, YearLt, Yea... | [
[
292,
298
],
[
305,
311
]
] | django/db/models/functions/datetime.py | python:3.11 |
django/django | django__django-13406 | 84609b3205905097d7d3038d32e6101f012c0619 | diff --git a/django/db/models/query.py b/django/db/models/query.py
--- a/django/db/models/query.py
+++ b/django/db/models/query.py
@@ -210,6 +210,8 @@ def query(self):
@query.setter
def query(self, value):
+ if value.values_select:
+ self._iterable_class = ValuesIterable
self._que... | diff --git a/tests/queryset_pickle/tests.py b/tests/queryset_pickle/tests.py
--- a/tests/queryset_pickle/tests.py
+++ b/tests/queryset_pickle/tests.py
@@ -11,7 +11,7 @@
class PickleabilityTestCase(TestCase):
@classmethod
def setUpTestData(cls):
- Happening.objects.create() # make sure the defaults ar... | Queryset with values()/values_list() crashes when recreated from a pickled query.
Description
I am pickling query objects (queryset.query) for later re-evaluation as per https://docs.djangoproject.com/en/2.2/ref/models/querysets/#pickling-querysets. However, when I tried to rerun a query that combines values and ann... | It seems that I have found the culprit. The queryset has an attribute _iterable_class, which in case of a .objects.all() type of query is ModelIterable, but when .values() is used, it should be ValuesIterable. Unfortunately, this is an attribute of the queryset, not of the query and thus it does not get pickled and unp... | 2020-09-10T12:38:11Z | 3.2 | ["test_annotation_values (queryset_pickle.tests.PickleabilityTestCase)", "test_annotation_values_list (queryset_pickle.tests.PickleabilityTestCase)", "test_annotation_with_callable_default (queryset_pickle.tests.PickleabilityTestCase)"] | ["test_in_lookup_query_evaluation (queryset_pickle.tests.InLookupTests)", "test_in_lookup_queryset_evaluation (queryset_pickle.tests.InLookupTests)", "test_datetime_callable_default_all (queryset_pickle.tests.PickleabilityTestCase)", "test_datetime_callable_default_filter (queryset_pickle.tests.PickleabilityTestCase)",... | 65dfb06a1ab56c238cc80f5e1c31f61210c4577d | <15 min fix | """
The main QuerySet implementation. This provides the public API for the ORM.
"""
import copy
import operator
import warnings
from collections import namedtuple
from functools import lru_cache
from itertools import chain
import django
from django.conf import settings
from django.core import exceptions
from django.d... | [
[
210,
217
]
] | django/db/models/query.py | python:3.11 |
django/django | django__django-13410 | 580a4341cb0b4cbfc215a70afc004875a7e815f4 | diff --git a/django/core/files/locks.py b/django/core/files/locks.py
--- a/django/core/files/locks.py
+++ b/django/core/files/locks.py
@@ -107,9 +107,12 @@ def unlock(f):
return True
else:
def lock(f, flags):
- ret = fcntl.flock(_fd(f), flags)
- return ret == 0
+ ... | diff --git a/tests/files/tests.py b/tests/files/tests.py
--- a/tests/files/tests.py
+++ b/tests/files/tests.py
@@ -8,7 +8,7 @@
from pathlib import Path
from unittest import mock
-from django.core.files import File
+from django.core.files import File, locks
from django.core.files.base import ContentFile
from djang... | Bug in posix implementation of django/core/files/locks.py
Description
The posix version of locks (the version which supports import fcntl) has a bug. The code attempts to return True to indicate success or failure acquiring a lock, but instead it always returns False. The reason is that cpython fcntl module returns N... | Thanks for the ticket. Would you like to prepare a pull request? (tests are also required). | 2020-09-11T09:58:41Z | 3.2 | ["test_exclusive_lock (files.tests.FileTests)", "test_shared_lock (files.tests.FileTests)"] | ["test_open_resets_file_to_start_and_returns_context_manager (files.tests.InMemoryUploadedFileTests)", "test_content_file_custom_name (files.tests.ContentFileTestCase)", "test_content_file_default_name (files.tests.ContentFileTestCase)", "test_content_file_input_type (files.tests.ContentFileTestCase)", "test_open_reset... | 65dfb06a1ab56c238cc80f5e1c31f61210c4577d | <15 min fix | """
Portable file locking utilities.
Based partially on an example by Jonathan Feignberg in the Python
Cookbook [1] (licensed under the Python Software License) and a ctypes port by
Anatoly Techtonik for Roundup [2] (license [3]).
[1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203
[2] https://sourcefor... | [
[
107,
118
]
] | django/core/files/locks.py | python:3.11 |
django/django | django__django-13417 | 71ae1ab0123582cc5bfe0f7d5f4cc19a9412f396 | diff --git a/django/db/models/query.py b/django/db/models/query.py
--- a/django/db/models/query.py
+++ b/django/db/models/query.py
@@ -1224,7 +1224,12 @@ def ordered(self):
return True
if self.query.extra_order_by or self.query.order_by:
return True
- elif self.query.default_or... | diff --git a/tests/queries/tests.py b/tests/queries/tests.py
--- a/tests/queries/tests.py
+++ b/tests/queries/tests.py
@@ -2084,6 +2084,16 @@ def test_annotated_ordering(self):
self.assertIs(qs.ordered, False)
self.assertIs(qs.order_by('num_notes').ordered, True)
+ def test_annotated_default_orde... | QuerySet.ordered property is incorrect for GROUP BY queries on models with Meta.ordering.
Description
Using the annotate function on a queryset doesn't keep the default ordering set in model's meta class.
A property should say whether the queryset will be ordered or not. I wanted to use the qs.ordered property for th... | Thanks for this report, however QuerySet.ordered works for me, see tests.
Replying to felixxm: Thanks for this report, however QuerySet.ordered works for me, see tests. Thanks for your answer but I've just checked again as it is in my example and ordered still returns True if an annotation is applied. As said earlier... | 2020-09-14T07:49:15Z | 3.2 | ["test_annotated_default_ordering (queries.tests.QuerysetOrderedTests)", "test_annotated_values_default_ordering (queries.tests.QuerysetOrderedTests)"] | ["test_no_extra_params (queries.tests.DefaultValuesInsertTest)", "test_ticket14729 (queries.tests.RawQueriesTests)", "test_exists (queries.tests.ExistsSql)", "test_ticket_18414 (queries.tests.ExistsSql)", "test_ticket_24278 (queries.tests.TestTicket24279)", "test_ticket7371 (queries.tests.CustomPkTests)", "test_ticket_... | 65dfb06a1ab56c238cc80f5e1c31f61210c4577d | <15 min fix | """
The main QuerySet implementation. This provides the public API for the ORM.
"""
import copy
import operator
import warnings
from collections import namedtuple
from functools import lru_cache
from itertools import chain
import django
from django.conf import settings
from django.core import exceptions
from django.d... | [
[
1224,
1235
]
] | django/db/models/query.py | python:3.11 |
django/django | django__django-13551 | 7f9e4524d6b23424cf44fbe1bf1f4e70f6bb066e | diff --git a/django/contrib/auth/tokens.py b/django/contrib/auth/tokens.py
--- a/django/contrib/auth/tokens.py
+++ b/django/contrib/auth/tokens.py
@@ -78,9 +78,9 @@ def _make_token_with_timestamp(self, user, timestamp, legacy=False):
def _make_hash_value(self, user, timestamp):
"""
- Hash the use... | diff --git a/tests/auth_tests/models/__init__.py b/tests/auth_tests/models/__init__.py
--- a/tests/auth_tests/models/__init__.py
+++ b/tests/auth_tests/models/__init__.py
@@ -8,6 +8,7 @@
from .no_password import NoPasswordUser
from .proxy import Proxy, UserProxy
from .uuid_pk import UUIDUser
+from .with_custom_email... | Changing user's email could invalidate password reset tokens
Description
Sequence:
Have account with email address foo@…
Password reset request for that email (unused)
foo@… account changes their email address
Password reset email is used
The password reset email's token should be rejected at that point, but in fact ... | 2020-10-17T17:22:01Z | 3.2 | ["Updating the user email address invalidates the token.", "test_token_with_different_secret (auth_tests.test_tokens.TokenGeneratorTest)"] | ["test_str (auth_tests.test_models.GroupTests)", "test_group_natural_key (auth_tests.test_models.NaturalKeysTestCase)", "test_user_natural_key (auth_tests.test_models.NaturalKeysTestCase)", "test_check_password (auth_tests.test_models.AnonymousUserTests)", "test_delete (auth_tests.test_models.AnonymousUserTests)", "tes... | 65dfb06a1ab56c238cc80f5e1c31f61210c4577d | <15 min fix | from datetime import datetime
from django.conf import settings
from django.utils.crypto import constant_time_compare, salted_hmac
from django.utils.http import base36_to_int, int_to_base36
class PasswordResetTokenGenerator:
"""
Strategy object used to generate and check tokens for the password
reset mech... | [
[
78,
86
],
[
94,
102
]
] | django/contrib/auth/tokens.py | python:3.11 | |
django/django | django__django-13741 | d746f28949c009251a8741ba03d156964050717f | diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py
--- a/django/contrib/auth/forms.py
+++ b/django/contrib/auth/forms.py
@@ -56,16 +56,9 @@ class ReadOnlyPasswordHashField(forms.Field):
def __init__(self, *args, **kwargs):
kwargs.setdefault("required", False)
+ kwargs.setdef... | diff --git a/tests/auth_tests/test_forms.py b/tests/auth_tests/test_forms.py
--- a/tests/auth_tests/test_forms.py
+++ b/tests/auth_tests/test_forms.py
@@ -1022,6 +1022,7 @@ def test_render(self):
def test_readonly_field_has_changed(self):
field = ReadOnlyPasswordHashField()
+ self.assertIs(field.... | Set disabled prop on ReadOnlyPasswordHashField
Description
Currently the django.contrib.auth.forms.UserChangeForm defines a clean_password method that returns the initial password value to prevent (accidental) changes to the password value. It is also documented that custom forms for the User model need to define thi... | Sounds good. Would you like to provide a patch?
Replying to Mariusz Felisiak: Sounds good. Would you like to provide a patch? I don't have the time to do a proper patch (with doc changes and additional tests). But I marked it as "Easy pickings" to entice others that are trying to get into contribution to Django ;-)
I'd... | 2020-12-02T10:52:52Z | 3.2 | ["test_readonly_field_has_changed (auth_tests.test_forms.ReadOnlyPasswordHashTest)"] | ["test_field_order (auth_tests.test_forms.PasswordChangeFormTest)", "test_html_autocomplete_attributes (auth_tests.test_forms.PasswordChangeFormTest)", "test_incorrect_password (auth_tests.test_forms.PasswordChangeFormTest)", "test_password_verification (auth_tests.test_forms.PasswordChangeFormTest)", "test_password_wh... | 65dfb06a1ab56c238cc80f5e1c31f61210c4577d | <15 min fix | import unicodedata
from django import forms
from django.contrib.auth import (
authenticate, get_user_model, password_validation,
)
from django.contrib.auth.hashers import (
UNUSABLE_PASSWORD_PREFIX, identify_hasher,
)
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_to... | [
[
56,
64
],
[
156,
161
]
] | django/contrib/auth/forms.py | python:3.11 |
django/django | django__django-13794 | fe886eee36be8022f34cfe59aa61ff1c21fe01d9 | diff --git a/django/utils/functional.py b/django/utils/functional.py
--- a/django/utils/functional.py
+++ b/django/utils/functional.py
@@ -176,6 +176,12 @@ def __mod__(self, rhs):
return str(self) % rhs
return self.__cast() % rhs
+ def __add__(self, other):
+ return sel... | diff --git a/tests/template_tests/filter_tests/test_add.py b/tests/template_tests/filter_tests/test_add.py
--- a/tests/template_tests/filter_tests/test_add.py
+++ b/tests/template_tests/filter_tests/test_add.py
@@ -2,6 +2,7 @@
from django.template.defaultfilters import add
from django.test import SimpleTestCase
+fr... | add filter is unable to concatenate strings with lazy string
Description
If you try to concatenate a string with a lazy string with the add template filter, the result is always the empty string because the add filter generates an exception (TypeError: can only concatenate str (not "__proxy__") to str).
| Tests.
Thanks. I attached a test. | 2020-12-19T20:09:34Z | 3.2 | ["test_lazy_add (utils_tests.test_functional.FunctionalTests)", "test_add08 (template_tests.filter_tests.test_add.AddTests)", "test_add09 (template_tests.filter_tests.test_add.AddTests)"] | ["test_add (template_tests.filter_tests.test_add.FunctionTests)", "cached_property caches its value and behaves like a property.", "test_cached_property_auto_name (utils_tests.test_functional.FunctionalTests)", "Disallow this case because the decorated function wouldn't be cached.", "test_cached_property_reuse_same_nam... | 65dfb06a1ab56c238cc80f5e1c31f61210c4577d | <15 min fix | import copy
import itertools
import operator
from functools import total_ordering, wraps
class cached_property:
"""
Decorator that converts a method with a single self argument into a
property cached on the instance.
A cached property can be made out of an existing method:
(e.g. ``url = cached_pr... | [
[
176,
187
]
] | django/utils/functional.py | python:3.11 |
django/django | django__django-13807 | 89fc144dedc737a79929231438f035b1d4a993c9 | diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py
--- a/django/db/backends/sqlite3/base.py
+++ b/django/db/backends/sqlite3/base.py
@@ -327,19 +327,24 @@ def check_constraints(self, table_names=None):
violations = cursor.execute('PRAGMA foreign_key_check').fetchal... | diff --git a/tests/backends/models.py b/tests/backends/models.py
--- a/tests/backends/models.py
+++ b/tests/backends/models.py
@@ -140,3 +140,11 @@ class Author(models.Model):
class Book(models.Model):
author = models.ForeignKey(Author, models.CASCADE, to_field='name')
+
+
+class SQLKeywordsModel(models.Model):... | loaddata crashes on SQLite when table names are SQL keywords.
Description
Steps to reproduce:
Create a Model called Order. (order is a SQL reserved word)
Create fixtures for the model
Use manage.py loaddata to load the fixture.
Notice that it fails with the following error. This is because the table name order is not... | Thanks for the report, I was able to reproduce this issue with db_table = 'order'. Reproduced at 966b5b49b6521483f1c90b4499c4c80e80136de3.
Simply wrapping table_name in connection.ops.quote_name should address the issue for anyone interested in picking the issue up.
a little guidance needed as this is my first ticket.
... | 2020-12-23T21:09:32Z | 3.2 | ["test_check_constraints_sql_keywords (backends.tests.FkConstraintsTests)"] | ["Sequence names are correct when resetting generic relations (Ref #13941)", "test_parameter_escaping (backends.tests.EscapingChecks)", "test_paramless_no_escaping (backends.tests.EscapingChecks)", "An executemany call with too many/not enough parameters will raise an exception (Refs #12612)", "test_paramless_no_escapi... | 65dfb06a1ab56c238cc80f5e1c31f61210c4577d | <15 min fix | """
SQLite backend for the sqlite3 module in the standard library.
"""
import datetime
import decimal
import functools
import hashlib
import math
import operator
import random
import re
import statistics
import warnings
from itertools import chain
from sqlite3 import dbapi2 as Database
import pytz
from django.core.ex... | [
[
327,
350
]
] | django/db/backends/sqlite3/base.py | python:3.11 |
django/django | django__django-13821 | e64c1d8055a3e476122633da141f16b50f0c4a2d | diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py
--- a/django/db/backends/sqlite3/base.py
+++ b/django/db/backends/sqlite3/base.py
@@ -64,8 +64,10 @@ def list_aggregate(function):
def check_sqlite_version():
- if Database.sqlite_version_info < (3, 8, 3):
- raise Improp... | diff --git a/tests/backends/sqlite/tests.py b/tests/backends/sqlite/tests.py
--- a/tests/backends/sqlite/tests.py
+++ b/tests/backends/sqlite/tests.py
@@ -30,9 +30,9 @@ class Tests(TestCase):
longMessage = True
def test_check_sqlite_version(self):
- msg = 'SQLite 3.8.3 or later is required (found 3.8... | Drop support for SQLite < 3.9.0
Description
(last modified by Tim Graham)
Indexes on expressions (see #26167) and the SQLITE_ENABLE_JSON1 compile-time option are supported on SQLite 3.9.0+.
Ubuntu Xenial ships with SQLite 3.11.0 (which will still by supported by Django) and will EOL in April 2021. Debian Jessi... | 2020-12-29T15:16:10Z | 3.2 | ["test_check_sqlite_version (backends.sqlite.tests.Tests)"] | ["test_parameter_escaping (backends.sqlite.tests.EscapingChecksDebug)", "test_parameter_escaping (backends.sqlite.tests.EscapingChecks)", "test_no_interpolation (backends.sqlite.tests.LastExecutedQueryTest)", "test_parameter_quoting (backends.sqlite.tests.LastExecutedQueryTest)", "Raise NotSupportedError when aggregati... | 65dfb06a1ab56c238cc80f5e1c31f61210c4577d | <15 min fix | """
SQLite backend for the sqlite3 module in the standard library.
"""
import datetime
import decimal
import functools
import hashlib
import math
import operator
import random
import re
import statistics
import warnings
from itertools import chain
from sqlite3 import dbapi2 as Database
import pytz
from django.core.ex... | [
[
64,
73
]
] | django/db/backends/sqlite3/base.py | python:3.11 | |
django/django | django__django-13933 | 42e8cf47c7ee2db238bf91197ea398126c546741 | diff --git a/django/forms/models.py b/django/forms/models.py
--- a/django/forms/models.py
+++ b/django/forms/models.py
@@ -1284,7 +1284,11 @@ def to_python(self, value):
value = getattr(value, key)
value = self.queryset.get(**{key: value})
except (ValueError, TypeError, self.query... | diff --git a/tests/forms_tests/tests/test_error_messages.py b/tests/forms_tests/tests/test_error_messages.py
--- a/tests/forms_tests/tests/test_error_messages.py
+++ b/tests/forms_tests/tests/test_error_messages.py
@@ -308,3 +308,16 @@ def test_modelchoicefield(self):
self.assertFormErrors(['REQUIRED'], f.clea... | ModelChoiceField does not provide value of invalid choice when raising ValidationError
Description
(last modified by Aaron Wiegel)
Compared with ChoiceField and others, ModelChoiceField does not show the value of the invalid choice when raising a validation error. Passing in parameters with the invalid value an... | This message has been the same literally forever b2b6fc8e3c78671c8b6af2709358c3213c84d119. Given that ChoiceField passes the value when raising the error, if you set error_messages you should be able to get the result you want.
Replying to Carlton Gibson: This message has been the same literally forever b2b6fc8e3c786... | 2021-01-26T03:58:23Z | 4.0 | ["test_modelchoicefield_value_placeholder (forms_tests.tests.test_error_messages.ModelChoiceFieldErrorMessagesTestCase)"] | ["test_modelchoicefield (forms_tests.tests.test_error_messages.ModelChoiceFieldErrorMessagesTestCase)", "test_booleanfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_charfield (forms_tests.tests.test_error_messages.FormsErrorMessagesTestCase)", "test_choicefield (forms_tests.tests.test_e... | 475cffd1d64c690cdad16ede4d5e81985738ceb4 | <15 min fix | """
Helper functions for creating Form classes from Django models
and database field objects.
"""
from itertools import chain
from django.core.exceptions import (
NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError,
)
from django.forms.fields import ChoiceField, Field
from django.forms.forms import... | [
[
1284,
1294
]
] | django/forms/models.py | python:3.11 |
django/django | django__django-14089 | d01709aae21de9cd2565b9c52f32732ea28a2d98 | diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py
--- a/django/utils/datastructures.py
+++ b/django/utils/datastructures.py
@@ -25,6 +25,9 @@ def discard(self, item):
def __iter__(self):
return iter(self.dict)
+ def __reversed__(self):
+ return reversed(self.dict)
+
... | diff --git a/tests/utils_tests/test_datastructures.py b/tests/utils_tests/test_datastructures.py
--- a/tests/utils_tests/test_datastructures.py
+++ b/tests/utils_tests/test_datastructures.py
@@ -1,7 +1,7 @@
"""
Tests for stuff in django.utils.datastructures.
"""
-
+import collections.abc
import copy
import pickle
... | Allow calling reversed() on an OrderedSet
Description
Currently, OrderedSet isn't reversible (i.e. allowed to be passed as an argument to Python's reversed()). This would be natural to support given that OrderedSet is ordered. This should be straightforward to add by adding a __reversed__() method to OrderedSet.
| 2021-03-06T20:51:08Z | 4.0 | ["test_reversed (utils_tests.test_datastructures.OrderedSetTests)"] | ["test_copy (utils_tests.test_datastructures.CaseInsensitiveMappingTests)", "test_create_with_invalid_key (utils_tests.test_datastructures.CaseInsensitiveMappingTests)", "test_create_with_invalid_values (utils_tests.test_datastructures.CaseInsensitiveMappingTests)", "test_del (utils_tests.test_datastructures.CaseInsens... | 475cffd1d64c690cdad16ede4d5e81985738ceb4 | <15 min fix | import copy
from collections.abc import Mapping
class OrderedSet:
"""
A set which keeps the ordering of the inserted items.
"""
def __init__(self, iterable=None):
self.dict = dict.fromkeys(iterable or ())
def add(self, item):
self.dict[item] = None
def remove(self, item):
... | [
[
25,
33
]
] | django/utils/datastructures.py | python:3.11 | |
django/django | django__django-14373 | b1a4b1f0bdf05adbd3dc4dde14228e68da54c1a3 | diff --git a/django/utils/dateformat.py b/django/utils/dateformat.py
--- a/django/utils/dateformat.py
+++ b/django/utils/dateformat.py
@@ -313,8 +313,8 @@ def y(self):
return '%02d' % (self.data.year % 100)
def Y(self):
- "Year, 4 digits; e.g. '1999'"
- return self.data.year
+ """Ye... | diff --git a/tests/utils_tests/test_dateformat.py b/tests/utils_tests/test_dateformat.py
--- a/tests/utils_tests/test_dateformat.py
+++ b/tests/utils_tests/test_dateformat.py
@@ -166,7 +166,7 @@ def test_r_format_with_non_en_locale(self):
'Sun, 08 Jul 1979 22:00:00 +0100',
)
- def tes... | DateFormat.Y() is not zero-padded.
Description
The Y specifier for django.utils.dateformat.DateFormat is supposed to always return a four-digit year padded with zeros. This doesn't seem to be the case for year < 1000.
| 2021-05-10T14:40:32Z | 4.0 | ["test_Y_format_year_before_1000 (utils_tests.test_dateformat.DateFormatTests)"] | ["test_am_pm (utils_tests.test_dateformat.DateFormatTests)", "test_date (utils_tests.test_dateformat.DateFormatTests)", "test_date_formats (utils_tests.test_dateformat.DateFormatTests)", "test_dateformat (utils_tests.test_dateformat.DateFormatTests)", "test_datetime_with_local_tzinfo (utils_tests.test_dateformat.DateFo... | 475cffd1d64c690cdad16ede4d5e81985738ceb4 | <15 min fix | """
PHP date() style date formatting
See http://www.php.net/date for format strings
Usage:
>>> import datetime
>>> d = datetime.datetime.now()
>>> df = DateFormat(d)
>>> print(df.format('jS F Y H:i'))
7th October 2003 11:39
>>>
"""
import calendar
import datetime
import time
from email.utils import format_datetime as ... | [
[
313,
320
]
] | django/utils/dateformat.py | python:3.11 | |
django/django | django__django-14404 | de32fe83a2e4a20887972c69a0693b94eb25a88b | diff --git a/django/contrib/admin/sites.py b/django/contrib/admin/sites.py
--- a/django/contrib/admin/sites.py
+++ b/django/contrib/admin/sites.py
@@ -420,14 +420,13 @@ def autocomplete_view(self, request):
def catch_all_view(self, request, url):
if settings.APPEND_SLASH and not url.endswith('/'):
... | diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py
--- a/tests/admin_views/tests.py
+++ b/tests/admin_views/tests.py
@@ -6602,6 +6602,42 @@ def test_missing_slash_append_slash_true(self):
response = self.client.get(known_url[:-1])
self.assertRedirects(response, known_url, status_code... | catch_all_view() does not support FORCE_SCRIPT_NAME.
Description
(last modified by SlavaSkvortsov)
catch_all_view returns redirect to '%s/' % request.path_info (script name cut off there) instead of '%s/' % request.path (with the script name)
Patch - https://github.com/django/django/pull/14404
| 2021-05-17T11:24:06Z | 4.0 | ["test_missing_slash_append_slash_true_force_script_name (admin_views.tests.AdminSiteFinalCatchAllPatternTests)", "test_missing_slash_append_slash_true_script_name (admin_views.tests.AdminSiteFinalCatchAllPatternTests)"] | ["test_explicitly_provided_pk (admin_views.tests.GetFormsetsWithInlinesArgumentTest)", "test_implicitly_generated_pk (admin_views.tests.GetFormsetsWithInlinesArgumentTest)", "test_should_be_able_to_edit_related_objects_on_add_view (admin_views.tests.AdminCustomSaveRelatedTests)", "test_should_be_able_to_edit_related_ob... | 475cffd1d64c690cdad16ede4d5e81985738ceb4 | <15 min fix | import re
from functools import update_wrapper
from weakref import WeakSet
from django.apps import apps
from django.conf import settings
from django.contrib.admin import ModelAdmin, actions
from django.contrib.admin.views.autocomplete import AutocompleteJsonView
from django.contrib.auth import REDIRECT_FIELD_NAME
from... | [
[
420,
432
]
] | django/contrib/admin/sites.py | python:3.11 | |
django/django | django__django-14493 | 7272e1963ffdf39c1d4fe225d5425a45dd095d11 | diff --git a/django/contrib/staticfiles/storage.py b/django/contrib/staticfiles/storage.py
--- a/django/contrib/staticfiles/storage.py
+++ b/django/contrib/staticfiles/storage.py
@@ -260,6 +260,7 @@ def post_process(self, paths, dry_run=False, **options):
processed_adjustable_paths[name] = (name, hashe... | diff --git a/tests/staticfiles_tests/storage.py b/tests/staticfiles_tests/storage.py
--- a/tests/staticfiles_tests/storage.py
+++ b/tests/staticfiles_tests/storage.py
@@ -97,3 +97,7 @@ class ExtraPatternsStorage(ManifestStaticFilesStorage):
class NoneHashStorage(ManifestStaticFilesStorage):
def file_hash(self, na... | ManifestStaticFilesStorage crashes with max_post_process_passes = 0.
Description
To reproduce:
Derive a custom class from ManifestStaticFilesStorage and set max_post_process_passes to 0:
class MyManifestStaticFilesStorage(ManifestStaticFilesStorage):
max_post_process_passes = 0
# settings.py
STATICFILES_STORAGE = "M... | An effective workaround is overriding patterns = (). It might not be worth fixing the UnboundLocalError.
I think it's worth fixing.
Hi guys, Can I work on this?
Replying to kingliar420: Can I work on this? Sure there is no need to ask. Please remember that a regression test is required. | 2021-06-05T12:50:25Z | 4.0 | ["test_collectstatistic_no_post_process_replaced_paths (staticfiles_tests.test_storage.TestCollectionNoPostProcessReplacedPaths)"] | ["test_hashed_name (staticfiles_tests.test_storage.TestCollectionNoneHashStorage)", "With storage classes having several file extension patterns, only the", "test_collect_static_files_default_permissions (staticfiles_tests.test_storage.TestStaticFilePermissions)", "test_collect_static_files_permissions (staticfiles_tes... | 475cffd1d64c690cdad16ede4d5e81985738ceb4 | <15 min fix | import hashlib
import json
import os
import posixpath
import re
from urllib.parse import unquote, urldefrag, urlsplit, urlunsplit
from django.conf import settings
from django.contrib.staticfiles.utils import check_settings, matches_patterns
from django.core.exceptions import ImproperlyConfigured
from django.core.files... | [
[
260,
266
]
] | django/contrib/staticfiles/storage.py | python:3.11 |
django/django | django__django-14534 | 910ecd1b8df7678f45c3d507dde6bcb1faafa243 | diff --git a/django/forms/boundfield.py b/django/forms/boundfield.py
--- a/django/forms/boundfield.py
+++ b/django/forms/boundfield.py
@@ -277,7 +277,7 @@ def template_name(self):
@property
def id_for_label(self):
- return 'id_%s_%s' % (self.data['name'], self.data['index'])
+ return self.data... | diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py
--- a/tests/forms_tests/tests/test_forms.py
+++ b/tests/forms_tests/tests/test_forms.py
@@ -720,7 +720,7 @@ class BeatleForm(Form):
fields = list(BeatleForm(auto_id=False)['name'])
self.assertEqual(len(fields), ... | BoundWidget.id_for_label ignores id set by ChoiceWidget.options
Description
If you look at the implementation of BoundField.subwidgets
class BoundField:
...
def subwidgets(self):
id_ = self.field.widget.attrs.get('id') or self.auto_id
attrs = {'id': id_} if id_ else {}
attrs = self.build_widget_attrs(attrs)
... | Hey Jacob — Sounds right: I didn't look in-depth but, if you can put your example in a test case it will be clear enough in the PR. Thanks.
Thanks Carlton, I will create a pull request asap.
Here is a pull request fixing this bug: https://github.com/django/django/pull/14533 (closed without merging)
Here is the new pul... | 2021-06-17T15:37:34Z | 4.0 | ["If auto_id is provided when initializing the form, the generated ID in", "test_iterable_boundfield_select (forms_tests.tests.test_forms.FormsTestCase)"] | ["test_attribute_class (forms_tests.tests.test_forms.RendererTests)", "test_attribute_instance (forms_tests.tests.test_forms.RendererTests)", "test_attribute_override (forms_tests.tests.test_forms.RendererTests)", "test_default (forms_tests.tests.test_forms.RendererTests)", "test_kwarg_class (forms_tests.tests.test_for... | 475cffd1d64c690cdad16ede4d5e81985738ceb4 | <15 min fix | import re
from django.core.exceptions import ValidationError
from django.forms.utils import flatatt, pretty_name
from django.forms.widgets import Textarea, TextInput
from django.utils.functional import cached_property
from django.utils.html import conditional_escape, format_html, html_safe
from django.utils.safestring... | [
[
277,
283
]
] | django/forms/boundfield.py | python:3.11 |
django/django | django__django-14539 | 6a5ef557f80a8eb6a758ebe99c8bb477ca47459e | diff --git a/django/utils/html.py b/django/utils/html.py
--- a/django/utils/html.py
+++ b/django/utils/html.py
@@ -283,8 +283,9 @@ def trim_punctuation(lead, middle, trail):
middle_unescaped = html.unescape(middle)
stripped = middle_unescaped.rstrip(TRAILING_PUNCTUATION_CHARS)
if ... | diff --git a/tests/utils_tests/test_html.py b/tests/utils_tests/test_html.py
--- a/tests/utils_tests/test_html.py
+++ b/tests/utils_tests/test_html.py
@@ -250,6 +250,10 @@ def test_urlize(self):
'Search for google.com/?q=! and see.',
'Search for <a href="http://google.com/?q=">google.c... | urlize() does not handle html escaped string and trailing punctuation correctly
Description
Example:
urlize('Search for google.com/?q=1<! and see.')
# expected output
'Search for <a href="http://google.com/?q=1%3C">google.com/?q=1<</a>! and see.'
# actual output
'Search for <a href="http://google.com/?q=1%3C">goo... | https://github.com/django/django/pull/14539/
OK, thanks, the example looks right. It's always delicate but let's take this for review. Related to #26193. | 2021-06-19T11:31:16Z | 4.0 | ["test_urlize (utils_tests.test_html.TestUtilsHtml)", "test_urlize_unchanged_inputs (utils_tests.test_html.TestUtilsHtml)"] | ["test_conditional_escape (utils_tests.test_html.TestUtilsHtml)", "test_escape (utils_tests.test_html.TestUtilsHtml)", "test_escapejs (utils_tests.test_html.TestUtilsHtml)", "test_format_html (utils_tests.test_html.TestUtilsHtml)", "test_html_safe (utils_tests.test_html.TestUtilsHtml)", "test_html_safe_defines_html_err... | 475cffd1d64c690cdad16ede4d5e81985738ceb4 | <15 min fix | """HTML utilities suitable for global use."""
import html
import json
import re
from html.parser import HTMLParser
from urllib.parse import (
parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit,
)
from django.utils.encoding import punycode
from django.utils.functional import Promise, keep_lazy, keep_lazy_t... | [
[
283,
291
]
] | django/utils/html.py | python:3.11 |
django/django | django__django-14580 | 36fa071d6ebd18a61c4d7f1b5c9d17106134bd44 | diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py
--- a/django/db/migrations/serializer.py
+++ b/django/db/migrations/serializer.py
@@ -273,7 +273,7 @@ def _format(self):
class TypeSerializer(BaseSerializer):
def serialize(self):
special_cases = [
- (models.M... | diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py
--- a/tests/migrations/test_writer.py
+++ b/tests/migrations/test_writer.py
@@ -658,6 +658,13 @@ def test_serialize_functools_partialmethod(self):
def test_serialize_type_none(self):
self.assertSerializedEqual(type(None))
+ ... | Missing import statement in generated migration (NameError: name 'models' is not defined)
Description
I found a bug in Django's latest release: 3.2.4.
Given the following contents of models.py:
from django.db import models
class MyField(models.TextField):
pass
class MyBaseModel(models.Model):
class Meta:
abstrac... | I could reproduce the issue with 3.2.4, 2.2.24 and the main branch. For what it's worth, the issue doesn't occur if the class MyModel does inherit from MyMixin.
MyBaseModel is not necessary to reproduce this issue, it's due to the fact that MyModel doesn't have fields from django.db.models and has custom bases. It look... | 2021-07-01T07:38:03Z | 4.0 | ["test_serialize_type_model (migrations.test_writer.WriterTests)"] | ["test_args_kwargs_signature (migrations.test_writer.OperationWriterTests)", "test_args_signature (migrations.test_writer.OperationWriterTests)", "test_empty_signature (migrations.test_writer.OperationWriterTests)", "test_expand_args_signature (migrations.test_writer.OperationWriterTests)", "test_kwargs_signature (migr... | 475cffd1d64c690cdad16ede4d5e81985738ceb4 | <15 min fix | import builtins
import collections.abc
import datetime
import decimal
import enum
import functools
import math
import os
import pathlib
import re
import types
import uuid
from django.conf import SettingsReference
from django.db import models
from django.db.migrations.operations.base import Operation
from django.db.mig... | [
[
273,
279
]
] | django/db/migrations/serializer.py | python:3.11 |
django/django | django__django-14608 | 7f33c1e22dbc34a7afae7967783725b10f1f13b1 | diff --git a/django/forms/formsets.py b/django/forms/formsets.py
--- a/django/forms/formsets.py
+++ b/django/forms/formsets.py
@@ -333,7 +333,7 @@ def full_clean(self):
self._non_form_errors.
"""
self._errors = []
- self._non_form_errors = self.error_class()
+ self._non_form_err... | diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py
--- a/tests/admin_views/tests.py
+++ b/tests/admin_views/tests.py
@@ -3348,7 +3348,10 @@ def test_non_form_errors_is_errorlist(self):
response = self.client.post(reverse('admin:admin_views_person_changelist'), data)
non_form_errors =... | Add `nonform` CSS class for non form errors in FormSets
Description
(last modified by Ties Jan Hefting)
Forms add the nonfield CSS class for non field errors in ErrorList instances. This is documented in a section on rendering form error messages. Similarly, in FormSets I'd expect to see the nonform CSS class ... | Seems reasonable (similar to #11776).
PR | 2021-07-07T19:51:30Z | 4.0 | ["If validate_max is set and max_num is less than TOTAL_FORMS in the", "If validate_min is set and min_num is more than TOTAL_FORMS in the", "test_non_form_errors (forms_tests.tests.test_formsets.FormsFormsetTestCase)", "test_non_form_errors_is_errorlist (admin_views.tests.AdminViewListEditable)"] | ["all_valid() validates all forms, even when some are invalid.", "test_valid (forms_tests.tests.test_formsets.AllValidTests)", "is_multipart() works with an empty formset.", "An empty formset still calls clean()", "Media is available on empty formset.", "test_customize_management_form_error (forms_tests.tests.test_form... | 475cffd1d64c690cdad16ede4d5e81985738ceb4 | <15 min fix | from django.core.exceptions import ValidationError
from django.forms import Form
from django.forms.fields import BooleanField, IntegerField
from django.forms.utils import ErrorList
from django.forms.widgets import HiddenInput, NumberInput
from django.utils.functional import cached_property
from django.utils.html import... | [
[
333,
339
],
[
380,
389
]
] | django/forms/formsets.py | python:3.11 |
django/django | django__django-14752 | b64db05b9cedd96905d637a2d824cbbf428e40e7 | diff --git a/django/contrib/admin/views/autocomplete.py b/django/contrib/admin/views/autocomplete.py
--- a/django/contrib/admin/views/autocomplete.py
+++ b/django/contrib/admin/views/autocomplete.py
@@ -11,7 +11,8 @@ class AutocompleteJsonView(BaseListView):
def get(self, request, *args, **kwargs):
"""
... | diff --git a/tests/admin_views/test_autocomplete_view.py b/tests/admin_views/test_autocomplete_view.py
--- a/tests/admin_views/test_autocomplete_view.py
+++ b/tests/admin_views/test_autocomplete_view.py
@@ -1,3 +1,4 @@
+import datetime
import json
from contextlib import contextmanager
@@ -293,6 +294,29 @@ class PKO... | Refactor AutocompleteJsonView to support extra fields in autocomplete response
Description
(last modified by mrts)
Adding data attributes to items in ordinary non-autocomplete foreign key fields that use forms.widgets.Select-based widgets is relatively easy. This enables powerful and dynamic admin site customiz... | Makes sense to me. | 2021-08-07T16:34:32Z | 4.0 | ["test_serialize_result (admin_views.test_autocomplete_view.AutocompleteJsonViewTests)"] | ["test_custom_to_field (admin_views.test_autocomplete_view.AutocompleteJsonViewTests)", "test_custom_to_field_custom_pk (admin_views.test_autocomplete_view.AutocompleteJsonViewTests)", "test_custom_to_field_permission_denied (admin_views.test_autocomplete_view.AutocompleteJsonViewTests)", "test_field_does_not_allowed (... | 475cffd1d64c690cdad16ede4d5e81985738ceb4 | <15 min fix | from django.apps import apps
from django.core.exceptions import FieldDoesNotExist, PermissionDenied
from django.http import Http404, JsonResponse
from django.views.generic.list import BaseListView
class AutocompleteJsonView(BaseListView):
"""Handle AutocompleteWidget's AJAX requests for data."""
paginate_by =... | [
[
11,
18
],
[
27,
45
]
] | django/contrib/admin/views/autocomplete.py | python:3.11 |
django/django | django__django-14765 | 4e8121e8e42a24acc3565851c9ef50ca8322b15c | diff --git a/django/db/migrations/state.py b/django/db/migrations/state.py
--- a/django/db/migrations/state.py
+++ b/django/db/migrations/state.py
@@ -91,10 +91,11 @@ class ProjectState:
def __init__(self, models=None, real_apps=None):
self.models = models or {}
# Apps to include from main regist... | diff --git a/tests/migrations/test_state.py b/tests/migrations/test_state.py
--- a/tests/migrations/test_state.py
+++ b/tests/migrations/test_state.py
@@ -924,6 +924,10 @@ class Meta:
1,
)
+ def test_real_apps_non_set(self):
+ with self.assertRaises(AssertionError):
+ Projec... | ProjectState.__init__() can assume its real_apps argument is a set
Description
PR #14760 made all calls to ProjectState.__init__() pass real_apps as a set. In ProjectState.__init__() now, then, instead of checking that real_apps is a set and converting it to a set if not, it can just assert that it's a set when non... | Hey Chris. I'm a bit Meh about the suggestion here but I'll accept so you can make the PR for review. (If the others like it...) ...part of Django's internal API I'm forever amazed what parts of Django folks out there are using. Perhaps not this. :) Thanks. | 2021-08-12T05:59:11Z | 4.0 | ["test_real_apps_non_set (migrations.test_state.StateTests)"] | ["test_abstract_model_children_inherit_indexes (migrations.test_state.ModelStateTests)", "test_bound_field_sanity_check (migrations.test_state.ModelStateTests)", "Tests making a ProjectState from an Apps with a swappable model", "A swappable model inheriting from a hierarchy:", "Tests making a ProjectState from unused ... | 475cffd1d64c690cdad16ede4d5e81985738ceb4 | <15 min fix | import copy
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
from django.apps import AppConfig
from django.apps.registry import Apps, apps as global_apps
from django.conf import settings
from django.core.exceptions import FieldDoesNotExist
from django.db import mo... | [
[
91,
101
]
] | django/db/migrations/state.py | python:3.11 |
django/django | django__django-14787 | 004b4620f6f4ad87261e149898940f2dcd5757ef | diff --git a/django/utils/decorators.py b/django/utils/decorators.py
--- a/django/utils/decorators.py
+++ b/django/utils/decorators.py
@@ -37,7 +37,7 @@ def _wrapper(self, *args, **kwargs):
# 'self' argument, but it's a closure over self so it can call
# 'func'. Also, wrap method.__get__() in a functi... | diff --git a/tests/decorators/tests.py b/tests/decorators/tests.py
--- a/tests/decorators/tests.py
+++ b/tests/decorators/tests.py
@@ -425,6 +425,29 @@ class Test:
def __module__(cls):
return "tests"
+ def test_wrapper_assignments(self):
+ """@method_decorator preserves... | method_decorator() should preserve wrapper assignments
Description
the function that is passed to the decorator is a partial object and does not have any of the attributes expected from a function i.e. __name__, __module__ etc...
consider the following case
def logger(func):
@wraps(func)
def inner(*args, **kwargs):... | 2021-08-23T12:59:59Z | 4.1 | ["@method_decorator preserves wrapper assignments."] | ["test_cache_control_decorator_http_request (decorators.tests.CacheControlDecoratorTest)", "Ensures @xframe_options_deny properly sets the X-Frame-Options header.", "Ensures @xframe_options_exempt properly instructs the", "Ensures @xframe_options_sameorigin properly sets the X-Frame-Options", "Built-in decorators set c... | 647480166bfe7532e8c471fef0146e3a17e6c0c9 | <15 min fix | "Functions that help with dynamically creating decorators for views."
from functools import partial, update_wrapper, wraps
class classonlymethod(classmethod):
def __get__(self, instance, cls=None):
if instance is not None:
raise AttributeError("This method is available only on the class, not ... | [
[
37,
43
]
] | django/utils/decorators.py | python:3.11 | |
django/django | django__django-14792 | d89f976bddb49fb168334960acc8979c3de991fa | diff --git a/django/utils/timezone.py b/django/utils/timezone.py
--- a/django/utils/timezone.py
+++ b/django/utils/timezone.py
@@ -72,8 +72,11 @@ def get_current_timezone_name():
def _get_timezone_name(timezone):
- """Return the name of ``timezone``."""
- return str(timezone)
+ """
+ Return the offset ... | diff --git a/tests/utils_tests/test_timezone.py b/tests/utils_tests/test_timezone.py
--- a/tests/utils_tests/test_timezone.py
+++ b/tests/utils_tests/test_timezone.py
@@ -260,6 +260,31 @@ def test_make_aware_zoneinfo_non_existent(self):
self.assertEqual(std.utcoffset(), datetime.timedelta(hours=1))
se... | Reverse time zone conversion in Trunc()/Extract() database functions.
Description
When using a time zone of "Etc/GMT-10" (or similar) for a Trunc class tzinfo, it appears there's a different behavior as of Django 3.2 in the resulting database query. I think it's due to a change in the return value of timezone._get_ti... | Thanks for the report. Regression in 10d126198434810529e0220b0c6896ed64ca0e88. Reproduced at 4fe3774c729f3fd5105b3001fe69a70bdca95ac3.
This problem is also affecting MySQL, the timezone "Etc/GMT-10" is returning "-10" instead of "-10:00". #33037 | 2021-08-24T09:25:15Z | 4.0 | ["The _get_timezone_name() helper must return the offset for fixed offset", "test_is_aware (utils_tests.test_timezone.TimezoneTests)"] | ["test_activate_invalid_timezone (utils_tests.test_timezone.TimezoneTests)", "test_fixedoffset_negative_timedelta (utils_tests.test_timezone.TimezoneTests)", "test_fixedoffset_timedelta (utils_tests.test_timezone.TimezoneTests)", "test_get_default_timezone (utils_tests.test_timezone.TimezoneTests)", "test_get_default_t... | 475cffd1d64c690cdad16ede4d5e81985738ceb4 | <15 min fix | """
Timezone-related classes and functions.
"""
import functools
from contextlib import ContextDecorator
from datetime import datetime, timedelta, timezone, tzinfo
import pytz
from asgiref.local import Local
from django.conf import settings
__all__ = [
'utc', 'get_fixed_timezone',
'get_default_timezone', 'g... | [
[
72,
82
]
] | django/utils/timezone.py | python:3.11 |
django/django | django__django-14855 | 475cffd1d64c690cdad16ede4d5e81985738ceb4 | diff --git a/django/contrib/admin/helpers.py b/django/contrib/admin/helpers.py
--- a/django/contrib/admin/helpers.py
+++ b/django/contrib/admin/helpers.py
@@ -209,7 +209,11 @@ def get_admin_url(self, remote_field, remote_obj):
remote_field.model._meta.model_name,
)
try:
- url =... | diff --git a/tests/admin_views/admin.py b/tests/admin_views/admin.py
--- a/tests/admin_views/admin.py
+++ b/tests/admin_views/admin.py
@@ -1142,6 +1142,8 @@ def get_formsets_with_inlines(self, request, obj=None):
raw_id_fields=['parent'],
)
site2.register(Person, save_as_continue=False)
+site2.register(ReadOnlyR... | Wrong URL generated by get_admin_url for readonly field in custom Admin Site
Description
When a model containing a ForeignKey field is viewed (or edited) in a custom Admin Site, and that ForeignKey field is listed in readonly_fields, the url generated for the link is /admin/... instead of /custom-admin/....
This appe... | Hey Ken, yes seems right. Good spot. Looks like this should have been part of b79088306513d5ed76d31ac40ab3c15f858946ea for #31181 (which was Django 3.2) here. However, I don't know if there are any side effects and I have not yet run the full suite of tests on this. Mostly looking for feedback whether I'm on the right... | 2021-09-14T01:27:01Z | 4.0 | ["test_readonly_foreignkey_links_custom_admin_site (admin_views.tests.ReadonlyTest)"] | ["test_explicitly_provided_pk (admin_views.tests.GetFormsetsWithInlinesArgumentTest)", "test_implicitly_generated_pk (admin_views.tests.GetFormsetsWithInlinesArgumentTest)", "test_should_be_able_to_edit_related_objects_on_add_view (admin_views.tests.AdminCustomSaveRelatedTests)", "test_should_be_able_to_edit_related_ob... | 475cffd1d64c690cdad16ede4d5e81985738ceb4 | <15 min fix | import json
from django import forms
from django.contrib.admin.utils import (
display_for_field, flatten_fieldsets, help_text_for_field, label_for_field,
lookup_field, quote,
)
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.fields.related import (
ForeignObjectRel, ManyToManyRe... | [
[
209,
219
]
] | django/contrib/admin/helpers.py | python:3.11 |
django/django | django__django-14915 | 903aaa35e5ceaa33bfc9b19b7f6da65ce5a91dd4 | diff --git a/django/forms/models.py b/django/forms/models.py
--- a/django/forms/models.py
+++ b/django/forms/models.py
@@ -1166,6 +1166,9 @@ def __init__(self, value, instance):
def __str__(self):
return str(self.value)
+ def __hash__(self):
+ return hash(self.value)
+
def __eq__(self, ot... | diff --git a/tests/model_forms/test_modelchoicefield.py b/tests/model_forms/test_modelchoicefield.py
--- a/tests/model_forms/test_modelchoicefield.py
+++ b/tests/model_forms/test_modelchoicefield.py
@@ -2,7 +2,7 @@
from django import forms
from django.core.exceptions import ValidationError
-from django.forms.models... | ModelChoiceIteratorValue is not hashable.
Description
Recently I migrated from Django 3.0 to Django 3.1. In my code, I add custom data-* attributes to the select widget options. After the upgrade some of those options broke. Error is {TypeError}unhashable type: 'ModelChoiceIteratorValue'.
Example (this one breaks):
... | Thanks for the ticket. Agreed, we could make ModelChoiceIteratorValue hashable by adding: def __hash__(self): return hash(self.value) For now you can use value.value as documented in the "Backwards incompatible changes in 3.1" section. Would you like to prepare a patch?
Replying to Mariusz Felisiak: Thanks for the tic... | 2021-09-29T22:00:15Z | 4.1 | ["test_choice_value_hash (model_forms.test_modelchoicefield.ModelChoiceFieldTests)"] | ["test_basics (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_choice_iterator_passes_model_to_widget (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_choices (model_forms.test_modelchoicefield.ModelChoiceFieldTests)", "test_choices_bool (model_forms.test_modelchoicefield.ModelChoiceFi... | 647480166bfe7532e8c471fef0146e3a17e6c0c9 | <15 min fix | """
Helper functions for creating Form classes from Django models
and database field objects.
"""
from itertools import chain
from django.core.exceptions import (
NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError,
)
from django.forms.fields import ChoiceField, Field
from django.forms.forms import... | [
[
1166,
1174
]
] | django/forms/models.py | python:3.11 |
django/django | django__django-14999 | a754b82dac511475b6276039471ccd17cc64aeb8 | diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py
--- a/django/db/migrations/operations/models.py
+++ b/django/db/migrations/operations/models.py
@@ -320,12 +320,13 @@ def database_forwards(self, app_label, schema_editor, from_state, to_state):
new_model = to_st... | diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py
--- a/tests/migrations/test_operations.py
+++ b/tests/migrations/test_operations.py
@@ -793,6 +793,28 @@ def test_rename_model_with_m2m(self):
self.assertEqual(Rider.objects.count(), 2)
self.assertEqual(Pony._meta.g... | RenameModel with db_table should be a noop.
Description
A RenameModel operation that already has db_table defined must be a noop.
In Postgres, it drops and recreates foreign key constraints. In sqlite it recreates the table (as expected for a table renaming).
| 2021-10-16T09:31:21Z | 4.1 | ["test_rename_model_with_db_table_noop (migrations.test_operations.OperationTests)"] | ["test_references_model_mixin (migrations.test_operations.TestCreateModel)", "test_reference_field_by_through_fields (migrations.test_operations.FieldOperationTests)", "test_references_field_by_from_fields (migrations.test_operations.FieldOperationTests)", "test_references_field_by_name (migrations.test_operations.Fiel... | 647480166bfe7532e8c471fef0146e3a17e6c0c9 | <15 min fix | from django.db import models
from django.db.migrations.operations.base import Operation
from django.db.migrations.state import ModelState
from django.db.migrations.utils import field_references, resolve_relation
from django.db.models.options import normalize_together
from django.utils.functional import cached_property
... | [
[
320,
332
]
] | django/db/migrations/operations/models.py | python:3.11 | |
django/django | django__django-15104 | a7e7043c8746933dafce652507d3b821801cdc7d | diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py
--- a/django/db/migrations/autodetector.py
+++ b/django/db/migrations/autodetector.py
@@ -96,7 +96,7 @@ def only_relation_agnostic_fields(self, fields):
for name, field in sorted(fields.items()):
deconstructio... | diff --git a/tests/migrations/test_autodetector.py b/tests/migrations/test_autodetector.py
--- a/tests/migrations/test_autodetector.py
+++ b/tests/migrations/test_autodetector.py
@@ -2834,6 +2834,28 @@ def test_parse_number(self):
expected_number,
)
+ def test_add_custom_fk_wi... | KeyError with migration autodetector and FK field with hardcoded reference
Description
Hi,
I encountered this issue on an old Django project (probably 10 years old) with tons of models and probably a lot of questionable design decisions.
The symptom is that running our test suite in verbose mode doesn't work:
$ pytho... | 2021-11-19T20:46:58Z | 4.1 | ["test_add_custom_fk_with_hardcoded_to (migrations.test_autodetector.AutodetectorTests)"] | ["test_auto (migrations.test_autodetector.MigrationSuggestNameTests)", "test_many_operations_suffix (migrations.test_autodetector.MigrationSuggestNameTests)", "test_no_operations (migrations.test_autodetector.MigrationSuggestNameTests)", "test_no_operations_initial (migrations.test_autodetector.MigrationSuggestNameTest... | 647480166bfe7532e8c471fef0146e3a17e6c0c9 | <15 min fix | import functools
import re
from itertools import chain
from django.conf import settings
from django.db import models
from django.db.migrations import operations
from django.db.migrations.migration import Migration
from django.db.migrations.operations.models import AlterModelOptions
from django.db.migrations.optimizer ... | [
[
96,
102
]
] | django/db/migrations/autodetector.py | python:3.11 | |
django/django | django__django-15127 | 9a6e2df3a8f01ea761529bec48e5a8dc0ea9575b | diff --git a/django/contrib/messages/apps.py b/django/contrib/messages/apps.py
--- a/django/contrib/messages/apps.py
+++ b/django/contrib/messages/apps.py
@@ -1,7 +1,18 @@
from django.apps import AppConfig
+from django.contrib.messages.storage import base
+from django.contrib.messages.utils import get_level_tags
+from... | diff --git a/tests/messages_tests/base.py b/tests/messages_tests/base.py
--- a/tests/messages_tests/base.py
+++ b/tests/messages_tests/base.py
@@ -1,7 +1,7 @@
-from django.contrib.messages import constants, get_level, set_level, utils
+from django.contrib.messages import constants, get_level, set_level
from django.con... | LEVEL_TAGS not updated when using @override_settings
Description
When reading messages inside tests, new message tags created using @override_settings is not updated.
That causes the django.contrib.messages.storage.base.Message.level_tag property results to be an empty string and not know the new tags.
| If you aren't planning to provide a patch (with a test), could you provide some minimal code that demonstrates the issue?
LEVEL_TAGS is a constant defined in the django.contrib.messages.storage.base module that's why it needs to be updated after changing MESSAGE_TAGS (see #16574 and override_settings_tags() hook). It ... | 2021-11-25T13:14:38Z | 4.1 | ["test_override_settings_level_tags (messages_tests.tests.TestLevelTags)"] | ["test_eq (messages_tests.tests.MessageTests)"] | 647480166bfe7532e8c471fef0146e3a17e6c0c9 | <15 min fix | from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class MessagesConfig(AppConfig):
name = 'django.contrib.messages'
verbose_name = _("Messages")
| [
[
1,
18
]
] | django/contrib/messages/apps.py | python:3.11 |
django/django | django__django-15277 | 30613d6a748fce18919ff8b0da166d9fda2ed9bc | diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
--- a/django/db/models/fields/__init__.py
+++ b/django/db/models/fields/__init__.py
@@ -1010,7 +1010,8 @@ class CharField(Field):
def __init__(self, *args, db_collation=None, **kwargs):
super().__init__(*args, **kwargs)... | diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py
--- a/tests/expressions/tests.py
+++ b/tests/expressions/tests.py
@@ -1852,6 +1852,30 @@ def test_resolve_output_field_failure(self):
with self.assertRaisesMessage(FieldError, msg):
Value(object()).output_field
+ def test_ou... | Micro-optimisation for Value._resolve_output_field (by modifying CharField.__init__)
Description
Currently, when you do something like annotate(x=Value('test')) that will eventually probably call down into Value._resolve_output_field() and run the following code:
if isinstance(self.value, str):
return fields.CharFie... | All tests passed in CI, PR is https://github.com/django/django/pull/15277 Force pushing a revised commit which includes a test case that errors without the change, for regression purposes. | 2022-01-03T12:14:06Z | 4.1 | ["The output field for a given Value doesn't get cleaned & validated,", "test_raise_empty_expressionlist (expressions.tests.ValueTests)"] | ["test_empty_group_by (expressions.tests.ExpressionWrapperTests)", "test_non_empty_group_by (expressions.tests.ExpressionWrapperTests)", "test_and (expressions.tests.CombinableTests)", "test_negation (expressions.tests.CombinableTests)", "test_or (expressions.tests.CombinableTests)", "test_reversed_and (expressions.tes... | 647480166bfe7532e8c471fef0146e3a17e6c0c9 | <15 min fix | import collections.abc
import copy
import datetime
import decimal
import math
import operator
import uuid
import warnings
from base64 import b64decode, b64encode
from functools import partialmethod, total_ordering
from django import forms
from django.apps import apps
from django.conf import settings
from django.core i... | [
[
1010,
1017
]
] | django/db/models/fields/__init__.py | python:3.11 |
django/django | django__django-15315 | 652c68ffeebd510a6f59e1b56b3e007d07683ad8 | diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
--- a/django/db/models/fields/__init__.py
+++ b/django/db/models/fields/__init__.py
@@ -542,11 +542,7 @@ def __lt__(self, other):
return NotImplemented
def __hash__(self):
- return hash((
- self.crea... | diff --git a/tests/model_fields/tests.py b/tests/model_fields/tests.py
--- a/tests/model_fields/tests.py
+++ b/tests/model_fields/tests.py
@@ -128,9 +128,14 @@ class InheritAbstractModel2(AbstractModel):
self.assertLess(abstract_model_field, inherit2_model_field)
self.assertLess(inherit1_model_field, ... | Model Field.__hash__() should be immutable.
Description
Field.__hash__ changes value when a field is assigned to a model class.
This code crashes with an AssertionError:
from django.db import models
f = models.CharField(max_length=200)
d = {f: 1}
class Book(models.Model):
title = f
assert f in d
The bug was introduc... | 2022-01-13T18:51:58Z | 4.1 | ["test_hash_immutability (model_fields.tests.BasicFieldTests)"] | ["test_check (model_fields.tests.ChoicesTests)", "test_choices (model_fields.tests.ChoicesTests)", "test_flatchoices (model_fields.tests.ChoicesTests)", "test_formfield (model_fields.tests.ChoicesTests)", "test_invalid_choice (model_fields.tests.ChoicesTests)", "test_blank_in_choices (model_fields.tests.GetChoicesTests... | 647480166bfe7532e8c471fef0146e3a17e6c0c9 | <15 min fix | import collections.abc
import copy
import datetime
import decimal
import math
import operator
import uuid
import warnings
from base64 import b64decode, b64encode
from functools import partialmethod, total_ordering
from django import forms
from django.apps import apps
from django.conf import settings
from django.core i... | [
[
542,
548
]
] | django/db/models/fields/__init__.py | python:3.11 | |
django/django | django__django-15368 | e972620ada4f9ed7bc57f28e133e85c85b0a7b20 | diff --git a/django/db/models/query.py b/django/db/models/query.py
--- a/django/db/models/query.py
+++ b/django/db/models/query.py
@@ -17,7 +17,7 @@
from django.db.models import AutoField, DateField, DateTimeField, sql
from django.db.models.constants import LOOKUP_SEP, OnConflict
from django.db.models.deletion impor... | diff --git a/tests/queries/test_bulk_update.py b/tests/queries/test_bulk_update.py
--- a/tests/queries/test_bulk_update.py
+++ b/tests/queries/test_bulk_update.py
@@ -211,6 +211,16 @@ def test_field_references(self):
Number.objects.bulk_update(numbers, ['num'])
self.assertCountEqual(Number.objects.fil... | bulk_update() does not work with plain F('...') expressions.
Description
Repro:
assign plain F(...) to some model instance field
save with bulk_update
Example:
Code highlighting:
>>> from exampleapp.models import SelfRef
>>> o = SelfRef.objects.all().first()
>>> o.c8 = F('name') # model has char fields 'c8' and 'name... | Thanks for the report. Agreed, we should check resolve_expression like elsewhere. Would you like to provide a patch?
Sure, can do a patch. Is this worth to add a test case as well? | 2022-01-27T13:44:35Z | 4.1 | ["test_f_expression (queries.test_bulk_update.BulkUpdateTests)"] | ["test_batch_size (queries.test_bulk_update.BulkUpdateNoteTests)", "test_foreign_keys_do_not_lookup (queries.test_bulk_update.BulkUpdateNoteTests)", "test_functions (queries.test_bulk_update.BulkUpdateNoteTests)", "test_multiple_fields (queries.test_bulk_update.BulkUpdateNoteTests)", "test_set_field_to_null (queries.te... | 647480166bfe7532e8c471fef0146e3a17e6c0c9 | <15 min fix | """
The main QuerySet implementation. This provides the public API for the ORM.
"""
import copy
import operator
import warnings
from itertools import chain, islice
import django
from django.conf import settings
from django.core import exceptions
from django.db import (
DJANGO_VERSION_PICKLE_KEY, IntegrityError, N... | [
[
17,
23
],
[
670,
676
]
] | django/db/models/query.py | python:3.11 |
django/django | django__django-15380 | 71e7c8e73712419626f1c2b6ec036e8559a2d667 | diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py
--- a/django/db/migrations/autodetector.py
+++ b/django/db/migrations/autodetector.py
@@ -824,7 +824,7 @@ def generate_renamed_fields(self):
for app_label, model_name, field_name in sorted(self.new_field_keys - self.old_fi... | diff --git a/tests/migrations/test_autodetector.py b/tests/migrations/test_autodetector.py
--- a/tests/migrations/test_autodetector.py
+++ b/tests/migrations/test_autodetector.py
@@ -1049,6 +1049,26 @@ def test_rename_related_field_preserved_db_column(self):
new_name='renamed_foo',
)
+ def te... | Migration autodetector crashes when renaming a model and field.
Description
Migration autodetector crashes when renaming a model and field in a single step:
$ python manage.py makemigrations
Did you rename the test_one.MyModel model to MyModel2? [y/N] y
Traceback (most recent call last):
File "manage.py", line 22, i... | 2022-01-31T19:44:44Z | 4.1 | ["test_rename_field_with_renamed_model (migrations.test_autodetector.AutodetectorTests)"] | ["test_auto (migrations.test_autodetector.MigrationSuggestNameTests)", "test_many_operations_suffix (migrations.test_autodetector.MigrationSuggestNameTests)", "test_no_operations (migrations.test_autodetector.MigrationSuggestNameTests)", "test_no_operations_initial (migrations.test_autodetector.MigrationSuggestNameTest... | 647480166bfe7532e8c471fef0146e3a17e6c0c9 | <15 min fix | import functools
import re
from itertools import chain
from django.conf import settings
from django.db import models
from django.db.migrations import operations
from django.db.migrations.migration import Migration
from django.db.migrations.operations.models import AlterModelOptions
from django.db.migrations.optimizer ... | [
[
824,
830
]
] | django/db/migrations/autodetector.py | python:3.11 | |
django/django | django__django-15467 | e0442a628eb480eac6a7888aed5a86f83499e299 | diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py
--- a/django/contrib/admin/options.py
+++ b/django/contrib/admin/options.py
@@ -269,7 +269,9 @@ def formfield_for_foreignkey(self, db_field, request, **kwargs):
"class": get_ul_class(self.radio_fields[db_field.name])... | diff --git a/tests/admin_widgets/tests.py b/tests/admin_widgets/tests.py
--- a/tests/admin_widgets/tests.py
+++ b/tests/admin_widgets/tests.py
@@ -21,6 +21,7 @@
CharField,
DateField,
DateTimeField,
+ ForeignKey,
ManyToManyField,
UUIDField,
)
@@ -141,6 +142,17 @@ def test_radio_fields_Foreig... | ModelAdmin with defined radio_fields override empty_label
Description
ModelAdmin drops my "empty_label" and set "default_empty_label". For example:
class MyModelAdmin(ModelAdmin):
radio_fields = 'myfield',
def formfield_for_foreignkey(self, db_field, *args, **kwargs):
if db_field.name == 'myfield':
kwargs['emp... | Agreed, empty_label from kwargs should take precedence over _('None').
I want to work on this to get familiarised with contributing process. Assigning this to me. | 2022-02-27T03:00:31Z | 4.1 | ["test_radio_fields_foreignkey_formfield_overrides_empty_label (admin_widgets.tests.AdminFormfieldForDBFieldTests)"] | ["test_CharField (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_DateField (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_DateTimeField (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_EmailField (admin_widgets.tests.AdminFormfieldForDBFieldTests)", "test_FileField (admin_widgets.tes... | 647480166bfe7532e8c471fef0146e3a17e6c0c9 | <15 min fix | import copy
import json
import re
from functools import partial, update_wrapper
from urllib.parse import quote as urlquote
from django import forms
from django.conf import settings
from django.contrib import messages
from django.contrib.admin import helpers, widgets
from django.contrib.admin.checks import (
BaseMo... | [
[
269,
277
]
] | django/contrib/admin/options.py | python:3.11 |
django/django | django__django-15499 | d90e34c61b27fba2527834806639eebbcfab9631 | diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py
--- a/django/db/migrations/operations/models.py
+++ b/django/db/migrations/operations/models.py
@@ -170,6 +170,19 @@ def reduce(self, operation, app_label):
managers=self.managers,
),... | diff --git a/tests/migrations/test_optimizer.py b/tests/migrations/test_optimizer.py
--- a/tests/migrations/test_optimizer.py
+++ b/tests/migrations/test_optimizer.py
@@ -129,6 +129,30 @@ def test_create_alter_model_options(self):
],
)
+ def test_create_alter_model_managers(self):
+ se... | Optimize CreateModel + AlterModelManagers to CreateModel
Description
During migration optimization, CreateModel + AlterModelOptions is reduced to just CreateModel, with the model options. Similarly, CreateModel + AlterModelManagers can become just CreateModel.
| 2022-03-10T22:32:35Z | 4.1 | ["test_create_alter_model_managers (migrations.test_optimizer.OptimizerTests)"] | ["AlterField should optimize into AddField.", "RemoveField should cancel AddField", "RenameField should optimize into AddField", "test_alter_alter_index_model (migrations.test_optimizer.OptimizerTests)", "test_alter_alter_owrt_model (migrations.test_optimizer.OptimizerTests)", "test_alter_alter_table_model (migrations.... | 647480166bfe7532e8c471fef0146e3a17e6c0c9 | <15 min fix | from django.db import models
from django.db.migrations.operations.base import Operation
from django.db.migrations.state import ModelState
from django.db.migrations.utils import field_references, resolve_relation
from django.db.models.options import normalize_together
from django.utils.functional import cached_property
... | [
[
170,
188
]
] | django/db/migrations/operations/models.py | python:3.11 | |
django/django | django__django-15569 | 884b4c27f506b3c29d58509fc83a35c30ea10d94 | diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py
--- a/django/db/models/query_utils.py
+++ b/django/db/models/query_utils.py
@@ -217,6 +217,7 @@ def _unregister_lookup(cls, lookup, lookup_name=None):
if lookup_name is None:
lookup_name = lookup.lookup_name
de... | diff --git a/tests/custom_lookups/tests.py b/tests/custom_lookups/tests.py
--- a/tests/custom_lookups/tests.py
+++ b/tests/custom_lookups/tests.py
@@ -323,6 +323,8 @@ def test_lookups_caching(self):
with register_lookup(models.ForeignObject, Exactly):
# getting the lookups again should re-cache
... | RegisterLookupMixin._unregister_lookup() should clear the lookup cache.
Description
(last modified by Himanshu Balasamanta)
In current source code, in the _unregister_lookup method, https://github.com/django/django/blame/main/django/db/models/query_utils.py#L212, the cache is not cleared, which should be done,... | Hi Himanshu. This may be right, yes — I need to have a sit-down and play with it. Main question: Are you able to put together an example case where the wrong result arrises? I was looking at PR #6906 which added the cache clearing. Also noting the For use in tests only... in the _unregister_lookup docstring. So this w... | 2022-04-08T06:55:17Z | 4.1 | ["test_get_transforms (model_fields.test_jsonfield.TestMethods)", "test_lookups_caching (custom_lookups.tests.LookupTests)"] | ["test_formfield (model_fields.test_jsonfield.TestFormField)", "test_formfield_custom_encoder_decoder (model_fields.test_jsonfield.TestFormField)", "test_subquery_usage (custom_lookups.tests.SubqueryTransformTests)", "test_call_order (custom_lookups.tests.LookupTransformCallOrderTests)", "test_overridden_get_lookup (cu... | 647480166bfe7532e8c471fef0146e3a17e6c0c9 | <15 min fix | """
Various data structures used in query construction.
Factored out from django.db.models.query to avoid making the main module very
large and/or so that they can be used by other modules without getting into
circular import difficulties.
"""
import copy
import functools
import inspect
from collections import namedtu... | [
[
217,
223
]
] | django/db/models/query_utils.py | python:3.11 |
django/django | django__django-15572 | 0b31e024873681e187b574fe1c4afe5e48aeeecf | diff --git a/django/template/autoreload.py b/django/template/autoreload.py
--- a/django/template/autoreload.py
+++ b/django/template/autoreload.py
@@ -17,7 +17,7 @@ def get_template_directories():
if not isinstance(backend, DjangoTemplates):
continue
- items.update(cwd / to_path(dir) for ... | diff --git a/tests/template_tests/test_autoreloader.py b/tests/template_tests/test_autoreloader.py
--- a/tests/template_tests/test_autoreloader.py
+++ b/tests/template_tests/test_autoreloader.py
@@ -81,6 +81,17 @@ def test_reset_all_loaders(self, mock_reset):
autoreload.reset_loaders()
self.assertEqua... | Django 3.2.4+ autoreload breaks on empty string in TEMPLATES DIRS.
Description
Django versions > 3.2.3 changes the way template dirs are handled, they are now normalized using pathlib.Path.
People having an invalid value in TEMPLATESDIRS? will notice that autoreload stops working.
"DIRS": os.getenv("TEMPLATES_DIRS", ... | 2022-04-09T09:38:31Z | 4.1 | ["test_template_dirs_ignore_empty_path (template_tests.test_autoreloader.TemplateReloadTests)"] | ["test_get_template_directories (template_tests.test_autoreloader.Jinja2TemplateReloadTests)", "test_reset_all_loaders (template_tests.test_autoreloader.Jinja2TemplateReloadTests)", "test_watch_for_template_changes (template_tests.test_autoreloader.Jinja2TemplateReloadTests)", "test_get_template_directories (template_t... | 647480166bfe7532e8c471fef0146e3a17e6c0c9 | <15 min fix | from pathlib import Path
from django.dispatch import receiver
from django.template import engines
from django.template.backends.django import DjangoTemplates
from django.utils._os import to_path
from django.utils.autoreload import autoreload_started, file_changed, is_django_path
def get_template_directories():
#... | [
[
17,
23
],
[
25,
31
]
] | django/template/autoreload.py | python:3.11 | |
django/django | django__django-15741 | 8c0886b068ba4e224dd78104b93c9638b860b398 | diff --git a/django/utils/formats.py b/django/utils/formats.py
--- a/django/utils/formats.py
+++ b/django/utils/formats.py
@@ -113,6 +113,7 @@ def get_format(format_type, lang=None, use_l10n=None):
use_l10n = settings.USE_L10N
if use_l10n and lang is None:
lang = get_language()
+ format_ty... | diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py
--- a/tests/i18n/tests.py
+++ b/tests/i18n/tests.py
@@ -1518,6 +1518,9 @@ def test_get_format_modules_lang(self):
with translation.override("de", deactivate=True):
self.assertEqual(".", get_format("DECIMAL_SEPARATOR", lang="en"))
+ def te... | django.utils.formats.get_format should allow lazy parameter
Description
Commit [659d2421c7adb] (fixing #20296) triggered a regression when the date template filter (possibly others are affected too) receives a lazy string, like in some_date|date:_('Y-m-d').
This fails with: TypeError: getattr(): attribute name must b... | 2022-05-28T09:52:42Z | 4.2 | ["test_date_lazy (template_tests.filter_tests.test_date.DateTests)", "test_get_format_lazy_format (i18n.tests.FormattingTests)"] | ["test_lazy (i18n.tests.TestModels)", "test_safestr (i18n.tests.TestModels)", "get_language_info return the first fallback language info if the lang_info", "test_localized_language_info (i18n.tests.TestLanguageInfo)", "test_unknown_language_code (i18n.tests.TestLanguageInfo)", "test_unknown_language_code_and_country_co... | 0fbdb9784da915fce5dcc1fe82bac9b4785749e5 | <15 min fix | import datetime
import decimal
import functools
import re
import unicodedata
from importlib import import_module
from django.conf import settings
from django.utils import dateformat, numberformat
from django.utils.functional import lazy
from django.utils.translation import check_for_language, get_language, to_locale
... | [
[
113,
119
]
] | django/utils/formats.py | python:3.11 | |
django/django | django__django-15851 | b4817d20b9e55df30be0b1b2ca8c8bb6d61aab07 | diff --git a/django/db/backends/postgresql/client.py b/django/db/backends/postgresql/client.py
--- a/django/db/backends/postgresql/client.py
+++ b/django/db/backends/postgresql/client.py
@@ -32,9 +32,9 @@ def settings_to_cmd_args_env(cls, settings_dict, parameters):
args += ["-h", host]
if port:
... | diff --git a/tests/dbshell/test_postgresql.py b/tests/dbshell/test_postgresql.py
--- a/tests/dbshell/test_postgresql.py
+++ b/tests/dbshell/test_postgresql.py
@@ -154,7 +154,7 @@ def test_accent(self):
def test_parameters(self):
self.assertEqual(
self.settings_to_cmd_args_env({"NAME": "dbname... | dbshell additional parameters should be passed before dbname on PostgreSQL.
Description
psql expects all options to proceed the database name, if provided. So, if doing something like `./manage.py dbshell -- -c "select * from some_table;" one will get this:
$ ./manage.py dbshell -- -c "select * from some_table;"
psql... | 2022-07-18T01:36:33Z | 4.2 | ["test_parameters (dbshell.test_postgresql.PostgreSqlDbshellCommandTestCase)"] | ["test_accent (dbshell.test_postgresql.PostgreSqlDbshellCommandTestCase)", "test_basic (dbshell.test_postgresql.PostgreSqlDbshellCommandTestCase)", "test_column (dbshell.test_postgresql.PostgreSqlDbshellCommandTestCase)", "test_crash_password_does_not_leak (dbshell.test_postgresql.PostgreSqlDbshellCommandTestCase)", "t... | 0fbdb9784da915fce5dcc1fe82bac9b4785749e5 | <15 min fix | import signal
from django.db.backends.base.client import BaseDatabaseClient
class DatabaseClient(BaseDatabaseClient):
executable_name = "psql"
@classmethod
def settings_to_cmd_args_env(cls, settings_dict, parameters):
args = [cls.executable_name]
options = settings_dict.get("OPTIONS", {}... | [
[
32,
40
]
] | django/db/backends/postgresql/client.py | python:3.11 | |
django/django | django__django-15863 | 37c5b8c07be104fd5288cd87f101e48cb7a40298 | diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
--- a/django/template/defaultfilters.py
+++ b/django/template/defaultfilters.py
@@ -149,7 +149,7 @@ def floatformat(text, arg=-1):
use_l10n = False
arg = arg[:-1] or -1
try:
- input_val = repr(text)
... | diff --git a/tests/template_tests/filter_tests/test_floatformat.py b/tests/template_tests/filter_tests/test_floatformat.py
--- a/tests/template_tests/filter_tests/test_floatformat.py
+++ b/tests/template_tests/filter_tests/test_floatformat.py
@@ -56,6 +56,10 @@ def test_inputs(self):
self.assertEqual(floatform... | Filter floatformat drops precision in decimal numbers
Description
I discovered that floatformat template filter may drop precision when used for Decimal numbers.
MWE:
from decimal import Decimal
from django import setup
from django.conf import settings
from django.template import Template, Context
TEMPLATES = [
{
... | 2022-07-20T12:58:04Z | 4.2 | ["test_inputs (template_tests.filter_tests.test_floatformat.FunctionTests)"] | ["test_floatformat01 (template_tests.filter_tests.test_floatformat.FloatformatTests)", "test_floatformat02 (template_tests.filter_tests.test_floatformat.FloatformatTests)", "test_float_dunder_method (template_tests.filter_tests.test_floatformat.FunctionTests)", "test_force_grouping (template_tests.filter_tests.test_flo... | 0fbdb9784da915fce5dcc1fe82bac9b4785749e5 | <15 min fix | """Default variable filters."""
import random as random_module
import re
import types
import warnings
from decimal import ROUND_HALF_UP, Context, Decimal, InvalidOperation
from functools import wraps
from inspect import unwrap
from operator import itemgetter
from pprint import pformat
from urllib.parse import quote
fr... | [
[
149,
155
]
] | django/template/defaultfilters.py | python:3.11 | |
django/django | django__django-15930 | 63884829acd207404f2a5c3cc1d6b4cd0a822b70 | diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
--- a/django/db/models/expressions.py
+++ b/django/db/models/expressions.py
@@ -1299,6 +1299,11 @@ def as_sql(self, compiler, connection, template=None, **extra_context):
template_params = extra_context
sql_params = []
... | diff --git a/tests/expressions_case/tests.py b/tests/expressions_case/tests.py
--- a/tests/expressions_case/tests.py
+++ b/tests/expressions_case/tests.py
@@ -415,6 +415,16 @@ def test_annotate_with_empty_when(self):
self.assertEqual(len(objects), CaseTestModel.objects.count())
self.assertTrue(all(obj... | Case() crashes with ~Q(pk__in=[]).
Description
The following code generates a syntax error.
User.objects.annotate(
_a=Case(
When(~Q(pk__in=[]), then=Value(True)),
default=Value(False),
output_field=BooleanField(),
)
).order_by("-a").values("pk")
The error is:
ProgrammingError: syntax error at or near "THEN"... | Thanks for the report (similar to the #33374 and #26517). | 2022-08-07T15:26:41Z | 4.2 | ["test_annotate_with_full_when (expressions_case.tests.CaseExpressionTests)"] | ["test_empty_q_object (expressions_case.tests.CaseWhenTests)", "test_invalid_when_constructor_args (expressions_case.tests.CaseWhenTests)", "test_only_when_arguments (expressions_case.tests.CaseWhenTests)", "test_conditional_aggregation_example (expressions_case.tests.CaseDocumentationExamples)", "test_conditional_upda... | 0fbdb9784da915fce5dcc1fe82bac9b4785749e5 | <15 min fix | import copy
import datetime
import functools
import inspect
import warnings
from collections import defaultdict
from decimal import Decimal
from uuid import UUID
from django.core.exceptions import EmptyResultSet, FieldError
from django.db import DatabaseError, NotSupportedError, connection
from django.db.models import... | [
[
1299,
1309
]
] | django/db/models/expressions.py | python:3.11 |
django/django | django__django-15987 | 7e6b537f5b92be152779fc492bb908d27fe7c52a | diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py
--- a/django/core/management/commands/loaddata.py
+++ b/django/core/management/commands/loaddata.py
@@ -367,7 +367,7 @@ def fixture_dirs(self):
for app_config in apps.get_app_configs():
app_label... | diff --git a/tests/fixtures_regress/tests.py b/tests/fixtures_regress/tests.py
--- a/tests/fixtures_regress/tests.py
+++ b/tests/fixtures_regress/tests.py
@@ -569,6 +569,20 @@ def test_fixture_dirs_with_default_fixture_path(self):
with self.assertRaisesMessage(ImproperlyConfigured, msg):
managemen... | Fixture dirs duplicates undetected if dir is Path instance
Description
When FIXTURE_DIRS contains Path instances, the duplicate check in loaddata does not detect duplicates.
| 2022-08-23T10:07:03Z | 4.2 | ["settings.FIXTURE_DIRS cannot contain a default fixtures directory"] | ["test_fixtures_loaded (fixtures_regress.tests.TestLoadFixtureFromOtherAppDirectory)", "Natural keys with foreing keys in dependencies works in a multiple", "M2M relations with explicit through models should NOT count as", "Circular M2M relations with explicit through models should be serializable", "M2M relations with... | 0fbdb9784da915fce5dcc1fe82bac9b4785749e5 | <15 min fix | import functools
import glob
import gzip
import os
import sys
import warnings
import zipfile
from itertools import product
from django.apps import apps
from django.conf import settings
from django.core import serializers
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import Ba... | [
[
367,
373
]
] | django/core/management/commands/loaddata.py | python:3.11 | |
django/django | django__django-16100 | c6350d594c359151ee17b0c4f354bb44f28ff69e | diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py
--- a/django/contrib/admin/options.py
+++ b/django/contrib/admin/options.py
@@ -2011,15 +2011,17 @@ def changelist_view(self, request, extra_context=None):
)
if formset.is_valid():
changecount = 0
-... | diff --git a/tests/admin_changelist/tests.py b/tests/admin_changelist/tests.py
--- a/tests/admin_changelist/tests.py
+++ b/tests/admin_changelist/tests.py
@@ -1,4 +1,5 @@
import datetime
+from unittest import mock
from django.contrib import admin
from django.contrib.admin.models import LogEntry
@@ -16,12 +17,12 @@... | Add transaction handling to Changelist list_editable processing.
Description
It seems that changelist_view in Django admin is missing a transaction. Since the view may change data in database, it should be wrapped in a transaction to prevent unexpected states in case of errors.
| So, this has never been wrapped in a transaction. See https://github.com/django/django/commit/7bc0878922 where it was added. Happy to accept as a New Feature to investigate adding that. (I can't immediately see any obvious blockers.) | 2022-09-24T13:32:02Z | 4.2 | ["test_list_editable_atomicity (admin_changelist.tests.ChangeListTests)"] | ["{% get_admin_log %} works if the user model's primary key isn't named", "test_missing_args (admin_changelist.tests.GetAdminLogTests)", "{% get_admin_log %} works without specifying a user.", "test_non_integer_limit (admin_changelist.tests.GetAdminLogTests)", "test_without_as (admin_changelist.tests.GetAdminLogTests)"... | 0fbdb9784da915fce5dcc1fe82bac9b4785749e5 | <15 min fix | import copy
import json
import re
from functools import partial, update_wrapper
from urllib.parse import quote as urlquote
from django import forms
from django.conf import settings
from django.contrib import messages
from django.contrib.admin import helpers, widgets
from django.contrib.admin.checks import (
BaseMo... | [
[
2011,
2027
]
] | django/contrib/admin/options.py | python:3.11 |
django/django | django__django-16116 | 5d36a8266c7d5d1994d7a7eeb4016f80d9cb0401 | diff --git a/django/core/management/commands/makemigrations.py b/django/core/management/commands/makemigrations.py
--- a/django/core/management/commands/makemigrations.py
+++ b/django/core/management/commands/makemigrations.py
@@ -70,7 +70,10 @@ def add_arguments(self, parser):
"--check",
acti... | diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py
--- a/tests/migrations/test_commands.py
+++ b/tests/migrations/test_commands.py
@@ -2391,9 +2391,10 @@ def test_makemigrations_check(self):
makemigrations --check should exit with a non-zero status when
there are change... | makemigrations --check generating migrations is inconsistent with other uses of --check
Description
To script a check for missing migrations but without actually intending to create the migrations, it is necessary to use both --check and --dry-run, which is inconsistent with migrate --check and optimizemigration --ch... | I think this makes sense. | 2022-09-25T23:54:49Z | 4.2 | ["makemigrations --check should exit with a non-zero status when"] | ["test_makemigrations_app_name_specified_as_label (migrations.test_commands.AppLabelErrorTests)", "test_makemigrations_nonexistent_app_label (migrations.test_commands.AppLabelErrorTests)", "test_migrate_app_name_specified_as_label (migrations.test_commands.AppLabelErrorTests)", "test_migrate_nonexistent_app_label (migr... | 0fbdb9784da915fce5dcc1fe82bac9b4785749e5 | <15 min fix | import os
import sys
import warnings
from itertools import takewhile
from django.apps import apps
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError, no_translations
from django.core.management.utils import run_formatters
from django.db import DEFAULT_DB_ALIAS, Operation... | [
[
70,
79
],
[
251,
262
]
] | django/core/management/commands/makemigrations.py | python:3.11 |
django/django | django__django-16139 | d559cb02da30f74debbb1fc3a46de0df134d2d80 | diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py
--- a/django/contrib/auth/forms.py
+++ b/django/contrib/auth/forms.py
@@ -163,7 +163,9 @@ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
password = self.fields.get("password")
if password:
- ... | diff --git a/tests/auth_tests/test_forms.py b/tests/auth_tests/test_forms.py
--- a/tests/auth_tests/test_forms.py
+++ b/tests/auth_tests/test_forms.py
@@ -1,5 +1,6 @@
import datetime
import re
+import urllib.parse
from unittest import mock
from django.contrib.auth.forms import (
@@ -22,6 +23,7 @@
from django.for... | Accessing UserAdmin via to_field leads to link to PasswordResetForm being broken (404)
Description
(last modified by Simon Kern)
Accessing the UserAdmin via another model's Admin that has a reference to User (with to_field set, e.g., to_field="uuid") leads to the UserAdmin being accessed via an url that looks s... | 2022-09-30T08:51:16Z | 4.2 | ["test_link_to_password_reset_in_helptext_via_to_field (auth_tests.test_forms.UserChangeFormTest)"] | ["test_field_order (auth_tests.test_forms.PasswordChangeFormTest)", "test_html_autocomplete_attributes (auth_tests.test_forms.PasswordChangeFormTest)", "test_incorrect_password (auth_tests.test_forms.PasswordChangeFormTest)", "test_password_verification (auth_tests.test_forms.PasswordChangeFormTest)", "test_password_wh... | 0fbdb9784da915fce5dcc1fe82bac9b4785749e5 | <15 min fix | import unicodedata
from django import forms
from django.contrib.auth import authenticate, get_user_model, password_validation
from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX, identify_hasher
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from... | [
[
163,
171
]
] | django/contrib/auth/forms.py | python:3.11 | |
django/django | django__django-16145 | 93d4c9ea1de24eb391cb2b3561b6703fd46374df | diff --git a/django/core/management/commands/runserver.py b/django/core/management/commands/runserver.py
--- a/django/core/management/commands/runserver.py
+++ b/django/core/management/commands/runserver.py
@@ -129,6 +129,13 @@ def inner_run(self, *args, **options):
shutdown_message = options.get("shutdown_mes... | diff --git a/tests/admin_scripts/tests.py b/tests/admin_scripts/tests.py
--- a/tests/admin_scripts/tests.py
+++ b/tests/admin_scripts/tests.py
@@ -1587,6 +1587,21 @@ def test_runserver_addrport(self):
call_command(self.cmd, addrport="7000")
self.assertServerSettings("127.0.0.1", "7000")
+ @mock.p... | `runserver 0`'s "Starting development server at <address>" doesn't work
Description
According to tutorial running
python manage.py runserver 0:8000
is the same as
python manage.py runserver 0.0.0.0:8000
but it's output
$ python manage.py runserver 0:8000 Watching for file changes with StatReloader ... | On a Mac I could click that link and have it take me to http://0.0.0.0:8000/ What OS are you on? It might even be better to just explicitly change it to say "0.0.0.0" because at least then you can copy & paste it as well … Let's wait to see what the triage team decide 🤷♂️
According to the Diátaxis framework, a tuto... | 2022-10-03T05:09:14Z | 4.2 | ["test_zero_ip_addr (admin_scripts.tests.ManageRunserver)"] | ["Program name is computed from the execute_from_command_line()'s argv", "test_params_to_runserver (admin_scripts.tests.ManageTestserver)", "test_testserver_handle_params (admin_scripts.tests.ManageTestserver)", "test_migration_warning_multiple_apps (admin_scripts.tests.ManageRunserverMigrationWarning)", "test_migratio... | 0fbdb9784da915fce5dcc1fe82bac9b4785749e5 | <15 min fix | import errno
import os
import re
import socket
import sys
from datetime import datetime
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.core.servers.basehttp import WSGIServer, get_internal_wsgi_application, run
from django.utils import autoreload
from dja... | [
[
129,
141
],
[
154,
160
]
] | django/core/management/commands/runserver.py | python:3.11 |
django/django | django__django-16255 | 444b6da7cc229a58a2c476a52e45233001dc7073 | diff --git a/django/contrib/sitemaps/__init__.py b/django/contrib/sitemaps/__init__.py
--- a/django/contrib/sitemaps/__init__.py
+++ b/django/contrib/sitemaps/__init__.py
@@ -167,7 +167,7 @@ def get_latest_lastmod(self):
return None
if callable(self.lastmod):
try:
- ret... | diff --git a/tests/sitemaps_tests/test_http.py b/tests/sitemaps_tests/test_http.py
--- a/tests/sitemaps_tests/test_http.py
+++ b/tests/sitemaps_tests/test_http.py
@@ -507,6 +507,16 @@ def test_callable_sitemod_full(self):
self.assertXMLEqual(index_response.content.decode(), expected_content_index)
sel... | Sitemaps without items raise ValueError on callable lastmod.
Description
When sitemap contains not items, but supports returning lastmod for an item, it fails with a ValueError:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
res... | Thanks for the report.
The default argument of max() can be used. | 2022-11-04T13:49:40Z | 4.2 | ["test_callable_sitemod_no_items (sitemaps_tests.test_http.HTTPSitemapTests)"] | ["A simple sitemap index can be rendered with a custom template", "test_simple_sitemap_custom_index_warning (sitemaps_tests.test_http.DeprecatedTests)", "A i18n sitemap with alternate/hreflang links can be rendered.", "A i18n sitemap index with limited languages can be rendered.", "A i18n sitemap index with x-default c... | 0fbdb9784da915fce5dcc1fe82bac9b4785749e5 | <15 min fix | import warnings
from urllib.parse import urlencode
from urllib.request import urlopen
from django.apps import apps as django_apps
from django.conf import settings
from django.core import paginator
from django.core.exceptions import ImproperlyConfigured
from django.urls import NoReverseMatch, reverse
from django.utils ... | [
[
167,
173
]
] | django/contrib/sitemaps/__init__.py | python:3.11 |
django/django | django__django-16333 | 60a7bd89860e504c0c33b02c78edcac87f6d1b5a | diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py
--- a/django/contrib/auth/forms.py
+++ b/django/contrib/auth/forms.py
@@ -141,6 +141,8 @@ def save(self, commit=True):
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
+ if hasattr(... | diff --git a/tests/auth_tests/test_forms.py b/tests/auth_tests/test_forms.py
--- a/tests/auth_tests/test_forms.py
+++ b/tests/auth_tests/test_forms.py
@@ -35,6 +35,7 @@
)
from .models.with_custom_email_field import CustomEmailField
from .models.with_integer_username import IntegerUsernameUser
+from .models.with_many... | UserCreationForm should save data from ManyToMany form fields
Description
When using contrib.auth.forms.UserCreationForm with a custom User model which has ManyToManyField fields, the data in all related form fields (e.g. a ModelMultipleChoiceField) is not saved.
This is because unlike its parent class django.forms.... | 2022-11-27T20:09:15Z | 4.2 | ["test_custom_form_saves_many_to_many_field (auth_tests.test_forms.UserCreationFormTest)"] | ["test_field_order (auth_tests.test_forms.PasswordChangeFormTest)", "test_html_autocomplete_attributes (auth_tests.test_forms.PasswordChangeFormTest)", "test_incorrect_password (auth_tests.test_forms.PasswordChangeFormTest)", "test_password_verification (auth_tests.test_forms.PasswordChangeFormTest)", "test_password_wh... | 0fbdb9784da915fce5dcc1fe82bac9b4785749e5 | <15 min fix | import unicodedata
from django import forms
from django.contrib.auth import authenticate, get_user_model, password_validation
from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX, identify_hasher
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from... | [
[
141,
148
]
] | django/contrib/auth/forms.py | python:3.11 | |
django/django | django__django-16429 | 6c86495bcee22eac19d7fb040b2988b830707cbd | diff --git a/django/utils/timesince.py b/django/utils/timesince.py
--- a/django/utils/timesince.py
+++ b/django/utils/timesince.py
@@ -97,6 +97,7 @@ def timesince(d, now=None, reversed=False, time_strings=None, depth=2):
d.hour,
d.minute,
d.second,
+ tzinfo=d.tzinfo,
... | diff --git a/tests/utils_tests/test_timesince.py b/tests/utils_tests/test_timesince.py
--- a/tests/utils_tests/test_timesince.py
+++ b/tests/utils_tests/test_timesince.py
@@ -1,7 +1,7 @@
import datetime
from django.test import TestCase
-from django.test.utils import requires_tz_support
+from django.test.utils impor... | timesince() raises TypeError with USE_TZ=True and >1 month interval.
Description
(last modified by Sage Abdullah)
As of 8d67e16493c903adc9d049141028bc0fff43f8c8, calling timesince() with a datetime object that's one month (or more) in the past and the USE_TZ setting is set to True results in the following crash... | Thanks for the report, however test_long_interval_with_tz works for me on the current main branch 🤔
Whoops, sorry, I haven't properly tested the function as I currently don't have a local Django dev environment. I'm testing this on a shell with my Django project, I think this should be reproducible: >>> from django.ut... | 2023-01-05T11:41:37Z | 4.2 | ["test_depth (utils_tests.test_timesince.TZAwareTimesinceTests)", "test_depth_invalid (utils_tests.test_timesince.TZAwareTimesinceTests)", "Test other units.", "test_thousand_years_ago (utils_tests.test_timesince.TZAwareTimesinceTests)"] | ["Timesince should work with both date objects (#9672)", "Both timesince and timeuntil should work on date objects (#17937).", "When using two different timezones.", "If the two differing units aren't adjacent, only the first unit is", "When the second date occurs before the first, we should always", "equal datetimes."... | 0fbdb9784da915fce5dcc1fe82bac9b4785749e5 | <15 min fix | import datetime
from django.utils.html import avoid_wrapping
from django.utils.timezone import is_aware
from django.utils.translation import gettext, ngettext_lazy
TIME_STRINGS = {
"year": ngettext_lazy("%(num)d year", "%(num)d years", "num"),
"month": ngettext_lazy("%(num)d month", "%(num)d months", "num"),
... | [
[
97,
103
]
] | django/utils/timesince.py | python:3.11 |
django/django | django__django-16569 | 278881e37619278789942513916acafaa88d26f3 | diff --git a/django/forms/formsets.py b/django/forms/formsets.py
--- a/django/forms/formsets.py
+++ b/django/forms/formsets.py
@@ -490,7 +490,9 @@ def add_fields(self, form, index):
required=False,
widget=self.get_ordering_widget(),
)
- if self.can_delet... | diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py
--- a/tests/forms_tests/tests/test_formsets.py
+++ b/tests/forms_tests/tests/test_formsets.py
@@ -1480,6 +1480,7 @@ def test_disable_delete_extra_formset_forms(self):
self.assertIn("DELETE", formset.forms[0].fields... | Formsets' add_fields() method fails in some circumstances if the argument index is None.
Description
Formsets' add_fields() method fails in some circumstances if the argument index is None.
When a FormSet has the attributes self.can_delete == True and self.can_delete_extra == False, calling the add_fields() method on... | 2023-02-17T20:11:38Z | 5.0 | ["test_disable_delete_extra_formset_forms (forms_tests.tests.test_formsets.FormsFormsetTestCase.test_disable_delete_extra_formset_forms)", "test_disable_delete_extra_formset_forms (forms_tests.tests.test_formsets.Jinja2FormsFormsetTestCase.test_disable_delete_extra_formset_forms)"] | ["all_valid() validates all forms, even when some are invalid.", "test_valid (forms_tests.tests.test_formsets.AllValidTests.test_valid)", "is_multipart() works with an empty formset.", "An empty formset still calls clean()", "Media is available on empty formset.", "test_as_div (forms_tests.tests.test_formsets.FormsetAs... | 4a72da71001f154ea60906a2f74898d32b7322a7 | <15 min fix | from django.core.exceptions import ValidationError
from django.forms import Form
from django.forms.fields import BooleanField, IntegerField
from django.forms.renderers import get_default_renderer
from django.forms.utils import ErrorList, RenderableFormMixin
from django.forms.widgets import CheckboxInput, HiddenInput, N... | [
[
490,
498
]
] | django/forms/formsets.py | python:3.11 | |
django/django | django__django-16595 | f9fe062de5fc0896d6bbbf3f260b5c44473b3c77 | diff --git a/django/db/migrations/operations/fields.py b/django/db/migrations/operations/fields.py
--- a/django/db/migrations/operations/fields.py
+++ b/django/db/migrations/operations/fields.py
@@ -247,9 +247,9 @@ def migration_name_fragment(self):
return "alter_%s_%s" % (self.model_name_lower, self.name_lowe... | diff --git a/tests/migrations/test_optimizer.py b/tests/migrations/test_optimizer.py
--- a/tests/migrations/test_optimizer.py
+++ b/tests/migrations/test_optimizer.py
@@ -221,10 +221,10 @@ def test_create_alter_owrt_delete_model(self):
migrations.AlterOrderWithRespectTo("Foo", "a")
)
- def _t... | Migration optimizer does not reduce multiple AlterField
Description
Let's consider the following operations:
operations = [
migrations.AddField(
model_name="book",
name="title",
field=models.CharField(max_length=256, null=True),
),
migrations.AlterField(
model_name="book",
name="title",
field=models.C... | Your analysis is correct Laurent, the reduction of multiple AlterField against the same model is simply not implemented today hence why you're running into this behaviour. Given you're already half way there I would encourage you to submit a PR that adds these changes and an optimizer regression test to cover them if... | 2023-02-24T10:30:35Z | 5.0 | ["test_alter_alter_field (migrations.test_optimizer.OptimizerTests.test_alter_alter_field)"] | ["AlterField should optimize into AddField.", "RemoveField should cancel AddField", "RenameField should optimize into AddField", "test_alter_alter_index_model (migrations.test_optimizer.OptimizerTests.test_alter_alter_index_model)", "test_alter_alter_owrt_model (migrations.test_optimizer.OptimizerTests.test_alter_alter... | 4a72da71001f154ea60906a2f74898d32b7322a7 | <15 min fix | from django.db.migrations.utils import field_references
from django.db.models import NOT_PROVIDED
from django.utils.functional import cached_property
from .base import Operation
class FieldOperation(Operation):
def __init__(self, model_name, name, field=None):
self.model_name = model_name
self.na... | [
[
247,
255
]
] | django/db/migrations/operations/fields.py | python:3.11 |
django/django | django__django-16642 | fbe850106b2e4b85f838219cb9e1df95fba6c164 | diff --git a/django/http/response.py b/django/http/response.py
--- a/django/http/response.py
+++ b/django/http/response.py
@@ -609,7 +609,9 @@ def set_headers(self, filelike):
# Encoding isn't set to prevent browsers from automatically
# uncompressing files.
content_ty... | diff --git a/tests/responses/test_fileresponse.py b/tests/responses/test_fileresponse.py
--- a/tests/responses/test_fileresponse.py
+++ b/tests/responses/test_fileresponse.py
@@ -253,8 +253,10 @@ def test_compressed_response(self):
"""
test_tuples = (
(".tar.gz", "application/gzip"),
+ ... | Improper guessing of Mime Type for "br" and "Z" file types
Description
Below FileResponse will set the content type as text/html, even if the last file extension is "Z' or "br".
FileResponse(open('test.html.Z', 'rb'))
FileResponse(open('test.html.br', 'rb'))
| Thanks for the report! | 2023-03-11T07:38:47Z | 5.0 | ["If compressed responses are served with the uncompressed Content-Type"] | ["Headers are set correctly with a buffer when an absolute filename is", "test_content_disposition_buffer (responses.test_fileresponse.FileResponseTests.test_content_disposition_buffer)", "test_content_disposition_buffer_attachment (responses.test_fileresponse.FileResponseTests.test_content_disposition_buffer_attachmen... | 4a72da71001f154ea60906a2f74898d32b7322a7 | <15 min fix | import datetime
import io
import json
import mimetypes
import os
import re
import sys
import time
import warnings
from email.header import Header
from http.client import responses
from urllib.parse import urlparse
from asgiref.sync import async_to_sync, sync_to_async
from django.conf import settings
from django.core ... | [
[
609,
617
]
] | django/http/response.py | python:3.11 |
django/django | django__django-16801 | 3b62d8c83e3e48d2ed61cfa32a61c56d9e030293 | diff --git a/django/db/models/fields/files.py b/django/db/models/fields/files.py
--- a/django/db/models/fields/files.py
+++ b/django/db/models/fields/files.py
@@ -441,7 +441,8 @@ def contribute_to_class(self, cls, name, **kwargs):
# after their corresponding image field don't stay cleared by
# Model._... | diff --git a/tests/model_fields/test_imagefield.py b/tests/model_fields/test_imagefield.py
--- a/tests/model_fields/test_imagefield.py
+++ b/tests/model_fields/test_imagefield.py
@@ -5,6 +5,7 @@
from django.core.exceptions import ImproperlyConfigured
from django.core.files import File
from django.core.files.images i... | ImageField unnecessarily adds a post_init signal handler to the model
Description
While debugging some performance issues in a Django app, I found a codepath where most of the time was being spent on initializing Django models after fetching from the DB. It turns out that 30% of the time was being spent on evaluating... | 2023-04-26T07:23:56Z | 5.0 | ["test_post_init_not_connected (model_fields.test_imagefield.ImageFieldNoDimensionsTests.test_post_init_not_connected)"] | ["Assigning ImageField to None clears dimensions.", "Tests assigning an image field through the model's constructor.", "Tests assigning an image in Manager.create().", "The default value for an ImageField is an instance of", "Dimensions are updated correctly in various situations.", "Tests assignment using the field's ... | 4a72da71001f154ea60906a2f74898d32b7322a7 | <15 min fix | import datetime
import posixpath
from django import forms
from django.core import checks
from django.core.files.base import File
from django.core.files.images import ImageFile
from django.core.files.storage import Storage, default_storage
from django.core.files.utils import validate_file_name
from django.db.models imp... | [
[
441,
448
],
[
458,
465
]
] | django/db/models/fields/files.py | python:3.11 | |
django/django | django__django-16899 | d3d173425fc0a1107836da5b4567f1c88253191b | diff --git a/django/contrib/admin/checks.py b/django/contrib/admin/checks.py
--- a/django/contrib/admin/checks.py
+++ b/django/contrib/admin/checks.py
@@ -771,10 +771,11 @@ def _check_readonly_fields_item(self, obj, field_name, label):
except FieldDoesNotExist:
return [
... | diff --git a/tests/admin_checks/tests.py b/tests/admin_checks/tests.py
--- a/tests/admin_checks/tests.py
+++ b/tests/admin_checks/tests.py
@@ -798,8 +798,9 @@ class SongAdmin(admin.ModelAdmin):
errors = SongAdmin(Song, AdminSite()).check()
expected = [
checks.Error(
- "The ... | ModelAdmin: Error message for readonly_fields's check does not include the field name
Description
When subclassing a ModelAdmin, the current error message for the readonly_fields would indicate the index of the value at fault but it will not include the field's name (from the test suite):
The value of 'readonly_field... | 2023-05-26T13:41:37Z | 5.0 | ["test_nonexistent_field (admin_checks.tests.SystemChecksTestCase.test_nonexistent_field)", "test_nonexistent_field_on_inline (admin_checks.tests.SystemChecksTestCase.test_nonexistent_field_on_inline)"] | ["test_admin_check_ignores_import_error_in_middleware (admin_checks.tests.SystemChecksTestCase.test_admin_check_ignores_import_error_in_middleware)", "test_allows_checks_relying_on_other_modeladmins (admin_checks.tests.SystemChecksTestCase.test_allows_checks_relying_on_other_modeladmins)", "test_app_label_in_admin_chec... | 4a72da71001f154ea60906a2f74898d32b7322a7 | <15 min fix | import collections
from itertools import chain
from django.apps import apps
from django.conf import settings
from django.contrib.admin.utils import NotRelationField, flatten, get_fields_from_path
from django.core import checks
from django.core.exceptions import FieldDoesNotExist
from django.db import models
from djang... | [
[
771,
781
]
] | django/contrib/admin/checks.py | python:3.11 | |
django/django | django__django-17029 | 953f29f700a60fc09b08b2c2270c12c447490c6a | diff --git a/django/apps/registry.py b/django/apps/registry.py
--- a/django/apps/registry.py
+++ b/django/apps/registry.py
@@ -373,6 +373,7 @@ def clear_cache(self):
This is mostly used in tests.
"""
+ self.get_swappable_settings_name.cache_clear()
# Call expire cache on each model. ... | diff --git a/tests/apps/tests.py b/tests/apps/tests.py
--- a/tests/apps/tests.py
+++ b/tests/apps/tests.py
@@ -197,6 +197,17 @@ def test_get_model(self):
with self.assertRaises(ValueError):
apps.get_model("admin_LogEntry")
+ @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
+ def test... | Apps.clear_cache() does not clear get_swappable_settings_name cache.
Description
We use apps.clear_cache() in django-stubs to be able to reset the previous state on consequential mypy runs.
Code: https://github.com/typeddjango/django-stubs/pull/1601/files#diff-c49d8fe2cd0a58fad3c36ab3a88c7745e9622f3098e60cd512953eb1... | Thanks for the report, tentatively accepted. | 2023-06-29T13:18:26Z | 5.0 | ["test_clear_cache (apps.tests.AppsTests.test_clear_cache)"] | ["test_app_default_auto_field (apps.tests.AppConfigTests.test_app_default_auto_field)", "test_default_auto_field_setting (apps.tests.AppConfigTests.test_default_auto_field_setting)", "If single element in __path__, use it (in preference to __file__).", "If the __path__ attr contains duplicate paths and there is no", "I... | 4a72da71001f154ea60906a2f74898d32b7322a7 | <15 min fix | import functools
import sys
import threading
import warnings
from collections import Counter, defaultdict
from functools import partial
from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured
from .config import AppConfig
class Apps:
"""
A registry that stores the configuration of insta... | [
[
373,
379
]
] | django/apps/registry.py | python:3.11 |
django/django | django__django-17087 | 4a72da71001f154ea60906a2f74898d32b7322a7 | diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py
--- a/django/db/migrations/serializer.py
+++ b/django/db/migrations/serializer.py
@@ -168,7 +168,7 @@ def serialize(self):
):
klass = self.value.__self__
module = klass.__module__
- return ... | diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py
--- a/tests/migrations/test_writer.py
+++ b/tests/migrations/test_writer.py
@@ -211,6 +211,10 @@ class NestedChoices(models.TextChoices):
X = "X", "X value"
Y = "Y", "Y value"
+ @classmethod
+ def method(cls... | Class methods from nested classes cannot be used as Field.default.
Description
(last modified by Mariusz Felisiak)
Given the following model:
class Profile(models.Model):
class Capability(models.TextChoices):
BASIC = ("BASIC", "Basic")
PROFESSIONAL = ("PROFESSIONAL", "Professional")
@classmethod
d... | Thanks for the report. It seems that FunctionTypeSerializer should use __qualname__ instead of __name__: django/db/migrations/serializer.py diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py index d88cda6e20..06657ebaab 100644 a b class FunctionTypeSerializer(BaseSerializer): 168168 ):... | 2023-07-17T20:28:41Z | 5.0 | ["test_serialize_nested_class_method (migrations.test_writer.WriterTests.test_serialize_nested_class_method)"] | ["test_args_kwargs_signature (migrations.test_writer.OperationWriterTests.test_args_kwargs_signature)", "test_args_signature (migrations.test_writer.OperationWriterTests.test_args_signature)", "test_empty_signature (migrations.test_writer.OperationWriterTests.test_empty_signature)", "test_expand_args_signature (migrati... | 4a72da71001f154ea60906a2f74898d32b7322a7 | <15 min fix | import builtins
import collections.abc
import datetime
import decimal
import enum
import functools
import math
import os
import pathlib
import re
import types
import uuid
from django.conf import SettingsReference
from django.db import models
from django.db.migrations.operations.base import Operation
from django.db.mig... | [
[
168,
174
]
] | django/db/migrations/serializer.py | python:3.11 |
django/django | django__django-9296 | 84322a29ce9b0940335f8ab3d60e55192bef1e50 | diff --git a/django/core/paginator.py b/django/core/paginator.py
--- a/django/core/paginator.py
+++ b/django/core/paginator.py
@@ -34,6 +34,10 @@ def __init__(self, object_list, per_page, orphans=0,
self.orphans = int(orphans)
self.allow_empty_first_page = allow_empty_first_page
+ def __iter__(se... | diff --git a/tests/pagination/tests.py b/tests/pagination/tests.py
--- a/tests/pagination/tests.py
+++ b/tests/pagination/tests.py
@@ -297,6 +297,13 @@ def test_get_page_empty_object_list_and_allow_empty_first_page_false(self):
with self.assertRaises(EmptyPage):
paginator.get_page(1)
+ def te... | Paginator just implement the __iter__ function
Description
(last modified by Alex Gaynor)
Right now, when you want to iter into all the pages of a Paginator object you to use the page_range function. It would be more logical and naturel to use the normal python of doing that by implementing the iter function li... | Reformatted, please use the preview button in the future.
I'm not sure that's common enough functionality to worry about.
So, some 9 years later we have a PR with this exact suggestion implemented... I'm going to reopen and Accept. Seems reasonable enough, and it's a small addition to enable a kind-of-expected behavio... | 2017-10-27T11:10:04Z | 3.1 | ["test_paginator_iteration (pagination.tests.PaginationTests)"] | ["test_count_does_not_silence_attribute_error (pagination.tests.PaginationTests)", "test_count_does_not_silence_type_error (pagination.tests.PaginationTests)", "test_float_integer_page (pagination.tests.PaginationTests)", "test_get_page (pagination.tests.PaginationTests)", "Paginator.get_page() with an empty object_lis... | 0668164b4ac93a5be79f5b87fae83c657124d9ab | <15 min fix | import collections.abc
import inspect
import warnings
from math import ceil
from django.utils.functional import cached_property
from django.utils.inspect import method_has_no_args
from django.utils.translation import gettext_lazy as _
class UnorderedObjectListWarning(RuntimeWarning):
pass
class InvalidPage(Exc... | [
[
34,
43
]
] | django/core/paginator.py | python:3.11 |
matplotlib/matplotlib | matplotlib__matplotlib-13989 | a3e2897bfaf9eaac1d6649da535c4e721c89fa69 | diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py
--- a/lib/matplotlib/axes/_axes.py
+++ b/lib/matplotlib/axes/_axes.py
@@ -6686,7 +6686,7 @@ def hist(self, x, bins=None, range=None, density=None, weights=None,
density = bool(density) or bool(normed)
if density and not stacked... | diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py
--- a/lib/matplotlib/tests/test_axes.py
+++ b/lib/matplotlib/tests/test_axes.py
@@ -6369,3 +6369,10 @@ def test_hist_nan_data():
assert np.allclose(bins, nanbins)
assert np.allclose(edges, nanedges)
+
+
+def test_hist_range_a... | hist() no longer respects range=... when density=True
<!--To help us understand and resolve your issue, please fill out the form to the best of your ability.-->
<!--You can feel free to delete the sections that do not apply.-->
### Bug report
**Bug summary**
<!--A short 1-2 sentences that succinctly describes... | :anger: I was about to tag.... | 2019-04-19T01:47:57Z | 3.0 | ["lib/matplotlib/tests/test_axes.py::test_hist_range_and_density"] | ["lib/matplotlib/tests/test_axes.py::test_get_labels", "lib/matplotlib/tests/test_axes.py::test_spy_invalid_kwargs", "lib/matplotlib/tests/test_axes.py::test_twinx_cla", "lib/matplotlib/tests/test_axes.py::test_twinx_axis_scales[png]", "lib/matplotlib/tests/test_axes.py::test_twin_inherit_autoscale_setting", "lib/matpl... | d0628598f8d9ec7b0da6b60e7b29be2067b6ea17 | <15 min fix | import collections.abc
import functools
import itertools
import logging
import math
import operator
from numbers import Number
import numpy as np
from numpy import ma
from matplotlib import _preprocess_data, rcParams
import matplotlib.cbook as cbook
import matplotlib.collections as mcoll
import matplotlib.colors as m... | [
[
6686,
6692
]
] | lib/matplotlib/axes/_axes.py | python:3.11 |
matplotlib/matplotlib | matplotlib__matplotlib-20676 | 6786f437df54ca7780a047203cbcfaa1db8dc542 | diff --git a/lib/matplotlib/widgets.py b/lib/matplotlib/widgets.py
--- a/lib/matplotlib/widgets.py
+++ b/lib/matplotlib/widgets.py
@@ -2156,7 +2156,12 @@ def new_axes(self, ax):
self.artists.append(self._rect)
def _setup_edge_handle(self, props):
- self._edge_handles = ToolLineHandles(self.ax... | diff --git a/lib/matplotlib/tests/test_widgets.py b/lib/matplotlib/tests/test_widgets.py
--- a/lib/matplotlib/tests/test_widgets.py
+++ b/lib/matplotlib/tests/test_widgets.py
@@ -302,6 +302,35 @@ def test_tool_line_handle():
assert tool_line_handle.positions == positions
+@pytest.mark.parametrize('direction', ... | interactive SpanSelector incorrectly forces axes limits to include 0
<!--To help us understand and resolve your issue, please fill out the form to the best of your ability.-->
<!--You can feel free to delete the sections that do not apply.-->
### Bug report
**Bug summary**
**Code for reproduction**
<!--A min... | I can't reproduce (or I don't understand what is the issue). Can you confirm that the following gif is the expected behaviour and that you get something different?

The point is that in th... | 2021-07-19T10:10:07Z | 3.4 | ["lib/matplotlib/tests/test_widgets.py::test_span_selector_bound[horizontal]", "lib/matplotlib/tests/test_widgets.py::test_span_selector_bound[vertical]"] | ["lib/matplotlib/tests/test_widgets.py::test_rectangle_drag[True-new_center0]", "lib/matplotlib/tests/test_widgets.py::test_rectangle_drag[False-new_center1]", "lib/matplotlib/tests/test_widgets.py::test_ellipse", "lib/matplotlib/tests/test_widgets.py::test_rectangle_handles", "lib/matplotlib/tests/test_widgets.py::tes... | f93c0a3dcb82feed0262d758626c90d4002685f3 | <15 min fix | """
GUI neutral widgets
===================
Widgets that are designed to work for any of the GUI backends.
All of these widgets require you to predefine a `matplotlib.axes.Axes`
instance and pass that as the first parameter. Matplotlib doesn't try to
be too smart with respect to layout -- you will have to figure out ... | [
[
2156,
2167
]
] | lib/matplotlib/widgets.py | python:3.11 |
matplotlib/matplotlib | matplotlib__matplotlib-20859 | 64619e53e9d0ed417daba287ac0d3a06943a54d5 | diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py
--- a/lib/matplotlib/legend.py
+++ b/lib/matplotlib/legend.py
@@ -360,7 +360,7 @@ def __init__(
"""
# local import only to avoid circularity
from matplotlib.axes import Axes
- from matplotlib.figure import Figure
+ ... | diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py
--- a/lib/matplotlib/tests/test_legend.py
+++ b/lib/matplotlib/tests/test_legend.py
@@ -871,3 +871,12 @@ def test_handlerline2d():
handles = [mlines.Line2D([0], [0], marker="v")]
leg = ax.legend(handles, ["Aardvark"], numpo... | Adding a legend to a `SubFigure` doesn't work
<!--To help us understand and resolve your issue, please fill out the form to the best of your ability.-->
<!--You can feel free to delete the sections that do not apply.-->
### Bug report
**Bug summary**
<!--A short 1-2 sentences that succinctly describes the bug... | Yep that was just an oversight, not a design decision ;-)
I don't want to complicate this too much, but a further issue arrises even after changing the line I suggest above (let me know if this should be a separate issue)
```python
fig = plt.figure()
subfig = fig.subfigures()
ax = subfig.subplots()
ax.plot([0, 1... | 2021-08-19T09:03:04Z | 3.4 | ["lib/matplotlib/tests/test_legend.py::test_subfigure_legend"] | ["lib/matplotlib/tests/test_legend.py::test_legend_ordereddict", "lib/matplotlib/tests/test_legend.py::test_legend_auto1[png]", "lib/matplotlib/tests/test_legend.py::test_legend_auto1[pdf]", "lib/matplotlib/tests/test_legend.py::test_legend_auto2[png]", "lib/matplotlib/tests/test_legend.py::test_legend_auto2[pdf]", "li... | f93c0a3dcb82feed0262d758626c90d4002685f3 | <15 min fix | """
The legend module defines the Legend class, which is responsible for
drawing legends associated with axes and/or figures.
.. important::
It is unlikely that you would ever create a Legend instance manually.
Most users would normally create a legend via the `~.Axes.legend`
function. For more details on... | [
[
360,
366
],
[
434,
446
]
] | lib/matplotlib/legend.py | python:3.11 |
matplotlib/matplotlib | matplotlib__matplotlib-22719 | a2a1b0a11b993fe5f8fab64b6161e99243a6393c | diff --git a/lib/matplotlib/category.py b/lib/matplotlib/category.py
--- a/lib/matplotlib/category.py
+++ b/lib/matplotlib/category.py
@@ -58,7 +58,7 @@ def convert(value, unit, axis):
is_numlike = all(units.ConversionInterface.is_numlike(v)
and not isinstance(v, (str, bytes))... | diff --git a/lib/matplotlib/tests/test_category.py b/lib/matplotlib/tests/test_category.py
--- a/lib/matplotlib/tests/test_category.py
+++ b/lib/matplotlib/tests/test_category.py
@@ -307,6 +307,15 @@ def test_overriding_units_in_plot(fig_test, fig_ref):
assert y_units is ax.yaxis.units
+def test_no_depreca... | [Bug]: Confusing deprecation warning when empty data passed to axis with category units
### Bug summary
I'm seeing a `MatplotlibDeprecationWarning` when using calling axes methods on empty data structures for axes that are using string unit converters. I think this is either a false alarm or a non-actionable warning... | cc @anntzer from #20334
Oops, sorry. This needs something like
```patch
diff --git i/lib/matplotlib/category.py w/lib/matplotlib/category.py
index c823b68fd9..55f21a57ca 100644
--- i/lib/matplotlib/category.py
+++ w/lib/matplotlib/category.py
@@ -58,7 +58,7 @@ class StrCategoryConverter(units.ConversionInterface... | 2022-03-28T14:42:28Z | 3.5 | ["lib/matplotlib/tests/test_category.py::test_no_deprecation_on_empty_data"] | ["lib/matplotlib/tests/test_category.py::TestUnitData::test_unit[single]", "lib/matplotlib/tests/test_category.py::TestUnitData::test_unit[unicode]", "lib/matplotlib/tests/test_category.py::TestUnitData::test_unit[mixed]", "lib/matplotlib/tests/test_category.py::TestUnitData::test_update", "lib/matplotlib/tests/test_ca... | de98877e3dc45de8dd441d008f23d88738dc015d | <15 min fix | """
Plotting of string "category" data: ``plot(['d', 'f', 'a'], [1, 2, 3])`` will
plot three points with x-axis values of 'd', 'f', 'a'.
See :doc:`/gallery/lines_bars_and_markers/categorical_variables` for an
example.
The module uses Matplotlib's `matplotlib.units` mechanism to convert from
strings to integers and pr... | [
[
58,
64
],
[
230,
236
]
] | lib/matplotlib/category.py | python:3.11 |
matplotlib/matplotlib | matplotlib__matplotlib-23476 | 33a0599711d26dc2b79f851c6daed4947df7c167 | diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py
--- a/lib/matplotlib/figure.py
+++ b/lib/matplotlib/figure.py
@@ -3023,6 +3023,9 @@ def __getstate__(self):
# Set cached renderer to None -- it can't be pickled.
state["_cachedRenderer"] = None
+ # discard any changes to the dpi... | diff --git a/lib/matplotlib/tests/test_figure.py b/lib/matplotlib/tests/test_figure.py
--- a/lib/matplotlib/tests/test_figure.py
+++ b/lib/matplotlib/tests/test_figure.py
@@ -2,6 +2,7 @@
from datetime import datetime
import io
from pathlib import Path
+import pickle
import platform
from threading import Timer
fro... | [Bug]: DPI of a figure is doubled after unpickling on M1 Mac
### Bug summary
When a figure is unpickled, it's dpi is doubled. This behaviour happens every time and if done in a loop it can cause an `OverflowError`.
### Code for reproduction
```python
import numpy as np
import matplotlib
import matplotlib.py... | I suspect this will also affect anything that know how to deal with high-dpi screens.
For, .... reasons..., when we handle high-dpi cases by doubling the dpi on the figure (we have ideas how to fix this, but it is a fair amount of work) when we show it. We are saving the doubled dpi which when re-loaded in doubled ... | 2022-07-22T18:58:22Z | 3.5 | ["lib/matplotlib/tests/test_figure.py::test_unpickle_with_device_pixel_ratio"] | ["lib/matplotlib/tests/test_figure.py::test_align_labels[png]", "lib/matplotlib/tests/test_figure.py::test_align_labels_stray_axes", "lib/matplotlib/tests/test_figure.py::test_figure_label", "lib/matplotlib/tests/test_figure.py::test_fignum_exists", "lib/matplotlib/tests/test_figure.py::test_clf_keyword", "lib/matplotl... | de98877e3dc45de8dd441d008f23d88738dc015d | <15 min fix | """
`matplotlib.figure` implements the following classes:
`Figure`
Top level `~matplotlib.artist.Artist`, which holds all plot elements.
Many methods are implemented in `FigureBase`.
`SubFigure`
A logical figure inside a figure, usually added to a figure (or parent
`SubFigure`) with `Figure.add_subfig... | [
[
3023,
3031
]
] | lib/matplotlib/figure.py | python:3.11 |
matplotlib/matplotlib | matplotlib__matplotlib-24149 | af39f1edffcd828f05cfdd04f2e59506bb4a27bc | diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py
--- a/lib/matplotlib/axes/_axes.py
+++ b/lib/matplotlib/axes/_axes.py
@@ -2182,11 +2182,19 @@ def _convert_dx(dx, x0, xconv, convert):
x0 = cbook._safe_first_finite(x0)
except (TypeError, IndexError, KeyError):
... | diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py
--- a/lib/matplotlib/tests/test_axes.py
+++ b/lib/matplotlib/tests/test_axes.py
@@ -8195,3 +8195,16 @@ def test_bar_leading_nan():
for b in rest:
assert np.isfinite(b.xy).all()
assert np.isfinite(b.get_... | [Bug]: ax.bar raises for all-nan data on matplotlib 3.6.1
### Bug summary
`ax.bar` raises an exception in 3.6.1 when passed only nan data. This irrevocably breaks seaborn's histogram function (which draws and then removes a "phantom" bar to trip the color cycle).
### Code for reproduction
```python
import numpy as ... | This is the PR in question: https://github.com/matplotlib/matplotlib/pull/23751 (although I have not checked is that is causing it).
Thanks @oscargus that indeed looks like the culprit: it asks for the "next" finite value and does not handle the `StopIteration` exception that you get if there isn't one.
> which draws a... | 2022-10-12T22:00:54Z | 3.6 | ["lib/matplotlib/tests/test_axes.py::test_bar_all_nan[png]"] | ["lib/matplotlib/tests/test_axes.py::test_invisible_axes[png]", "lib/matplotlib/tests/test_axes.py::test_get_labels", "lib/matplotlib/tests/test_axes.py::test_repr", "lib/matplotlib/tests/test_axes.py::test_label_loc_vertical[png]", "lib/matplotlib/tests/test_axes.py::test_label_loc_vertical[pdf]", "lib/matplotlib/test... | 73909bcb408886a22e2b84581d6b9e6d9907c813 | <15 min fix | import functools
import itertools
import logging
import math
from numbers import Integral, Number
import numpy as np
from numpy import ma
import matplotlib as mpl
import matplotlib.category # Register category unit converter as side-effect.
import matplotlib.cbook as cbook
import matplotlib.collections as mcoll
impo... | [
[
2182,
2200
]
] | lib/matplotlib/axes/_axes.py | python:3.11 |
matplotlib/matplotlib | matplotlib__matplotlib-24177 | 493d608e39d32a67173c23a7bbc47d6bfedcef61 | diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py
--- a/lib/matplotlib/axes/_base.py
+++ b/lib/matplotlib/axes/_base.py
@@ -2434,7 +2434,7 @@ def _update_patch_limits(self, patch):
# Get all vertices on the path
# Loop through each segment to get extrema for Bezier curve section... | diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py
--- a/lib/matplotlib/tests/test_axes.py
+++ b/lib/matplotlib/tests/test_axes.py
@@ -8165,6 +8165,58 @@ def test_bezier_autoscale():
assert ax.get_ylim()[0] == -0.5
+def test_small_autoscale():
+ # Check that paths with small ... | [Bug]: ax.hist density not auto-scaled when using histtype='step'
### Bug summary
I need to plot a histogram of some data (generated by `numpy.save` in binary format) from my work using the `matplotlib.axes.Axes.hist` function. I noted that the histogram's density axis (when setting `density=True`) is not automatica... | I cannot see a difference between your left and right side plot so it's not clear what difference you are concerned about.
> I cannot see a difference between your left and right side plot so it's not clear what difference you are concerned about.
Thanks for the quick reply. I updated my post with the expected and ... | 2022-10-15T10:52:31Z | 3.6 | ["lib/matplotlib/tests/test_axes.py::test_small_autoscale"] | ["lib/matplotlib/tests/test_axes.py::test_invisible_axes[png]", "lib/matplotlib/tests/test_axes.py::test_get_labels", "lib/matplotlib/tests/test_axes.py::test_repr", "lib/matplotlib/tests/test_axes.py::test_label_loc_vertical[png]", "lib/matplotlib/tests/test_axes.py::test_label_loc_vertical[pdf]", "lib/matplotlib/test... | 73909bcb408886a22e2b84581d6b9e6d9907c813 | <15 min fix | from collections.abc import MutableSequence
from contextlib import ExitStack
import functools
import inspect
import itertools
import logging
from numbers import Real
from operator import attrgetter
import types
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, _docstring, offsetbox
impor... | [
[
2434,
2440
]
] | lib/matplotlib/axes/_base.py | python:3.11 |
matplotlib/matplotlib | matplotlib__matplotlib-24570 | 8f0003ae902952372824c9917975fb372c026a42 | diff --git a/lib/matplotlib/offsetbox.py b/lib/matplotlib/offsetbox.py
--- a/lib/matplotlib/offsetbox.py
+++ b/lib/matplotlib/offsetbox.py
@@ -166,10 +166,10 @@ def _get_aligned_offsets(hd_list, height, align="baseline"):
descent = max(d for h, d in hd_list)
height = height_descent + descent
... | diff --git a/lib/matplotlib/tests/test_offsetbox.py b/lib/matplotlib/tests/test_offsetbox.py
--- a/lib/matplotlib/tests/test_offsetbox.py
+++ b/lib/matplotlib/tests/test_offsetbox.py
@@ -13,7 +13,7 @@
from matplotlib.offsetbox import (
AnchoredOffsetbox, AnnotationBbox, AnchoredText, DrawingArea, OffsetBox,
- ... | [Bug]: `align` in `HPacker` is reversed
### Bug summary
For the `align` parameter in `HPacker`, the options `top` and `bottom` seems reversed
### Code for reproduction
```python
import matplotlib.pyplot as plt
from matplotlib.offsetbox import DrawingArea, HPacker, VPacker, AnchoredOffsetbox, TextArea
from matplotl... | This indeed seems incorrect, however, I'm not sure what the path to fixing it is even that it's likely been that way for quite a while and swapping back will break anyone who had corrected for the mistake.
I can't see that we use this internally, and it's obviously untested.
> This indeed seems incorrect, howeve... | 2022-11-30T15:50:17Z | 3.6 | ["lib/matplotlib/tests/test_offsetbox.py::test_packers[bottom]", "lib/matplotlib/tests/test_offsetbox.py::test_packers[top]"] | ["lib/matplotlib/tests/test_offsetbox.py::test_offsetbox_clipping[png]", "lib/matplotlib/tests/test_offsetbox.py::test_offsetbox_clipping[pdf]", "lib/matplotlib/tests/test_offsetbox.py::test_offsetbox_clip_children", "lib/matplotlib/tests/test_offsetbox.py::test_offsetbox_loc_codes", "lib/matplotlib/tests/test_offsetbo... | 73909bcb408886a22e2b84581d6b9e6d9907c813 | <15 min fix | r"""
Container classes for `.Artist`\s.
`OffsetBox`
The base of all container artists defined in this module.
`AnchoredOffsetbox`, `AnchoredText`
Anchor and align an arbitrary `.Artist` or a text relative to the parent
axes or a specific anchor point.
`DrawingArea`
A container with fixed width and he... | [
[
166,
175
]
] | lib/matplotlib/offsetbox.py | python:3.11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.