repo
stringclasses
12 values
instance_id
stringlengths
18
32
base_commit
stringlengths
40
40
patch
stringlengths
344
4.93k
test_patch
stringlengths
398
14.4k
problem_statement
stringlengths
230
24.8k
hints_text
stringlengths
0
59.9k
created_at
stringlengths
20
20
version
stringlengths
3
4
FAIL_TO_PASS
stringlengths
12
25.6k
PASS_TO_PASS
stringlengths
2
124k
environment_setup_commit
stringlengths
40
40
astropy/astropy
astropy__astropy-14182
a5917978be39d13cd90b517e1de4e7a539ffaa48
diff --git a/astropy/io/ascii/rst.py b/astropy/io/ascii/rst.py --- a/astropy/io/ascii/rst.py +++ b/astropy/io/ascii/rst.py @@ -27,7 +27,6 @@ def get_fixedwidth_params(self, line): class SimpleRSTData(FixedWidthData): - start_line = 3 end_line = -1 splitter_class = FixedWidthTwoLineDataSplitter @@ -39,12 +38,29 @@ class RST(FixedWidth): Example:: - ==== ===== ====== - Col1 Col2 Col3 - ==== ===== ====== - 1 2.3 Hello - 2 4.5 Worlds - ==== ===== ====== + >>> from astropy.table import QTable + >>> import astropy.units as u + >>> import sys + >>> tbl = QTable({"wave": [350, 950] * u.nm, "response": [0.7, 1.2] * u.count}) + >>> tbl.write(sys.stdout, format="ascii.rst") + ===== ======== + wave response + ===== ======== + 350.0 0.7 + 950.0 1.2 + ===== ======== + + Like other fixed-width formats, when writing a table you can provide ``header_rows`` + to specify a list of table rows to output as the header. For example:: + + >>> tbl.write(sys.stdout, format="ascii.rst", header_rows=['name', 'unit']) + ===== ======== + wave response + nm ct + ===== ======== + 350.0 0.7 + 950.0 1.2 + ===== ======== Currently there is no support for reading tables which utilize continuation lines, or for ones which define column spans through the use of an additional @@ -57,10 +73,15 @@ class RST(FixedWidth): data_class = SimpleRSTData header_class = SimpleRSTHeader - def __init__(self): - super().__init__(delimiter_pad=None, bookend=False) + def __init__(self, header_rows=None): + super().__init__(delimiter_pad=None, bookend=False, header_rows=header_rows) def write(self, lines): lines = super().write(lines) - lines = [lines[1]] + lines + [lines[1]] + idx = len(self.header.header_rows) + lines = [lines[idx]] + lines + [lines[idx]] return lines + + def read(self, table): + self.data.start_line = 2 + len(self.header.header_rows) + return super().read(table)
diff --git a/astropy/io/ascii/tests/test_rst.py b/astropy/io/ascii/tests/test_rst.py --- a/astropy/io/ascii/tests/test_rst.py +++ b/astropy/io/ascii/tests/test_rst.py @@ -2,7 +2,11 @@ from io import StringIO +import numpy as np + +import astropy.units as u from astropy.io import ascii +from astropy.table import QTable from .common import assert_almost_equal, assert_equal @@ -185,3 +189,27 @@ def test_write_normal(): ==== ========= ==== ==== """, ) + + +def test_rst_with_header_rows(): + """Round-trip a table with header_rows specified""" + lines = [ + "======= ======== ====", + " wave response ints", + " nm ct ", + "float64 float32 int8", + "======= ======== ====", + " 350.0 1.0 1", + " 950.0 2.0 2", + "======= ======== ====", + ] + tbl = QTable.read(lines, format="ascii.rst", header_rows=["name", "unit", "dtype"]) + assert tbl["wave"].unit == u.nm + assert tbl["response"].unit == u.ct + assert tbl["wave"].dtype == np.float64 + assert tbl["response"].dtype == np.float32 + assert tbl["ints"].dtype == np.int8 + + out = StringIO() + tbl.write(out, format="ascii.rst", header_rows=["name", "unit", "dtype"]) + assert out.getvalue().splitlines() == lines
Please support header rows in RestructuredText output ### Description It would be great if the following would work: ```Python >>> from astropy.table import QTable >>> import astropy.units as u >>> import sys >>> tbl = QTable({'wave': [350,950]*u.nm, 'response': [0.7, 1.2]*u.count}) >>> tbl.write(sys.stdout, format="ascii.rst") ===== ======== wave response ===== ======== 350.0 0.7 950.0 1.2 ===== ======== >>> tbl.write(sys.stdout, format="ascii.fixed_width", header_rows=["name", "unit"]) | wave | response | | nm | ct | | 350.0 | 0.7 | | 950.0 | 1.2 | >>> tbl.write(sys.stdout, format="ascii.rst", header_rows=["name", "unit"]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3/dist-packages/astropy/table/connect.py", line 129, in __call__ self.registry.write(instance, *args, **kwargs) File "/usr/lib/python3/dist-packages/astropy/io/registry/core.py", line 369, in write return writer(data, *args, **kwargs) File "/usr/lib/python3/dist-packages/astropy/io/ascii/connect.py", line 26, in io_write return write(table, filename, **kwargs) File "/usr/lib/python3/dist-packages/astropy/io/ascii/ui.py", line 856, in write writer = get_writer(Writer=Writer, fast_writer=fast_writer, **kwargs) File "/usr/lib/python3/dist-packages/astropy/io/ascii/ui.py", line 800, in get_writer writer = core._get_writer(Writer, fast_writer, **kwargs) File "/usr/lib/python3/dist-packages/astropy/io/ascii/core.py", line 1719, in _get_writer writer = Writer(**writer_kwargs) TypeError: RST.__init__() got an unexpected keyword argument 'header_rows' ``` ### Additional context RestructuredText output is a great way to fill autogenerated documentation with content, so having this flexible makes the life easier `:-)`
2022-12-16T11:13:37Z
5.1
["astropy/io/ascii/tests/test_rst.py::test_rst_with_header_rows"]
["astropy/io/ascii/tests/test_rst.py::test_read_normal", "astropy/io/ascii/tests/test_rst.py::test_read_normal_names", "astropy/io/ascii/tests/test_rst.py::test_read_normal_names_include", "astropy/io/ascii/tests/test_rst.py::test_read_normal_exclude", "astropy/io/ascii/tests/test_rst.py::test_read_unbounded_right_column", "astropy/io/ascii/tests/test_rst.py::test_read_unbounded_right_column_header", "astropy/io/ascii/tests/test_rst.py::test_read_right_indented_table", "astropy/io/ascii/tests/test_rst.py::test_trailing_spaces_in_row_definition", "astropy/io/ascii/tests/test_rst.py::test_write_normal"]
5f74eacbcc7fff707a44d8eb58adaa514cb7dcb5
astropy/astropy
astropy__astropy-14365
7269fa3e33e8d02485a647da91a5a2a60a06af61
diff --git a/astropy/io/ascii/qdp.py b/astropy/io/ascii/qdp.py --- a/astropy/io/ascii/qdp.py +++ b/astropy/io/ascii/qdp.py @@ -68,7 +68,7 @@ def _line_type(line, delimiter=None): _new_re = rf"NO({sep}NO)+" _data_re = rf"({_decimal_re}|NO|[-+]?nan)({sep}({_decimal_re}|NO|[-+]?nan))*)" _type_re = rf"^\s*((?P<command>{_command_re})|(?P<new>{_new_re})|(?P<data>{_data_re})?\s*(\!(?P<comment>.*))?\s*$" - _line_type_re = re.compile(_type_re) + _line_type_re = re.compile(_type_re, re.IGNORECASE) line = line.strip() if not line: return "comment" @@ -306,7 +306,7 @@ def _get_tables_from_qdp_file(qdp_file, input_colnames=None, delimiter=None): values = [] for v in line.split(delimiter): - if v == "NO": + if v.upper() == "NO": values.append(np.ma.masked) else: # Understand if number is int or float
diff --git a/astropy/io/ascii/tests/test_qdp.py b/astropy/io/ascii/tests/test_qdp.py --- a/astropy/io/ascii/tests/test_qdp.py +++ b/astropy/io/ascii/tests/test_qdp.py @@ -43,7 +43,18 @@ def test_get_tables_from_qdp_file(tmp_path): assert np.isclose(table2["MJD_nerr"][0], -2.37847222222222e-05) -def test_roundtrip(tmp_path): +def lowercase_header(value): + """Make every non-comment line lower case.""" + lines = [] + for line in value.splitlines(): + if not line.startswith("!"): + line = line.lower() + lines.append(line) + return "\n".join(lines) + + [email protected]("lowercase", [False, True]) +def test_roundtrip(tmp_path, lowercase): example_qdp = """ ! Swift/XRT hardness ratio of trigger: XXXX, name: BUBU X-2 ! Columns are as labelled @@ -70,6 +81,8 @@ def test_roundtrip(tmp_path): 53000.123456 2.37847222222222e-05 -2.37847222222222e-05 -0.292553 -0.374935 NO 1.14467592592593e-05 -1.14467592592593e-05 0.000000 NO """ + if lowercase: + example_qdp = lowercase_header(example_qdp) path = str(tmp_path / "test.qdp") path2 = str(tmp_path / "test2.qdp")
ascii.qdp Table format assumes QDP commands are upper case ### Description ascii.qdp assumes that commands in a QDP file are upper case, for example, for errors they must be "READ SERR 1 2" whereas QDP itself is not case sensitive and case use "read serr 1 2". As many QDP files are created by hand, the expectation that all commands be all-caps should be removed. ### Expected behavior The following qdp file should read into a `Table` with errors, rather than crashing. ``` read serr 1 2 1 0.5 1 0.5 ``` ### How to Reproduce Create a QDP file: ``` > cat > test.qdp read serr 1 2 1 0.5 1 0.5 <EOF> > python Python 3.10.9 (main, Dec 7 2022, 02:03:23) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from astropy.table import Table >>> Table.read('test.qdp',format='ascii.qdp') WARNING: table_id not specified. Reading the first available table [astropy.io.ascii.qdp] Traceback (most recent call last): ... raise ValueError(f'Unrecognized QDP line: {line}') ValueError: Unrecognized QDP line: read serr 1 2 ``` Running "qdp test.qdp" works just fine. ### Versions Python 3.10.9 (main, Dec 7 2022, 02:03:23) [Clang 13.0.0 (clang-1300.0.29.30)] astropy 5.1 Numpy 1.24.1 pyerfa 2.0.0.1 Scipy 1.10.0 Matplotlib 3.6.3
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 details. GitHub issues in the Astropy repository are used to track bug reports and feature requests; If your issue poses a question about how to use Astropy, please instead raise your question in the [Astropy Discourse user forum](https://community.openastronomy.org/c/astropy/8) and close this issue. If you feel that this issue has not been responded to in a timely manner, please send a message directly to the [development mailing list](http://groups.google.com/group/astropy-dev). If the issue is urgent or sensitive in nature (e.g., a security vulnerability) please send an e-mail directly to the private e-mail [email protected]. Huh, so we do have this format... https://docs.astropy.org/en/stable/io/ascii/index.html @taldcroft , you know anything about this? This is the format I'm using, which has the issue: https://docs.astropy.org/en/stable/api/astropy.io.ascii.QDP.html The issue is that the regex that searches for QDP commands is not case insensitive. This attached patch fixes the issue, but I'm sure there's a better way of doing it. [qdp.patch](https://github.com/astropy/astropy/files/10667923/qdp.patch) @jak574 - the fix is probably as simple as that. Would you like to put in a bugfix PR?
2023-02-06T19:20:34Z
5.1
["astropy/io/ascii/tests/test_qdp.py::test_roundtrip[True]"]
["astropy/io/ascii/tests/test_qdp.py::test_get_tables_from_qdp_file", "astropy/io/ascii/tests/test_qdp.py::test_roundtrip[False]", "astropy/io/ascii/tests/test_qdp.py::test_read_example", "astropy/io/ascii/tests/test_qdp.py::test_roundtrip_example", "astropy/io/ascii/tests/test_qdp.py::test_roundtrip_example_comma", "astropy/io/ascii/tests/test_qdp.py::test_read_write_simple", "astropy/io/ascii/tests/test_qdp.py::test_read_write_simple_specify_name", "astropy/io/ascii/tests/test_qdp.py::test_get_lines_from_qdp"]
5f74eacbcc7fff707a44d8eb58adaa514cb7dcb5
astropy/astropy
astropy__astropy-7746
d5bd3f68bb6d5ce3a61bdce9883ee750d1afade5
diff --git a/astropy/wcs/wcs.py b/astropy/wcs/wcs.py --- a/astropy/wcs/wcs.py +++ b/astropy/wcs/wcs.py @@ -1212,6 +1212,9 @@ def _array_converter(self, func, sky, *args, ra_dec_order=False): """ def _return_list_of_arrays(axes, origin): + if any([x.size == 0 for x in axes]): + return axes + try: axes = np.broadcast_arrays(*axes) except ValueError: @@ -1235,6 +1238,8 @@ def _return_single_array(xy, origin): raise ValueError( "When providing two arguments, the array must be " "of shape (N, {0})".format(self.naxis)) + if 0 in xy.shape: + return xy if ra_dec_order and sky == 'input': xy = self._denormalize_sky(xy) result = func(xy, origin)
diff --git a/astropy/wcs/tests/test_wcs.py b/astropy/wcs/tests/test_wcs.py --- a/astropy/wcs/tests/test_wcs.py +++ b/astropy/wcs/tests/test_wcs.py @@ -1093,3 +1093,21 @@ def test_keyedsip(): assert isinstance( w.sip, wcs.Sip ) assert w.sip.crpix[0] == 2048 assert w.sip.crpix[1] == 1026 + + +def test_zero_size_input(): + with fits.open(get_pkg_data_filename('data/sip.fits')) as f: + w = wcs.WCS(f[0].header) + + inp = np.zeros((0, 2)) + assert_array_equal(inp, w.all_pix2world(inp, 0)) + assert_array_equal(inp, w.all_world2pix(inp, 0)) + + inp = [], [1] + result = w.all_pix2world([], [1], 0) + assert_array_equal(inp[0], result[0]) + assert_array_equal(inp[1], result[1]) + + result = w.all_world2pix([], [1], 0) + assert_array_equal(inp[0], result[0]) + assert_array_equal(inp[1], result[1])
Issue when passing empty lists/arrays to WCS transformations The following should not fail but instead should return empty lists/arrays: ``` In [1]: from astropy.wcs import WCS In [2]: wcs = WCS('2MASS_h.fits') In [3]: wcs.wcs_pix2world([], [], 0) --------------------------------------------------------------------------- InconsistentAxisTypesError Traceback (most recent call last) <ipython-input-3-e2cc0e97941a> in <module>() ----> 1 wcs.wcs_pix2world([], [], 0) ~/Dropbox/Code/Astropy/astropy/astropy/wcs/wcs.py in wcs_pix2world(self, *args, **kwargs) 1352 return self._array_converter( 1353 lambda xy, o: self.wcs.p2s(xy, o)['world'], -> 1354 'output', *args, **kwargs) 1355 wcs_pix2world.__doc__ = """ 1356 Transforms pixel coordinates to world coordinates by doing ~/Dropbox/Code/Astropy/astropy/astropy/wcs/wcs.py in _array_converter(self, func, sky, ra_dec_order, *args) 1267 "a 1-D array for each axis, followed by an origin.") 1268 -> 1269 return _return_list_of_arrays(axes, origin) 1270 1271 raise TypeError( ~/Dropbox/Code/Astropy/astropy/astropy/wcs/wcs.py in _return_list_of_arrays(axes, origin) 1223 if ra_dec_order and sky == 'input': 1224 xy = self._denormalize_sky(xy) -> 1225 output = func(xy, origin) 1226 if ra_dec_order and sky == 'output': 1227 output = self._normalize_sky(output) ~/Dropbox/Code/Astropy/astropy/astropy/wcs/wcs.py in <lambda>(xy, o) 1351 raise ValueError("No basic WCS settings were created.") 1352 return self._array_converter( -> 1353 lambda xy, o: self.wcs.p2s(xy, o)['world'], 1354 'output', *args, **kwargs) 1355 wcs_pix2world.__doc__ = """ InconsistentAxisTypesError: ERROR 4 in wcsp2s() at line 2646 of file cextern/wcslib/C/wcs.c: ncoord and/or nelem inconsistent with the wcsprm. ```
2018-08-20T14:07:20Z
1.3
["astropy/wcs/tests/test_wcs.py::test_zero_size_input"]
["astropy/wcs/tests/test_wcs.py::TestMaps::test_consistency", "astropy/wcs/tests/test_wcs.py::TestMaps::test_maps", "astropy/wcs/tests/test_wcs.py::TestSpectra::test_consistency", "astropy/wcs/tests/test_wcs.py::TestSpectra::test_spectra", "astropy/wcs/tests/test_wcs.py::test_fixes", "astropy/wcs/tests/test_wcs.py::test_outside_sky", "astropy/wcs/tests/test_wcs.py::test_pix2world", "astropy/wcs/tests/test_wcs.py::test_load_fits_path", "astropy/wcs/tests/test_wcs.py::test_dict_init", "astropy/wcs/tests/test_wcs.py::test_extra_kwarg", "astropy/wcs/tests/test_wcs.py::test_3d_shapes", "astropy/wcs/tests/test_wcs.py::test_preserve_shape", "astropy/wcs/tests/test_wcs.py::test_broadcasting", "astropy/wcs/tests/test_wcs.py::test_shape_mismatch", "astropy/wcs/tests/test_wcs.py::test_invalid_shape", "astropy/wcs/tests/test_wcs.py::test_warning_about_defunct_keywords", "astropy/wcs/tests/test_wcs.py::test_warning_about_defunct_keywords_exception", "astropy/wcs/tests/test_wcs.py::test_to_header_string", "astropy/wcs/tests/test_wcs.py::test_to_fits", "astropy/wcs/tests/test_wcs.py::test_to_header_warning", "astropy/wcs/tests/test_wcs.py::test_no_comments_in_header", "astropy/wcs/tests/test_wcs.py::test_find_all_wcs_crash", "astropy/wcs/tests/test_wcs.py::test_validate", "astropy/wcs/tests/test_wcs.py::test_validate_with_2_wcses", "astropy/wcs/tests/test_wcs.py::test_crpix_maps_to_crval", "astropy/wcs/tests/test_wcs.py::test_all_world2pix", "astropy/wcs/tests/test_wcs.py::test_scamp_sip_distortion_parameters", "astropy/wcs/tests/test_wcs.py::test_fixes2", "astropy/wcs/tests/test_wcs.py::test_unit_normalization", "astropy/wcs/tests/test_wcs.py::test_footprint_to_file", "astropy/wcs/tests/test_wcs.py::test_validate_faulty_wcs", "astropy/wcs/tests/test_wcs.py::test_error_message", "astropy/wcs/tests/test_wcs.py::test_out_of_bounds", "astropy/wcs/tests/test_wcs.py::test_calc_footprint_1", "astropy/wcs/tests/test_wcs.py::test_calc_footprint_2", "astropy/wcs/tests/test_wcs.py::test_calc_footprint_3", "astropy/wcs/tests/test_wcs.py::test_sip", "astropy/wcs/tests/test_wcs.py::test_printwcs", "astropy/wcs/tests/test_wcs.py::test_invalid_spherical", "astropy/wcs/tests/test_wcs.py::test_no_iteration", "astropy/wcs/tests/test_wcs.py::test_sip_tpv_agreement", "astropy/wcs/tests/test_wcs.py::test_tpv_copy", "astropy/wcs/tests/test_wcs.py::test_hst_wcs", "astropy/wcs/tests/test_wcs.py::test_list_naxis", "astropy/wcs/tests/test_wcs.py::test_sip_broken", "astropy/wcs/tests/test_wcs.py::test_no_truncate_crval", "astropy/wcs/tests/test_wcs.py::test_no_truncate_crval_try2", "astropy/wcs/tests/test_wcs.py::test_no_truncate_crval_p17", "astropy/wcs/tests/test_wcs.py::test_no_truncate_using_compare", "astropy/wcs/tests/test_wcs.py::test_passing_ImageHDU", "astropy/wcs/tests/test_wcs.py::test_inconsistent_sip", "astropy/wcs/tests/test_wcs.py::test_bounds_check", "astropy/wcs/tests/test_wcs.py::test_naxis", "astropy/wcs/tests/test_wcs.py::test_sip_with_altkey", "astropy/wcs/tests/test_wcs.py::test_to_fits_1", "astropy/wcs/tests/test_wcs.py::test_keyedsip"]
848c8fa21332abd66b44efe3cb48b72377fb32cc
django/django
django__django-10924
bceadd2788dc2dad53eba0caae172bd8522fd483
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 @@ -1709,7 +1709,7 @@ def get_prep_value(self, value): def formfield(self, **kwargs): return super().formfield(**{ - 'path': self.path, + 'path': self.path() if callable(self.path) else self.path, 'match': self.match, 'recursive': self.recursive, 'form_class': forms.FilePathField,
diff --git a/tests/model_fields/test_filepathfield.py b/tests/model_fields/test_filepathfield.py new file mode 100644 --- /dev/null +++ b/tests/model_fields/test_filepathfield.py @@ -0,0 +1,22 @@ +import os + +from django.db.models import FilePathField +from django.test import SimpleTestCase + + +class FilePathFieldTests(SimpleTestCase): + def test_path(self): + path = os.path.dirname(__file__) + field = FilePathField(path=path) + self.assertEqual(field.path, path) + self.assertEqual(field.formfield().path, path) + + def test_callable_path(self): + path = os.path.dirname(__file__) + + def generate_path(): + return path + + field = FilePathField(path=generate_path) + self.assertEqual(field.path(), path) + self.assertEqual(field.formfield().path, path)
Allow FilePathField path to accept a callable. Description I have a special case where I want to create a model containing the path to some local files on the server/dev machine. Seeing as the place where these files are stored is different on different machines I have the following: import os from django.conf import settings from django.db import models class LocalFiles(models.Model): name = models.CharField(max_length=255) file = models.FilePathField(path=os.path.join(settings.LOCAL_FILE_DIR, 'example_dir')) Now when running manage.py makemigrations it will resolve the path based on the machine it is being run on. Eg: /home/<username>/server_files/example_dir I had to manually change the migration to include the os.path.join() part to not break this when running the migration on production/other machine.
So, to clarify, what exactly is the bug/feature proposal/issue here? The way I see it, you're supposed to use os.path.join() and LOCAL_FILE_DIR to define a relative path. It's sort of like how we use BASE_DIR to define relative paths in a lot of other places. Could you please clarify a bit more as to what the issue is so as to make it easier to test and patch? Replying to Hemanth V. Alluri: So, to clarify, what exactly is the bug/feature proposal/issue here? The way I see it, you're supposed to use os.path.join() and LOCAL_FILE_DIR to define a relative path. It's sort of like how we use BASE_DIR to define relative paths in a lot of other places. Could you please clarify a bit more as to what the issue is so as to make it easier to test and patch? LOCAL_FILE_DIR doesn't have to be the same on another machine, and in this case it isn't the same on the production server. So the os.path.join() will generate a different path on my local machine compared to the server. When i ran ./manage.py makemigrations the Migration had the path resolved "hardcoded" to my local path, which will not work when applying that path on the production server. This will also happen when using the BASE_DIR setting as the path of your FilePathField, seeing as that's based on the location of your project folder, which will almost always be on a different location. My suggestion would be to let makemigrations not resolve the path and instead keep the os.path.join(), which I have now done manually. More importantly would be to retain the LOCAL_FILE_DIR setting in the migration. Replying to Sebastiaan Arendsen: Replying to Hemanth V. Alluri: So, to clarify, what exactly is the bug/feature proposal/issue here? The way I see it, you're supposed to use os.path.join() and LOCAL_FILE_DIR to define a relative path. It's sort of like how we use BASE_DIR to define relative paths in a lot of other places. Could you please clarify a bit more as to what the issue is so as to make it easier to test and patch? LOCAL_FILE_DIR doesn't have to be the same on another machine, and in this case it isn't the same on the production server. So the os.path.join() will generate a different path on my local machine compared to the server. When i ran ./manage.py makemigrations the Migration had the path resolved "hardcoded" to my local path, which will not work when applying that path on the production server. This will also happen when using the BASE_DIR setting as the path of your FilePathField, seeing as that's based on the location of your project folder, which will almost always be on a different location. My suggestion would be to let makemigrations not resolve the path and instead keep the os.path.join(), which I have now done manually. More importantly would be to retain the LOCAL_FILE_DIR setting in the migration. Please look at this ticket: https://code.djangoproject.com/ticket/6896 I think that something like what sandychapman suggested about an extra flag would be cool if the design decision was approved and if there were no restrictions in the implementation for such a change to be made. But that's up to the developers who have had more experience with the project to decide, not me. This seems a reasonable use-case: allow FilePathField to vary path by environment. The trouble with os.path.join(...) is that it will always be interpreted at import time, when the class definition is loaded. (The (...) say, ...and call this....) The way to defer that would be to all path to accept a callable, similarly to how FileField's upload_to takes a callable. It should be enough to evaluate the callable in FilePathField.__init__(). Experimenting with generating a migration looks good. (The operation gives path the fully qualified import path of the specified callable, just as with upload_to.) I'm going to tentatively mark this as Easy Pickings: it should be simple enough. Replying to Nicolas Noé: Hi Nicolas, Are you still working on this ticket? Sorry, I forgot about it. I'll try to solve this real soon (or release the ticket if I can't find time for it). ​PR Can I work on this ticket ? Sure, sorry for blocking the ticket while I was too busy... I think that Nicolas Noe's solution, ​PR, was correct. The model field can accept a callable as it is currently implemented. If you pass it a callable for the path argument it will correctly use that fully qualified function import path in the migration. The problem is when you go to actually instantiate a FilePathField instance, the FilePathField form does some type checking and gives you one of these TypeError: scandir: path should be string, bytes, os.PathLike or None, not function This can be avoided by evaluating the path function first thing in the field form __init__ function, as in the pull request. Then everything seems to work fine. Hi, If I only change self.path in forms/fields.py, right after __init__ I get this error: File "/home/hpfn/Documentos/Programacao/python/testes/.venv/lib/python3.6/site-packages/django/forms/fields.py", line 1106, in __init__ self.choices.append((f, f.replace(path, "", 1))) TypeError: replace() argument 1 must be str, not function The 'path' param is used a few lines after. There is one more time. Line 1106 can be wrong. If I put in models/fields/__init__.py - after super(): if callable(self.path): self.path = self.path() I can run 'python manage.py runserver' It can be: if callable(path): path = path() at the beginning of forms/fields.py ​PR All comments in the original PR (​https://github.com/django/django/pull/10299/commits/7ddb83ca7ed5b2a586e9d4c9e0a79d60b27c26b6) seems to be resolved in the latter one (​https://github.com/django/django/pull/10924/commits/9c3b2c85e46efcf1c916e4b76045d834f16050e3). Any hope of this featuring coming through. Django keep bouncing between migrations due to different paths to models.FilePathField
2019-02-03T11:30:12Z
3.0
["test_callable_path (model_fields.test_filepathfield.FilePathFieldTests)"]
["test_path (model_fields.test_filepathfield.FilePathFieldTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django/django
django__django-11019
93e892bb645b16ebaf287beb5fe7f3ffe8d10408
diff --git a/django/forms/widgets.py b/django/forms/widgets.py --- a/django/forms/widgets.py +++ b/django/forms/widgets.py @@ -6,16 +6,21 @@ import datetime import re 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 django.utils.datastructures import OrderedSet from django.utils.dates import MONTHS from django.utils.formats import get_format from django.utils.html import format_html, html_safe from django.utils.safestring import mark_safe +from django.utils.topological_sort import ( + CyclicDependencyError, stable_topological_sort, +) from django.utils.translation import gettext_lazy as _ from .renderers import get_default_renderer @@ -59,22 +64,15 @@ def __str__(self): @property def _css(self): - css = self._css_lists[0] - # filter(None, ...) avoids calling merge with empty dicts. - for obj in filter(None, self._css_lists[1:]): - css = { - medium: self.merge(css.get(medium, []), obj.get(medium, [])) - for medium in css.keys() | obj.keys() - } - return css + css = defaultdict(list) + for css_list in self._css_lists: + for medium, sublist in css_list.items(): + css[medium].append(sublist) + return {medium: self.merge(*lists) for medium, lists in css.items()} @property def _js(self): - js = self._js_lists[0] - # filter(None, ...) avoids calling merge() with empty lists. - for obj in filter(None, self._js_lists[1:]): - js = self.merge(js, obj) - return js + return self.merge(*self._js_lists) def render(self): return mark_safe('\n'.join(chain.from_iterable(getattr(self, 'render_' + name)() for name in MEDIA_TYPES))) @@ -115,39 +113,37 @@ def __getitem__(self, name): raise KeyError('Unknown media type "%s"' % name) @staticmethod - def merge(list_1, list_2): + def merge(*lists): """ - Merge two lists while trying to keep the relative order of the elements. - Warn if the lists have the same two elements in a different relative - order. + Merge lists while trying to keep the relative order of the elements. + Warn if the lists have the same elements in a different relative order. For static assets it can be important to have them included in the DOM in a certain order. In JavaScript you may not be able to reference a global or in CSS you might want to override a style. """ - # Start with a copy of list_1. - combined_list = list(list_1) - last_insert_index = len(list_1) - # Walk list_2 in reverse, inserting each element into combined_list if - # it doesn't already exist. - for path in reversed(list_2): - try: - # Does path already exist in the list? - index = combined_list.index(path) - except ValueError: - # Add path to combined_list since it doesn't exist. - combined_list.insert(last_insert_index, path) - else: - if index > last_insert_index: - warnings.warn( - 'Detected duplicate Media files in an opposite order:\n' - '%s\n%s' % (combined_list[last_insert_index], combined_list[index]), - MediaOrderConflictWarning, - ) - # path already exists in the list. Update last_insert_index so - # that the following elements are inserted in front of this one. - last_insert_index = index - return combined_list + dependency_graph = defaultdict(set) + all_items = OrderedSet() + for list_ in filter(None, lists): + head = list_[0] + # The first items depend on nothing but have to be part of the + # dependency graph to be included in the result. + dependency_graph.setdefault(head, set()) + for item in list_: + all_items.add(item) + # No self dependencies + if head != item: + dependency_graph[item].add(head) + head = item + try: + return stable_topological_sort(all_items, dependency_graph) + except CyclicDependencyError: + warnings.warn( + 'Detected duplicate Media files in an opposite order: {}'.format( + ', '.join(repr(l) for l in lists) + ), MediaOrderConflictWarning, + ) + return list(all_items) def __add__(self, other): combined = Media()
diff --git a/tests/admin_inlines/tests.py b/tests/admin_inlines/tests.py --- a/tests/admin_inlines/tests.py +++ b/tests/admin_inlines/tests.py @@ -497,10 +497,10 @@ def test_inline_media_only_inline(self): response.context['inline_admin_formsets'][0].media._js, [ 'admin/js/vendor/jquery/jquery.min.js', - 'admin/js/jquery.init.js', - 'admin/js/inlines.min.js', 'my_awesome_inline_scripts.js', 'custom_number.js', + 'admin/js/jquery.init.js', + 'admin/js/inlines.min.js', ] ) self.assertContains(response, 'my_awesome_inline_scripts.js') diff --git a/tests/admin_widgets/test_autocomplete_widget.py b/tests/admin_widgets/test_autocomplete_widget.py --- a/tests/admin_widgets/test_autocomplete_widget.py +++ b/tests/admin_widgets/test_autocomplete_widget.py @@ -139,4 +139,4 @@ def test_media(self): else: expected_files = base_files with translation.override(lang): - self.assertEqual(AutocompleteSelect(rel, admin.site).media._js, expected_files) + self.assertEqual(AutocompleteSelect(rel, admin.site).media._js, list(expected_files)) diff --git a/tests/forms_tests/tests/test_media.py b/tests/forms_tests/tests/test_media.py --- a/tests/forms_tests/tests/test_media.py +++ b/tests/forms_tests/tests/test_media.py @@ -25,8 +25,8 @@ def test_construction(self): ) self.assertEqual( repr(m), - "Media(css={'all': ('path/to/css1', '/path/to/css2')}, " - "js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'))" + "Media(css={'all': ['path/to/css1', '/path/to/css2']}, " + "js=['/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'])" ) class Foo: @@ -125,8 +125,8 @@ class Media: <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/path/to/js4"></script>""" +<script type="text/javascript" src="/path/to/js4"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) # media addition hasn't affected the original objects @@ -151,6 +151,17 @@ class Media: self.assertEqual(str(w4.media), """<link href="/path/to/css1" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script>""") + def test_media_deduplication(self): + # A deduplication test applied directly to a Media object, to confirm + # that the deduplication doesn't only happen at the point of merging + # two or more media objects. + media = Media( + css={'all': ('/path/to/css1', '/path/to/css1')}, + js=('/path/to/js1', '/path/to/js1'), + ) + self.assertEqual(str(media), """<link href="/path/to/css1" type="text/css" media="all" rel="stylesheet"> +<script type="text/javascript" src="/path/to/js1"></script>""") + def test_media_property(self): ############################################################### # Property-based media definitions @@ -197,12 +208,12 @@ def _media(self): self.assertEqual( str(w6.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> -<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <link href="/other/path" type="text/css" media="all" rel="stylesheet"> +<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="/other/js"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/other/js"></script>""" +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) def test_media_inheritance(self): @@ -247,8 +258,8 @@ class Media: <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/path/to/js4"></script>""" +<script type="text/javascript" src="/path/to/js4"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) def test_media_inheritance_from_property(self): @@ -322,8 +333,8 @@ class Media: <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/path/to/js4"></script>""" +<script type="text/javascript" src="/path/to/js4"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) def test_media_inheritance_single_type(self): @@ -420,8 +431,8 @@ def __init__(self, attrs=None): <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/path/to/js4"></script>""" +<script type="text/javascript" src="/path/to/js4"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) def test_form_media(self): @@ -462,8 +473,8 @@ class MyForm(Form): <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/path/to/js4"></script>""" +<script type="text/javascript" src="/path/to/js4"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) # Form media can be combined to produce a single media definition. @@ -477,8 +488,8 @@ class AnotherForm(Form): <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> -<script type="text/javascript" src="/path/to/js4"></script>""" +<script type="text/javascript" src="/path/to/js4"></script> +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) # Forms can also define media, following the same rules as widgets. @@ -495,28 +506,28 @@ class Media: self.assertEqual( str(f3.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> +<link href="/some/form/css" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> -<link href="/some/form/css" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="/some/form/javascript"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script> -<script type="text/javascript" src="/some/form/javascript"></script>""" +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" ) # Media works in templates self.assertEqual( Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})), """<script type="text/javascript" src="/path/to/js1"></script> +<script type="text/javascript" src="/some/form/javascript"></script> <script type="text/javascript" src="http://media.other.com/path/to/js2"></script> -<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script> <script type="text/javascript" src="/path/to/js4"></script> -<script type="text/javascript" src="/some/form/javascript"></script>""" +<script type="text/javascript" src="https://secure.other.com/path/to/js3"></script>""" """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet"> +<link href="/some/form/css" type="text/css" media="all" rel="stylesheet"> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet"> -<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet"> -<link href="/some/form/css" type="text/css" media="all" rel="stylesheet">""" +<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">""" ) def test_html_safe(self): @@ -526,19 +537,23 @@ def test_html_safe(self): def test_merge(self): test_values = ( - (([1, 2], [3, 4]), [1, 2, 3, 4]), + (([1, 2], [3, 4]), [1, 3, 2, 4]), (([1, 2], [2, 3]), [1, 2, 3]), (([2, 3], [1, 2]), [1, 2, 3]), (([1, 3], [2, 3]), [1, 2, 3]), (([1, 2], [1, 3]), [1, 2, 3]), (([1, 2], [3, 2]), [1, 3, 2]), + (([1, 2], [1, 2]), [1, 2]), + ([[1, 2], [1, 3], [2, 3], [5, 7], [5, 6], [6, 7, 9], [8, 9]], [1, 5, 8, 2, 6, 3, 7, 9]), + ((), []), + (([1, 2],), [1, 2]), ) - for (list1, list2), expected in test_values: - with self.subTest(list1=list1, list2=list2): - self.assertEqual(Media.merge(list1, list2), expected) + for lists, expected in test_values: + with self.subTest(lists=lists): + self.assertEqual(Media.merge(*lists), expected) def test_merge_warning(self): - msg = 'Detected duplicate Media files in an opposite order:\n1\n2' + msg = 'Detected duplicate Media files in an opposite order: [1, 2], [2, 1]' with self.assertWarnsMessage(RuntimeWarning, msg): self.assertEqual(Media.merge([1, 2], [2, 1]), [1, 2]) @@ -546,28 +561,30 @@ def test_merge_js_three_way(self): """ The relative order of scripts is preserved in a three-way merge. """ - # custom_widget.js doesn't depend on jquery.js. - widget1 = Media(js=['custom_widget.js']) - widget2 = Media(js=['jquery.js', 'uses_jquery.js']) - form_media = widget1 + widget2 - # The relative ordering of custom_widget.js and jquery.js has been - # established (but without a real need to). - self.assertEqual(form_media._js, ['custom_widget.js', 'jquery.js', 'uses_jquery.js']) - # The inline also uses custom_widget.js. This time, it's at the end. - inline_media = Media(js=['jquery.js', 'also_jquery.js']) + Media(js=['custom_widget.js']) - merged = form_media + inline_media - self.assertEqual(merged._js, ['custom_widget.js', 'jquery.js', 'uses_jquery.js', 'also_jquery.js']) + widget1 = Media(js=['color-picker.js']) + widget2 = Media(js=['text-editor.js']) + widget3 = Media(js=['text-editor.js', 'text-editor-extras.js', 'color-picker.js']) + merged = widget1 + widget2 + widget3 + self.assertEqual(merged._js, ['text-editor.js', 'text-editor-extras.js', 'color-picker.js']) + + def test_merge_js_three_way2(self): + # The merge prefers to place 'c' before 'b' and 'g' before 'h' to + # preserve the original order. The preference 'c'->'b' is overridden by + # widget3's media, but 'g'->'h' survives in the final ordering. + widget1 = Media(js=['a', 'c', 'f', 'g', 'k']) + widget2 = Media(js=['a', 'b', 'f', 'h', 'k']) + widget3 = Media(js=['b', 'c', 'f', 'k']) + merged = widget1 + widget2 + widget3 + self.assertEqual(merged._js, ['a', 'b', 'c', 'f', 'g', 'h', 'k']) def test_merge_css_three_way(self): - widget1 = Media(css={'screen': ['a.css']}) - widget2 = Media(css={'screen': ['b.css']}) - widget3 = Media(css={'all': ['c.css']}) - form1 = widget1 + widget2 - form2 = widget2 + widget1 - # form1 and form2 have a.css and b.css in different order... - self.assertEqual(form1._css, {'screen': ['a.css', 'b.css']}) - self.assertEqual(form2._css, {'screen': ['b.css', 'a.css']}) - # ...but merging succeeds as the relative ordering of a.css and b.css - # was never specified. - merged = widget3 + form1 + form2 - self.assertEqual(merged._css, {'screen': ['a.css', 'b.css'], 'all': ['c.css']}) + widget1 = Media(css={'screen': ['c.css'], 'all': ['d.css', 'e.css']}) + widget2 = Media(css={'screen': ['a.css']}) + widget3 = Media(css={'screen': ['a.css', 'b.css', 'c.css'], 'all': ['e.css']}) + merged = widget1 + widget2 + # c.css comes before a.css because widget1 + widget2 establishes this + # order. + self.assertEqual(merged._css, {'screen': ['c.css', 'a.css'], 'all': ['d.css', 'e.css']}) + merged = merged + widget3 + # widget3 contains an explicit ordering of c.css and a.css. + self.assertEqual(merged._css, {'screen': ['a.css', 'b.css', 'c.css'], 'all': ['d.css', 'e.css']})
Merging 3 or more media objects can throw unnecessary MediaOrderConflictWarnings Description Consider the following form definition, where text-editor-extras.js depends on text-editor.js but all other JS files are independent: from django import forms class ColorPicker(forms.Widget): class Media: js = ['color-picker.js'] class SimpleTextWidget(forms.Widget): class Media: js = ['text-editor.js'] class FancyTextWidget(forms.Widget): class Media: js = ['text-editor.js', 'text-editor-extras.js', 'color-picker.js'] class MyForm(forms.Form): background_color = forms.CharField(widget=ColorPicker()) intro = forms.CharField(widget=SimpleTextWidget()) body = forms.CharField(widget=FancyTextWidget()) Django should be able to resolve the JS files for the final form into the order text-editor.js, text-editor-extras.js, color-picker.js. However, accessing MyForm().media results in: /projects/django/django/forms/widgets.py:145: MediaOrderConflictWarning: Detected duplicate Media files in an opposite order: text-editor-extras.js text-editor.js MediaOrderConflictWarning, Media(css={}, js=['text-editor-extras.js', 'color-picker.js', 'text-editor.js']) The MediaOrderConflictWarning is a result of the order that the additions happen in: ColorPicker().media + SimpleTextWidget().media produces Media(css={}, js=['color-picker.js', 'text-editor.js']), which (wrongly) imposes the constraint that color-picker.js must appear before text-editor.js. The final result is particularly unintuitive here, as it's worse than the "naïve" result produced by Django 1.11 before order-checking was added (color-picker.js, text-editor.js, text-editor-extras.js), and the pair of files reported in the warning message seems wrong too (aren't color-picker.js and text-editor.js the wrong-ordered ones?)
As a tentative fix, I propose that media objects should explicitly distinguish between cases where we do / don't care about ordering, notionally something like: class FancyTextWidget(forms.Widget): class Media: js = { ('text-editor.js', 'text-editor-extras.js'), # tuple = order is important 'color-picker.js' # set = order is unimportant } (although using a set for this is problematic due to the need for contents to be hashable), and the result of adding two media objects should be a "don't care" so that we aren't introducing dependencies where the original objects didn't have them. We would then defer assembling them into a flat list until the final render call. I haven't worked out the rest of the algorithm yet, but I'm willing to dig further if this sounds like a sensible plan of attack... Are you testing with the fix from #30153? Yes, testing against current master (b39bd0aa6d5667d6bbcf7d349a1035c676e3f972). So ​https://github.com/django/django/commit/959d0c078a1c903cd1e4850932be77c4f0d2294d (the fix for #30153) didn't make this case worse, it just didn't improve on it. The problem is actually the same I encountered, with the same unintuitive error message too. There is still a way to produce a conflicting order but it's harder to trigger in the administration interface now but unfortunately still easy. Also, going back to the state of things pre 2.0 was already discussed previously and rejected. Here's a failing test and and an idea to make this particular test pass: Merge the JS sublists starting from the longest list and continuing with shorter lists. The CSS case is missing yet. The right thing to do would be (against ​worse is better) to add some sort of dependency resolution solver with backtracking but that's surely a bad idea for many other reasons. The change makes some old tests fail (I only took a closer look at test_merge_js_three_way and in this case the failure is fine -- custom_widget.js is allowed to appear before jquery.js.) diff --git a/django/forms/widgets.py b/django/forms/widgets.py index 02aa32b207..d85c409152 100644 --- a/django/forms/widgets.py +++ b/django/forms/widgets.py @@ -70,9 +70,15 @@ class Media: @property def _js(self): - js = self._js_lists[0] + sorted_by_length = list(sorted( + filter(None, self._js_lists), + key=lambda lst: -len(lst), + )) + if not sorted_by_length: + return [] + js = sorted_by_length[0] # filter(None, ...) avoids calling merge() with empty lists. - for obj in filter(None, self._js_lists[1:]): + for obj in filter(None, sorted_by_length[1:]): js = self.merge(js, obj) return js diff --git a/tests/forms_tests/tests/test_media.py b/tests/forms_tests/tests/test_media.py index 8cb484a15e..9d17ad403b 100644 --- a/tests/forms_tests/tests/test_media.py +++ b/tests/forms_tests/tests/test_media.py @@ -571,3 +571,12 @@ class FormsMediaTestCase(SimpleTestCase): # was never specified. merged = widget3 + form1 + form2 self.assertEqual(merged._css, {'screen': ['a.css', 'b.css'], 'all': ['c.css']}) + + def test_merge_js_some_more(self): + widget1 = Media(js=['color-picker.js']) + widget2 = Media(js=['text-editor.js']) + widget3 = Media(js=['text-editor.js', 'text-editor-extras.js', 'color-picker.js']) + + merged = widget1 + widget2 + widget3 + + self.assertEqual(merged._js, ['text-editor.js', 'text-editor-extras.js', 'color-picker.js']) Thinking some more: sorted() is more likely to break existing code because people probably haven't listed all dependencies in their js attributes now. Yes, that's not what they should have done, but breaking peoples' projects sucks and I don't really want to do that (even if introducing sorted() might be the least disruptive and at the same time most correct change) wanting to handle the jquery, widget1, noConflict and jquery, widget2, noConflict case has introduced an unexpected amount of complexity introducing a complex solving framework will have a really bad impact on runtime and will introduce even more complexity and is out of the question to me I'm happy to help fixing this but right now I only see bad and worse choices. I don't think sorting by length is the way to go - it would be trivial to make the test fail again by extending the first list with unrelated items. It might be a good real-world heuristic for finding a solution more often, but that's just trading a reproducible bug for an unpredictable one. (I'm not sure I'd trust it as a heuristic either: we've encountered this issue on Wagtail CMS, where we're making extensive use of form media on hierarchical form structures, and so those media definitions will tend to bubble up several layers to reach the top level. At that point, there's no way of knowing whether the longer list is the one with more complex dependencies, or just one that collected more unrelated files on the way up the tree...) I'll do some more thinking on this. My hunch is that even if it does end up being a travelling-salesman-type problem, it's unlikely to be run on a large enough data set for performance to be an issue. I don't think sorting by length is the way to go - it would be trivial to make the test fail again by extending the first list with unrelated items. It might be a good real-world heuristic for finding a solution more often, but that's just trading a reproducible bug for an unpredictable one. Well yes, if the ColorPicker itself would have a longer list of JS files it depends on then it would fail too. If, on the other hand, it wasn't a ColorPicker widget but a ColorPicker formset or form the initially declared lists would still be preserved and sorting the lists by length would give the correct result. Since #30153 the initially declared lists (or tuples) are preserved so maybe you have many JS and CSS declarations but as long as they are unrelated there will not be many long sublists. I'm obviously happy though if you're willing to spend the time finding a robust solution to this problem. (For the record: Personally I was happy with the state of things pre-2.0 too... and For the record 2: I'm also using custom widgets and inlines in feincms3/django-content-editor. It's really surprising to me that we didn't stumble on this earlier since we're always working on the latest Django version or even on pre-release versions if at all possible) Hi there, I'm the dude who implemented the warning. I am not so sure this is a bug. Let's try tackle this step by step. The new merging algorithm that was introduced in version 2 is an improvement. It is the most accurate way to merge two sorted lists. It's not the simplest way, but has been reviewed plenty times. The warning is another story. It is independent from the algorithm. It merely tells you that the a certain order could not be maintained. We figured back than, that this would be a good idea. It warns a developer about a potential issue, but does not raise an exception. With that in mind, the correct way to deal with the issue described right now, is to ignore the warning. BUT, that doesn't mean that you don't have a valid point. There are implicit and explicit orders. Not all assets require ordering and (random) orders that only exist because of Media merging don't matter at all. This brings me back to a point that I have [previously made](https://code.djangoproject.com/ticket/30153#comment:6). It would make sense to store the original lists, which is now the case on master, and only raise if the order violates the original list. The current implementation on master could also be improved by removing duplicates. Anyways, I would considers those changes improvements, but not bug fixes. I didn't have time yet to look into this. But I do have some time this weekend. If you want I can take another look into this and propose a solution that solves this issue. Best -Joe "Ignore the warning" doesn't work here - the order-fixing has broken the dependency between text-editor.js and text-editor-extras.js. I can (reluctantly) accept an implementation that produces false warnings, and I can accept that a genuine dependency loop might produce undefined behaviour, but the combination of the two - breaking the ordering as a result of seeing a loop that isn't there - is definitely a bug. (To be clear, I'm not suggesting that the 2.x implementation is a step backwards from not doing order checking at all - but it does introduce a new failure case, and that's what I'm keen to fix.) To summarise: Even with the new strategy in #30153 of holding on to the un-merged lists as long as possible, the final merging is still done by adding one list at a time. The intermediate results are lists, which are assumed to be order-critical; this means the intermediate results have additional constraints that are not present in the original lists, causing it to see conflicts where there aren't any. Additionally, we should try to preserve the original sequence of files as much as possible, to avoid unnecessarily breaking user code that hasn't fully specified its dependencies and is relying on the 1.x behaviour. I think we need to approach this as a graph problem (which I realise might sound like overkill, but I'd rather start with something formally correct and optimise later as necessary): a conflict occurs whenever the dependency graph is cyclic. #30153 is a useful step towards this, as it ensures we have the accurate dependency graph up until the point where we need to assemble the final list. I suggest we replace Media.merge with a new method that accepts any number of lists (using *args if we want to preserve the existing method signature for backwards compatibility). This would work as follows: Iterate over all items in all sub-lists, building a dependency graph (where a dependency is any item that immediately precedes it within a sub-list) and a de-duplicated list containing all items indexed in the order they are first encountered Starting from the first item in the de-duplicated list, backtrack through the dependency graph, following the lowest-indexed dependency each time until we reach an item with no dependencies. While backtracking, maintain a stack of visited items. If we encounter an item already on the stack, this is a dependency loop; throw a MediaOrderConflictWarning and break out of the backtracking loop Output the resulting item, then remove it from the dependency graph and the de-duplicated list If the 'visited items' stack is non-empty, pop the last item off it and repeat the backtracking step from there. Otherwise, repeat the backtracking step starting from the next item in the de-duplicated list Repeat until no items remain This sounds correct. I'm not sure it's right though. It does sound awfully complex for what there is to gain. Maintaining this down the road will not get easier. Finding, explaining and understanding the fix for #30153 did already cost a lot of time which could also have been invested elsewhere. If I manually assign widget3's JS lists (see https://code.djangoproject.com/ticket/30179#comment:5) then everything just works and the final result is correct: # widget3 = Media(js=['text-editor.js', 'text-editor-extras.js', 'color-picker.js']) widget3 = Media() widget3._js_lists = [['text-editor.js', 'text-editor-extras.js'], ['color-picker.js']] So what you proposed first (https://code.djangoproject.com/ticket/30179#comment:1) might just work fine and would be good enough (tm). Something like ​https://github.com/django/django/blob/543fc97407a932613d283c1e0bb47616cf8782e3/django/forms/widgets.py#L52 # Instead of self._js_lists = [js]: self._js_lists = list(js) if isinstance(js, set) else [js] @Matthias: I think that solution will work, but only if: 1) we're going to insist that users always use this notation wherever a "non-dependency" exists - i.e. it is considered user error for the user to forget to put color-picker.js in its own sub-list 2) we have a very tight definition of what a dependency is - e.g. color-picker.js can't legally be a dependency of text-editor.js / text-editor-extras.js, because it exists on its own in ColorPicker's media - which also invalidates the [jquery, widget1, noconflict] + [jquery, widget2, noconflict] case (does noconflict depend on widget1 or not?) I suspect you only have to go slightly before the complexity of [jquery, widget1, noconflict] + [jquery, widget2, noconflict] before you start running into counter-examples again. PR: ​https://github.com/django/django/pull/11010 I encountered another subtle bug along the way (which I suspect has existed since 1.x): #12879 calls for us to strip duplicates from the input lists, but in the current implementation the only de-duplication happens during Media.merge, so this never happens in the case of a single list. I've now extended the tests to cover this: ​https://github.com/django/django/pull/11010/files#diff-7fc04ae9019782c1884a0e97e96eda1eR154 . As a minor side effect of this extra de-duplication step, tuples get converted to lists more often, so I've had to fix up some existing tests accordingly - hopefully that's acceptable fall-out :-) Matt, great work. I believe it is best to merge all lists at once and not sequentially as I did. Based on your work, I would suggest to simply use the algorithms implemented in Python. Therefore the whole merge function can be replaced with a simple one liner: import heapq from collections import OrderedDict def merge(*sublists): return list(OrderedDict.fromkeys(heapq.merge(*sublists))) # >>> merge([3],[1],[1,2],[2,3]) # [1, 2, 3] It actually behaves different. I will continue to review your pull-request. As stated there, it would be helpful if there is some kind of resource to understand what strategy you implemented. For now I will try to review it without it.
2019-02-23T15:51:14Z
3.0
["test_combine_media (forms_tests.tests.test_media.FormsMediaTestCase)", "test_construction (forms_tests.tests.test_media.FormsMediaTestCase)", "test_form_media (forms_tests.tests.test_media.FormsMediaTestCase)", "test_media_deduplication (forms_tests.tests.test_media.FormsMediaTestCase)", "test_media_inheritance (forms_tests.tests.test_media.FormsMediaTestCase)", "test_media_inheritance_extends (forms_tests.tests.test_media.FormsMediaTestCase)", "test_media_property_parent_references (forms_tests.tests.test_media.FormsMediaTestCase)", "test_merge (forms_tests.tests.test_media.FormsMediaTestCase)", "test_merge_css_three_way (forms_tests.tests.test_media.FormsMediaTestCase)", "test_merge_js_three_way (forms_tests.tests.test_media.FormsMediaTestCase)", "test_merge_js_three_way2 (forms_tests.tests.test_media.FormsMediaTestCase)", "test_merge_warning (forms_tests.tests.test_media.FormsMediaTestCase)", "test_multi_widget (forms_tests.tests.test_media.FormsMediaTestCase)", "test_media (admin_widgets.test_autocomplete_widget.AutocompleteMixinTests)", "test_render_options (admin_widgets.test_autocomplete_widget.AutocompleteMixinTests)", "test_inline_media_only_inline (admin_inlines.tests.TestInlineMedia)"]
["Regression for #9362", "test_html_safe (forms_tests.tests.test_media.FormsMediaTestCase)", "test_media_dsl (forms_tests.tests.test_media.FormsMediaTestCase)", "test_media_inheritance_from_property (forms_tests.tests.test_media.FormsMediaTestCase)", "test_media_inheritance_single_type (forms_tests.tests.test_media.FormsMediaTestCase)", "test_media_property (forms_tests.tests.test_media.FormsMediaTestCase)", "test_multi_media (forms_tests.tests.test_media.FormsMediaTestCase)", "test_build_attrs (admin_widgets.test_autocomplete_widget.AutocompleteMixinTests)", "test_build_attrs_no_custom_class (admin_widgets.test_autocomplete_widget.AutocompleteMixinTests)", "test_build_attrs_not_required_field (admin_widgets.test_autocomplete_widget.AutocompleteMixinTests)", "test_build_attrs_required_field (admin_widgets.test_autocomplete_widget.AutocompleteMixinTests)", "test_get_url (admin_widgets.test_autocomplete_widget.AutocompleteMixinTests)", "Empty option isn't present if the field isn't required.", "Empty option is present if the field isn't required.", "test_deleting_inline_with_protected_delete_does_not_validate (admin_inlines.tests.TestInlineProtectedOnDelete)", "test_all_inline_media (admin_inlines.tests.TestInlineMedia)", "test_inline_media_only_base (admin_inlines.tests.TestInlineMedia)", "test_inline_add_fk_add_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_add_fk_noperm (admin_inlines.tests.TestInlinePermissions)", "test_inline_add_m2m_add_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_add_m2m_noperm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_fk_add_change_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_fk_add_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_fk_all_perms (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_fk_change_del_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_fk_change_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_fk_noperm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_m2m_add_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_m2m_change_perm (admin_inlines.tests.TestInlinePermissions)", "test_inline_change_m2m_noperm (admin_inlines.tests.TestInlinePermissions)", "Admin inline should invoke local callable when its name is listed in readonly_fields", "test_can_delete (admin_inlines.tests.TestInline)", "test_create_inlines_on_inherited_model (admin_inlines.tests.TestInline)", "test_custom_form_tabular_inline_label (admin_inlines.tests.TestInline)", "test_custom_form_tabular_inline_overridden_label (admin_inlines.tests.TestInline)", "test_custom_get_extra_form (admin_inlines.tests.TestInline)", "test_custom_min_num (admin_inlines.tests.TestInline)", "test_custom_pk_shortcut (admin_inlines.tests.TestInline)", "test_help_text (admin_inlines.tests.TestInline)", "test_inline_editable_pk (admin_inlines.tests.TestInline)", "#18263 -- Make sure hidden fields don't get a column in tabular inlines", "test_inline_nonauto_noneditable_inherited_pk (admin_inlines.tests.TestInline)", "test_inline_nonauto_noneditable_pk (admin_inlines.tests.TestInline)", "test_inline_primary (admin_inlines.tests.TestInline)", "Inlines `show_change_link` for registered models when enabled.", "Inlines `show_change_link` disabled for unregistered models.", "test_localize_pk_shortcut (admin_inlines.tests.TestInline)", "Autogenerated many-to-many inlines are displayed correctly (#13407)", "test_min_num (admin_inlines.tests.TestInline)", "Admin inline `readonly_field` shouldn't invoke parent ModelAdmin callable", "test_non_related_name_inline (admin_inlines.tests.TestInline)", "Inlines without change permission shows field inputs on add form.", "Bug #13174.", "test_stacked_inline_edit_form_contains_has_original_class (admin_inlines.tests.TestInline)", "test_tabular_inline_column_css_class (admin_inlines.tests.TestInline)", "Inlines `show_change_link` disabled by default.", "test_tabular_model_form_meta_readonly_field (admin_inlines.tests.TestInline)", "test_tabular_non_field_errors (admin_inlines.tests.TestInline)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django/django
django__django-11283
08a4ee06510ae45562c228eefbdcaac84bd38c7a
diff --git a/django/contrib/auth/migrations/0011_update_proxy_permissions.py b/django/contrib/auth/migrations/0011_update_proxy_permissions.py --- a/django/contrib/auth/migrations/0011_update_proxy_permissions.py +++ b/django/contrib/auth/migrations/0011_update_proxy_permissions.py @@ -1,5 +1,18 @@ -from django.db import migrations +import sys + +from django.core.management.color import color_style +from django.db import migrations, transaction from django.db.models import Q +from django.db.utils import IntegrityError + +WARNING = """ + A problem arose migrating proxy model permissions for {old} to {new}. + + Permission(s) for {new} already existed. + Codenames Q: {query} + + Ensure to audit ALL permissions for {old} and {new}. +""" def update_proxy_model_permissions(apps, schema_editor, reverse=False): @@ -7,6 +20,7 @@ def update_proxy_model_permissions(apps, schema_editor, reverse=False): Update the content_type of proxy model permissions to use the ContentType of the proxy model. """ + style = color_style() Permission = apps.get_model('auth', 'Permission') ContentType = apps.get_model('contenttypes', 'ContentType') for Model in apps.get_models(): @@ -24,10 +38,16 @@ def update_proxy_model_permissions(apps, schema_editor, reverse=False): proxy_content_type = ContentType.objects.get_for_model(Model, for_concrete_model=False) old_content_type = proxy_content_type if reverse else concrete_content_type new_content_type = concrete_content_type if reverse else proxy_content_type - Permission.objects.filter( - permissions_query, - content_type=old_content_type, - ).update(content_type=new_content_type) + try: + with transaction.atomic(): + Permission.objects.filter( + permissions_query, + content_type=old_content_type, + ).update(content_type=new_content_type) + except IntegrityError: + old = '{}_{}'.format(old_content_type.app_label, old_content_type.model) + new = '{}_{}'.format(new_content_type.app_label, new_content_type.model) + sys.stdout.write(style.WARNING(WARNING.format(old=old, new=new, query=permissions_query))) def revert_proxy_model_permissions(apps, schema_editor):
diff --git a/tests/auth_tests/test_migrations.py b/tests/auth_tests/test_migrations.py --- a/tests/auth_tests/test_migrations.py +++ b/tests/auth_tests/test_migrations.py @@ -4,6 +4,7 @@ from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.test import TestCase +from django.test.utils import captured_stdout from .models import Proxy, UserProxy @@ -152,3 +153,27 @@ def test_user_keeps_same_permissions_after_migrating_backward(self): user = User._default_manager.get(pk=user.pk) for permission in [self.default_permission, self.custom_permission]: self.assertTrue(user.has_perm('auth_tests.' + permission.codename)) + + def test_migrate_with_existing_target_permission(self): + """ + Permissions may already exist: + + - Old workaround was to manually create permissions for proxy models. + - Model may have been concrete and then converted to proxy. + + Output a reminder to audit relevant permissions. + """ + proxy_model_content_type = ContentType.objects.get_for_model(Proxy, for_concrete_model=False) + Permission.objects.create( + content_type=proxy_model_content_type, + codename='add_proxy', + name='Can add proxy', + ) + Permission.objects.create( + content_type=proxy_model_content_type, + codename='display_proxys', + name='May display proxys information', + ) + with captured_stdout() as stdout: + update_proxy_permissions.update_proxy_model_permissions(apps, None) + self.assertIn('A problem arose migrating proxy model permissions', stdout.getvalue())
Migration auth.0011_update_proxy_permissions fails for models recreated as a proxy. Description (last modified by Mariusz Felisiak) I am trying to update my project to Django 2.2. When I launch python manage.py migrate, I get this error message when migration auth.0011_update_proxy_permissions is applying (full stacktrace is available ​here): django.db.utils.IntegrityError: duplicate key value violates unique constraint "idx_18141_auth_permission_content_type_id_01ab375a_uniq" DETAIL: Key (co.ntent_type_id, codename)=(12, add_agency) already exists. It looks like the migration is trying to re-create already existing entries in the auth_permission table. At first I though it cloud because we recently renamed a model. But after digging and deleting the entries associated with the renamed model from our database in the auth_permission table, the problem still occurs with other proxy models. I tried to update directly from 2.0.13 and 2.1.8. The issues appeared each time. I also deleted my venv and recreated it without an effect. I searched for a ticket about this on the bug tracker but found nothing. I also posted this on ​django-users and was asked to report this here.
Please provide a sample project or enough details to reproduce the issue. Same problem for me. If a Permission exists already with the new content_type and permission name, IntegrityError is raised since it violates the unique_key constraint on permission model i.e. content_type_id_code_name To get into the situation where you already have permissions with the content type you should be able to do the following: Start on Django <2.2 Create a model called 'TestModel' Migrate Delete the model called 'TestModel' Add a new proxy model called 'TestModel' Migrate Update to Django >=2.2 Migrate We think this is what happened in our case where we found this issue (​https://sentry.thalia.nu/share/issue/68be0f8c32764dec97855b3cbb3d8b55/). We have a proxy model with the same name that a previous non-proxy model once had. This changed during a refactor and the permissions + content type for the original model still exist. Our solution will probably be removing the existing permissions from the table, but that's really only a workaround. Reproduced with steps from comment. It's probably regression in 181fb60159e54d442d3610f4afba6f066a6dac05. What happens when creating a regular model, deleting it and creating a new proxy model: Create model 'RegularThenProxyModel' +----------------------------------+---------------------------+-----------------------+ | name | codename | model | +----------------------------------+---------------------------+-----------------------+ | Can add regular then proxy model | add_regularthenproxymodel | regularthenproxymodel | +----------------------------------+---------------------------+-----------------------+ Migrate Delete the model called 'RegularThenProxyModel' Add a new proxy model called 'RegularThenProxyModel' +----------------------------------+---------------------------+-----------------------+ | name | codename | model | +----------------------------------+---------------------------+-----------------------+ | Can add concrete model | add_concretemodel | concretemodel | | Can add regular then proxy model | add_regularthenproxymodel | concretemodel | | Can add regular then proxy model | add_regularthenproxymodel | regularthenproxymodel | +----------------------------------+---------------------------+-----------------------+ What happens when creating a proxy model right away: Create a proxy model 'RegularThenProxyModel' +----------------------------------+---------------------------+---------------+ | name | codename | model | +----------------------------------+---------------------------+---------------+ | Can add concrete model | add_concretemodel | concretemodel | | Can add regular then proxy model | add_regularthenproxymodel | concretemodel | +----------------------------------+---------------------------+---------------+ As you can see, the problem here is that permissions are not cleaned up, so we are left with an existing | Can add regular then proxy model | add_regularthenproxymodel | regularthenproxymodel | row. When the 2.2 migration is applied, it tries to create that exact same row, hence the IntegrityError. Unfortunately, there is no remove_stale_permission management command like the one for ContentType. So I think we can do one of the following: Show a nice error message to let the user delete the conflicting migration OR Re-use the existing permission I think 1. is much safer as it will force users to use a new permission and assign it accordingly to users/groups. Edit: I revised my initial comment after reproducing the error in my environment. It's also possible to get this kind of integrity error on the auth.0011 migration if another app is migrated first causing the auth post_migrations hook to run. The auth post migrations hook runs django.contrib.auth.management.create_permissions, which writes the new form of the auth_permission records to the table. Then when the auth.0011 migration runs it tries to update things to the values that were just written. To reproduce this behavior: pip install Django==2.1.7 Create an app, let's call it app, with two models, TestModel(models.Model) and ProxyModel(TestModel) the second one with proxy=True python manage.py makemigrations python manage.py migrate pip install Django==2.2 Add another model to app python manage.py makemigrations migrate the app only, python manage.py migrate app. This does not run the auth migrations, but does run the auth post_migrations hook Note that new records have been added to auth_permission python manage.py migrate, this causes an integrity error when the auth.0011 migration tries to update records that are the same as the ones already added in step 8. This has the same exception as this bug report, I don't know if it's considered a different bug, or the same one. Yes it is the same issue. My recommendation to let the users figure it out with a helpful message still stands even if it may sound a bit painful, because: It prevents data loss (we don't do an automatic delete/create of permissions) It prevents security oversights (we don't re-use an existing permission) It shouldn't happen for most use cases Again, I would love to hear some feedback or other alternatives. I won’t have time to work on this for the next 2 weeks so I’m de-assigning myself. I’ll pick it up again if nobody does and I’m available to discuss feedback/suggestions. I'll make a patch for this. I'll see about raising a suitable warning from the migration but we already warn in the release notes for this to audit permissions: my initial thought was that re-using the permission would be OK. (I see Arthur's comment. Other thoughts?) Being my first contribution I wanted to be super (super) careful with security concerns, but given the existing warning in the release notes for auditing prior to update, I agree that re-using the permission feels pretty safe and would remove overhead for people running into this scenario. Thanks for taking this on Carlton, I'd be happy to review.
2019-04-26T07:02:50Z
3.0
["test_migrate_with_existing_target_permission (auth_tests.test_migrations.ProxyModelWithSameAppLabelTests)"]
["test_migrate_backwards (auth_tests.test_migrations.ProxyModelWithDifferentAppLabelTests)", "test_proxy_model_permissions_contenttype (auth_tests.test_migrations.ProxyModelWithDifferentAppLabelTests)", "test_user_has_now_proxy_model_permissions (auth_tests.test_migrations.ProxyModelWithDifferentAppLabelTests)", "test_user_keeps_same_permissions_after_migrating_backward (auth_tests.test_migrations.ProxyModelWithDifferentAppLabelTests)", "test_migrate_backwards (auth_tests.test_migrations.ProxyModelWithSameAppLabelTests)", "test_proxy_model_permissions_contenttype (auth_tests.test_migrations.ProxyModelWithSameAppLabelTests)", "test_user_keeps_same_permissions_after_migrating_backward (auth_tests.test_migrations.ProxyModelWithSameAppLabelTests)", "test_user_still_has_proxy_model_permissions (auth_tests.test_migrations.ProxyModelWithSameAppLabelTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django/django
django__django-11564
580e644f24f1c5ae5b94784fb73a9953a178fd26
diff --git a/django/conf/__init__.py b/django/conf/__init__.py --- a/django/conf/__init__.py +++ b/django/conf/__init__.py @@ -15,7 +15,8 @@ import django from django.conf import global_settings -from django.core.exceptions import ImproperlyConfigured +from django.core.exceptions import ImproperlyConfigured, ValidationError +from django.core.validators import URLValidator from django.utils.deprecation import RemovedInDjango40Warning from django.utils.functional import LazyObject, empty @@ -109,6 +110,26 @@ def configure(self, default_settings=global_settings, **options): setattr(holder, name, value) self._wrapped = holder + @staticmethod + def _add_script_prefix(value): + """ + Add SCRIPT_NAME prefix to relative paths. + + Useful when the app is being served at a subpath and manually prefixing + subpath to STATIC_URL and MEDIA_URL in settings is inconvenient. + """ + # Don't apply prefix to valid URLs. + try: + URLValidator()(value) + return value + except (ValidationError, AttributeError): + pass + # Don't apply prefix to absolute paths. + if value.startswith('/'): + return value + from django.urls import get_script_prefix + return '%s%s' % (get_script_prefix(), value) + @property def configured(self): """Return True if the settings have already been configured.""" @@ -128,6 +149,14 @@ def PASSWORD_RESET_TIMEOUT_DAYS(self): ) return self.__getattr__('PASSWORD_RESET_TIMEOUT_DAYS') + @property + def STATIC_URL(self): + return self._add_script_prefix(self.__getattr__('STATIC_URL')) + + @property + def MEDIA_URL(self): + return self._add_script_prefix(self.__getattr__('MEDIA_URL')) + class Settings: def __init__(self, settings_module):
diff --git a/tests/file_storage/tests.py b/tests/file_storage/tests.py --- a/tests/file_storage/tests.py +++ b/tests/file_storage/tests.py @@ -521,7 +521,7 @@ def test_setting_changed(self): defaults_storage = self.storage_class() settings = { 'MEDIA_ROOT': 'overridden_media_root', - 'MEDIA_URL': 'overridden_media_url/', + 'MEDIA_URL': '/overridden_media_url/', 'FILE_UPLOAD_PERMISSIONS': 0o333, 'FILE_UPLOAD_DIRECTORY_PERMISSIONS': 0o333, } diff --git a/tests/settings_tests/tests.py b/tests/settings_tests/tests.py --- a/tests/settings_tests/tests.py +++ b/tests/settings_tests/tests.py @@ -12,6 +12,7 @@ override_settings, signals, ) from django.test.utils import requires_tz_support +from django.urls import clear_script_prefix, set_script_prefix @modify_settings(ITEMS={ @@ -567,3 +568,51 @@ def decorated_function(): signals.setting_changed.disconnect(self.receiver) # This call shouldn't raise any errors. decorated_function() + + +class MediaURLStaticURLPrefixTest(SimpleTestCase): + def set_script_name(self, val): + clear_script_prefix() + if val is not None: + set_script_prefix(val) + + def test_not_prefixed(self): + # Don't add SCRIPT_NAME prefix to valid URLs, absolute paths or None. + tests = ( + '/path/', + 'http://myhost.com/path/', + None, + ) + for setting in ('MEDIA_URL', 'STATIC_URL'): + for path in tests: + new_settings = {setting: path} + with self.settings(**new_settings): + for script_name in ['/somesubpath', '/somesubpath/', '/', '', None]: + with self.subTest(script_name=script_name, **new_settings): + try: + self.set_script_name(script_name) + self.assertEqual(getattr(settings, setting), path) + finally: + clear_script_prefix() + + def test_add_script_name_prefix(self): + tests = ( + # Relative paths. + ('/somesubpath', 'path/', '/somesubpath/path/'), + ('/somesubpath/', 'path/', '/somesubpath/path/'), + ('/', 'path/', '/path/'), + # Invalid URLs. + ('/somesubpath/', 'htp://myhost.com/path/', '/somesubpath/htp://myhost.com/path/'), + # Blank settings. + ('/somesubpath/', '', '/somesubpath/'), + ) + for setting in ('MEDIA_URL', 'STATIC_URL'): + for script_name, path, expected_path in tests: + new_settings = {setting: path} + with self.settings(**new_settings): + with self.subTest(script_name=script_name, **new_settings): + try: + self.set_script_name(script_name) + self.assertEqual(getattr(settings, setting), expected_path) + finally: + clear_script_prefix()
Add support for SCRIPT_NAME in STATIC_URL and MEDIA_URL Description (last modified by Rostyslav Bryzgunov) By default, {% static '...' %} tag just appends STATIC_URL in the path. When running on sub-path, using SCRIPT_NAME WSGI param, it results in incorrect static URL - it doesn't prepend SCRIPT_NAME prefix. This problem can be solved with prepending SCRIPT_NAME to STATIC_URL in settings.py but that doesn't work when SCRIPT_NAME is a dynamic value. This can be easily added into default Django static tag and django.contrib.staticfiles tag as following: def render(self, context): url = self.url(context) # Updating url here with request.META['SCRIPT_NAME'] if self.varname is None: return url context[self.varname] = url return '' On more research I found that FileSystemStorage and StaticFilesStorage ignores SCRIPT_NAME as well. We might have to do a lot of changes but I think it's worth the efforts.
This change doesn't seem correct to me (for one, it seems like it could break existing sites). Why not include the appropriate prefix in your STATIC_URL and MEDIA_URL settings? This is not a patch. This is just an idea I got about the patch for {% static %} only. The patch will (probably) involve FileSystemStorage and StaticFileSystemStorage classes. The main idea behind this feature was that Django will auto detect script_name header and use that accordingly for creating static and media urls. This will reduce human efforts for setting up sites in future. This patch will also take time to develop so it can be added in Django2.0 timeline. What I meant was that I don't think Django should automatically use SCRIPT_NAME in generating those URLs. If you're running your site on a subpath, then you should set your STATIC_URL to '​http://example.com/subpath/static/' or whatever. However, you might not even be hosting static and uploaded files on the same domain as your site (in fact, for user-uploaded files, you shouldn't do that ​for security reasons) in which case SCRIPT_URL is irrelevant in constructing the static/media URLs. How would the change make it easier to setup sites? I think that the idea basically makes sense. Ideally, a Django instance shouldn't need to know at which subpath it is being deployed, as this can be considered as purely sysadmin stuff. It would be a good separation of concerns. For example, the Web administrator may change the WSGIScriptAlias from /foo to /bar and the application should continue working. Of course, this only applies when *_URL settings are not full URIs. In practice, it's very likely that many running instances are adapting their *_URL settings to include the base script path, hence the behavior change would be backwards incompatible. The question is whether the change is worth the incompatibility. I see. I guess the idea would be to use get_script_prefix() like reverse() does as I don't think we have access to request everywhere we need it. It seems like some public APIs like get_static_url() and get_media_url() would replace accessing the settings directly whenever building URLs. For backwards compatibility, possibly these functions could try to detect if the setting is already prefixed appropriately. Removing the prefix from the settings, however, means that the URLs are no longer correct when generated outside of a request/response cycle though (#16734). I'm not sure if it might create any practical problems, but we might think about addressing that issue first. I'm here at DjangoCon US 2016 will try to create a patch for this ticket ;) Why? But before I make the patch, here are some reasons to do it. The first reason is consistency inside Django core: {% url '...' %} template tag does respect SCRIPT_NAME but {% static '...' %} does not reverse(...) function does respect SCRIPT_NAME but static(...) does not And the second reason is that there is no way to make it work in case when SCRIPT_NAME is a dynamic value - see an example below. Of course we shouldn't modify STATIC_URL when it's an absolute URL, with domain & protocol. But if it starts with / - it's relative to our Django project and we need to add SCRIPT_NAME prefix. Real life example You have Django running via WSGI behind reverse proxy (let's call it back-end server), and another HTTP server on the front (let's call it front-end server). Front-end server URL is http://some.domain.com/sub/path/, back-end server URL is http://1.2.3.4:5678/. You want them both to work. You pass SCRIPT_NAME = '/sub/path/' from front-end server to back-end one. But when you access back-end server directly - there is no SCRIPT_NAME passed to WSGI/Django. So we cannot hard-code SCRIPT_NAME in Django settings because it's dynamic. Pull-request created: ​https://github.com/django/django/pull/7000 At least documentation and additional tests look like they are required. Absolutely agree with your remarks, Tim. I'll add tests. Could you point to docs that need to be updated? I would like to take this ticket on and have a new PR for it: ​https://github.com/django/django/pull/10724
2019-07-12T21:06:28Z
3.1
["test_add_script_name_prefix (settings_tests.tests.MediaURLStaticURLPrefixTest)", "test_not_prefixed (settings_tests.tests.MediaURLStaticURLPrefixTest)"]
["test_max_recursion_error (settings_tests.tests.ClassDecoratedTestCaseSuper)", "test_override_settings_inheritance (settings_tests.tests.ChildDecoratedTestCase)", "test_method_override (settings_tests.tests.FullyDecoratedTestCase)", "test_override (settings_tests.tests.FullyDecoratedTestCase)", "test_max_recursion_error (settings_tests.tests.ClassDecoratedTestCase)", "test_method_override (settings_tests.tests.ClassDecoratedTestCase)", "test_override (settings_tests.tests.ClassDecoratedTestCase)", "Settings are overridden within setUpClass (#21281).", "Regression test for #9610.", "test_first_character_dot (file_storage.tests.FileStoragePathParsing)", "test_get_filesystem_storage (file_storage.tests.GetStorageClassTests)", "test_get_invalid_storage_module (file_storage.tests.GetStorageClassTests)", "test_get_nonexistent_storage_class (file_storage.tests.GetStorageClassTests)", "test_get_nonexistent_storage_module (file_storage.tests.GetStorageClassTests)", "Receiver fails on both enter and exit.", "Receiver fails on enter only.", "Receiver fails on exit only.", "test_override_settings_reusable_on_enter (settings_tests.tests.OverrideSettingsIsolationOnExceptionTests)", "test_configure (settings_tests.tests.IsOverriddenTest)", "test_evaluated_lazysettings_repr (settings_tests.tests.IsOverriddenTest)", "test_module (settings_tests.tests.IsOverriddenTest)", "test_override (settings_tests.tests.IsOverriddenTest)", "test_settings_repr (settings_tests.tests.IsOverriddenTest)", "test_unevaluated_lazysettings_repr (settings_tests.tests.IsOverriddenTest)", "test_usersettingsholder_repr (settings_tests.tests.IsOverriddenTest)", "test_content_saving (file_storage.tests.ContentFileStorageTestCase)", "test_none (settings_tests.tests.SecureProxySslHeaderTest)", "test_set_with_xheader_right (settings_tests.tests.SecureProxySslHeaderTest)", "test_set_with_xheader_wrong (settings_tests.tests.SecureProxySslHeaderTest)", "test_set_without_xheader (settings_tests.tests.SecureProxySslHeaderTest)", "test_xheader_preferred_to_underlying_request (settings_tests.tests.SecureProxySslHeaderTest)", "Regression test for #19031", "test_already_configured (settings_tests.tests.SettingsTests)", "test_class_decorator (settings_tests.tests.SettingsTests)", "test_context_manager (settings_tests.tests.SettingsTests)", "test_decorator (settings_tests.tests.SettingsTests)", "test_incorrect_timezone (settings_tests.tests.SettingsTests)", "test_no_secret_key (settings_tests.tests.SettingsTests)", "test_no_settings_module (settings_tests.tests.SettingsTests)", "test_nonupper_settings_ignored_in_default_settings (settings_tests.tests.SettingsTests)", "test_nonupper_settings_prohibited_in_configure (settings_tests.tests.SettingsTests)", "test_override (settings_tests.tests.SettingsTests)", "test_override_change (settings_tests.tests.SettingsTests)", "test_override_doesnt_leak (settings_tests.tests.SettingsTests)", "test_override_settings_delete (settings_tests.tests.SettingsTests)", "test_override_settings_nested (settings_tests.tests.SettingsTests)", "test_settings_delete (settings_tests.tests.SettingsTests)", "test_settings_delete_wrapped (settings_tests.tests.SettingsTests)", "test_signal_callback_context_manager (settings_tests.tests.SettingsTests)", "test_signal_callback_decorator (settings_tests.tests.SettingsTests)", "test_tuple_settings (settings_tests.tests.TestListSettings)", "test_deconstruction (file_storage.tests.FileSystemStorageTests)", "test_lazy_base_url_init (file_storage.tests.FileSystemStorageTests)", "test_file_upload_default_permissions (file_storage.tests.FileStoragePermissions)", "test_file_upload_directory_default_permissions (file_storage.tests.FileStoragePermissions)", "test_file_upload_directory_permissions (file_storage.tests.FileStoragePermissions)", "test_file_upload_permissions (file_storage.tests.FileStoragePermissions)", "test_decorated_testcase_module (settings_tests.tests.FullyDecoratedTranTestCase)", "test_decorated_testcase_name (settings_tests.tests.FullyDecoratedTranTestCase)", "test_method_list_override (settings_tests.tests.FullyDecoratedTranTestCase)", "test_method_list_override_nested_order (settings_tests.tests.FullyDecoratedTranTestCase)", "test_method_list_override_no_ops (settings_tests.tests.FullyDecoratedTranTestCase)", "test_method_list_override_strings (settings_tests.tests.FullyDecoratedTranTestCase)", "test_method_override (settings_tests.tests.FullyDecoratedTranTestCase)", "test_override (settings_tests.tests.FullyDecoratedTranTestCase)", "test_custom_valid_name_callable_upload_to (file_storage.tests.FileFieldStorageTests)", "test_duplicate_filename (file_storage.tests.FileFieldStorageTests)", "test_empty_upload_to (file_storage.tests.FileFieldStorageTests)", "test_extended_length_storage (file_storage.tests.FileFieldStorageTests)", "test_file_object (file_storage.tests.FileFieldStorageTests)", "test_file_truncation (file_storage.tests.FileFieldStorageTests)", "test_filefield_default (file_storage.tests.FileFieldStorageTests)", "test_filefield_pickling (file_storage.tests.FileFieldStorageTests)", "test_filefield_read (file_storage.tests.FileFieldStorageTests)", "test_filefield_reopen (file_storage.tests.FileFieldStorageTests)", "test_filefield_write (file_storage.tests.FileFieldStorageTests)", "test_files (file_storage.tests.FileFieldStorageTests)", "test_pathlib_upload_to (file_storage.tests.FileFieldStorageTests)", "test_random_upload_to (file_storage.tests.FileFieldStorageTests)", "test_stringio (file_storage.tests.FileFieldStorageTests)", "test_base_url (file_storage.tests.OverwritingStorageTests)", "test_delete_deletes_directories (file_storage.tests.OverwritingStorageTests)", "test_delete_no_name (file_storage.tests.OverwritingStorageTests)", "test_empty_location (file_storage.tests.OverwritingStorageTests)", "test_file_access_options (file_storage.tests.OverwritingStorageTests)", "test_file_chunks_error (file_storage.tests.OverwritingStorageTests)", "test_file_get_accessed_time (file_storage.tests.OverwritingStorageTests)", "test_file_get_accessed_time_timezone (file_storage.tests.OverwritingStorageTests)", "test_file_get_created_time (file_storage.tests.OverwritingStorageTests)", "test_file_get_created_time_timezone (file_storage.tests.OverwritingStorageTests)", "test_file_get_modified_time (file_storage.tests.OverwritingStorageTests)", "test_file_get_modified_time_timezone (file_storage.tests.OverwritingStorageTests)", "test_file_path (file_storage.tests.OverwritingStorageTests)", "test_file_save_with_path (file_storage.tests.OverwritingStorageTests)", "test_file_save_without_name (file_storage.tests.OverwritingStorageTests)", "The storage backend should preserve case of filenames.", "test_file_storage_prevents_directory_traversal (file_storage.tests.OverwritingStorageTests)", "test_file_url (file_storage.tests.OverwritingStorageTests)", "test_listdir (file_storage.tests.OverwritingStorageTests)", "test_makedirs_race_handling (file_storage.tests.OverwritingStorageTests)", "test_remove_race_handling (file_storage.tests.OverwritingStorageTests)", "test_save_doesnt_close (file_storage.tests.OverwritingStorageTests)", "Saving to same file name twice overwrites the first file.", "test_setting_changed (file_storage.tests.OverwritingStorageTests)", "test_base_url (file_storage.tests.DiscardingFalseContentStorageTests)", "test_custom_storage_discarding_empty_content (file_storage.tests.DiscardingFalseContentStorageTests)", "test_delete_deletes_directories (file_storage.tests.DiscardingFalseContentStorageTests)", "test_delete_no_name (file_storage.tests.DiscardingFalseContentStorageTests)", "test_empty_location (file_storage.tests.DiscardingFalseContentStorageTests)", "test_file_access_options (file_storage.tests.DiscardingFalseContentStorageTests)", "test_file_chunks_error (file_storage.tests.DiscardingFalseContentStorageTests)", "test_file_get_accessed_time (file_storage.tests.DiscardingFalseContentStorageTests)", "test_file_get_accessed_time_timezone (file_storage.tests.DiscardingFalseContentStorageTests)", "test_file_get_created_time (file_storage.tests.DiscardingFalseContentStorageTests)", "test_file_get_created_time_timezone (file_storage.tests.DiscardingFalseContentStorageTests)", "test_file_get_modified_time (file_storage.tests.DiscardingFalseContentStorageTests)", "test_file_get_modified_time_timezone (file_storage.tests.DiscardingFalseContentStorageTests)", "test_file_path (file_storage.tests.DiscardingFalseContentStorageTests)", "test_file_save_with_path (file_storage.tests.DiscardingFalseContentStorageTests)", "test_file_save_without_name (file_storage.tests.DiscardingFalseContentStorageTests)", "test_file_storage_prevents_directory_traversal (file_storage.tests.DiscardingFalseContentStorageTests)", "test_file_url (file_storage.tests.DiscardingFalseContentStorageTests)", "test_listdir (file_storage.tests.DiscardingFalseContentStorageTests)", "test_makedirs_race_handling (file_storage.tests.DiscardingFalseContentStorageTests)", "test_remove_race_handling (file_storage.tests.DiscardingFalseContentStorageTests)", "test_save_doesnt_close (file_storage.tests.DiscardingFalseContentStorageTests)", "test_setting_changed (file_storage.tests.DiscardingFalseContentStorageTests)", "test_base_url (file_storage.tests.CustomStorageTests)", "test_custom_get_available_name (file_storage.tests.CustomStorageTests)", "test_delete_deletes_directories (file_storage.tests.CustomStorageTests)", "test_delete_no_name (file_storage.tests.CustomStorageTests)", "test_empty_location (file_storage.tests.CustomStorageTests)", "test_file_access_options (file_storage.tests.CustomStorageTests)", "test_file_chunks_error (file_storage.tests.CustomStorageTests)", "test_file_get_accessed_time (file_storage.tests.CustomStorageTests)", "test_file_get_accessed_time_timezone (file_storage.tests.CustomStorageTests)", "test_file_get_created_time (file_storage.tests.CustomStorageTests)", "test_file_get_created_time_timezone (file_storage.tests.CustomStorageTests)", "test_file_get_modified_time (file_storage.tests.CustomStorageTests)", "test_file_get_modified_time_timezone (file_storage.tests.CustomStorageTests)", "test_file_path (file_storage.tests.CustomStorageTests)", "test_file_save_with_path (file_storage.tests.CustomStorageTests)", "test_file_save_without_name (file_storage.tests.CustomStorageTests)", "test_file_storage_prevents_directory_traversal (file_storage.tests.CustomStorageTests)", "test_file_url (file_storage.tests.CustomStorageTests)", "test_listdir (file_storage.tests.CustomStorageTests)", "test_makedirs_race_handling (file_storage.tests.CustomStorageTests)", "test_remove_race_handling (file_storage.tests.CustomStorageTests)", "test_save_doesnt_close (file_storage.tests.CustomStorageTests)", "test_setting_changed (file_storage.tests.CustomStorageTests)", "test_base_url (file_storage.tests.FileStorageTests)", "test_delete_deletes_directories (file_storage.tests.FileStorageTests)", "test_delete_no_name (file_storage.tests.FileStorageTests)", "test_empty_location (file_storage.tests.FileStorageTests)", "test_file_access_options (file_storage.tests.FileStorageTests)", "test_file_chunks_error (file_storage.tests.FileStorageTests)", "test_file_get_accessed_time (file_storage.tests.FileStorageTests)", "test_file_get_accessed_time_timezone (file_storage.tests.FileStorageTests)", "test_file_get_created_time (file_storage.tests.FileStorageTests)", "test_file_get_created_time_timezone (file_storage.tests.FileStorageTests)", "test_file_get_modified_time (file_storage.tests.FileStorageTests)", "test_file_get_modified_time_timezone (file_storage.tests.FileStorageTests)", "test_file_path (file_storage.tests.FileStorageTests)", "test_file_save_with_path (file_storage.tests.FileStorageTests)", "test_file_save_without_name (file_storage.tests.FileStorageTests)", "test_file_storage_prevents_directory_traversal (file_storage.tests.FileStorageTests)", "test_file_url (file_storage.tests.FileStorageTests)", "test_listdir (file_storage.tests.FileStorageTests)", "test_makedirs_race_handling (file_storage.tests.FileStorageTests)", "test_remove_race_handling (file_storage.tests.FileStorageTests)", "test_save_doesnt_close (file_storage.tests.FileStorageTests)", "test_setting_changed (file_storage.tests.FileStorageTests)", "test_urllib_request_urlopen (file_storage.tests.FileLikeObjectTestCase)", "test_race_condition (file_storage.tests.FileSaveRaceConditionTest)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-11630
65e86948b80262574058a94ccaae3a9b59c3faea
diff --git a/django/core/checks/model_checks.py b/django/core/checks/model_checks.py --- a/django/core/checks/model_checks.py +++ b/django/core/checks/model_checks.py @@ -4,7 +4,8 @@ from itertools import chain from django.apps import apps -from django.core.checks import Error, Tags, register +from django.conf import settings +from django.core.checks import Error, Tags, Warning, register @register(Tags.models) @@ -35,14 +36,25 @@ def check_all_models(app_configs=None, **kwargs): indexes[model_index.name].append(model._meta.label) for model_constraint in model._meta.constraints: constraints[model_constraint.name].append(model._meta.label) + if settings.DATABASE_ROUTERS: + error_class, error_id = Warning, 'models.W035' + error_hint = ( + 'You have configured settings.DATABASE_ROUTERS. Verify that %s ' + 'are correctly routed to separate databases.' + ) + else: + error_class, error_id = Error, 'models.E028' + error_hint = None for db_table, model_labels in db_table_models.items(): if len(model_labels) != 1: + model_labels_str = ', '.join(model_labels) errors.append( - Error( + error_class( "db_table '%s' is used by multiple models: %s." - % (db_table, ', '.join(db_table_models[db_table])), + % (db_table, model_labels_str), obj=db_table, - id='models.E028', + hint=(error_hint % model_labels_str) if error_hint else None, + id=error_id, ) ) for index_name, model_labels in indexes.items():
diff --git a/tests/check_framework/test_model_checks.py b/tests/check_framework/test_model_checks.py --- a/tests/check_framework/test_model_checks.py +++ b/tests/check_framework/test_model_checks.py @@ -1,12 +1,16 @@ from django.core import checks -from django.core.checks import Error +from django.core.checks import Error, Warning from django.db import models from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import ( - isolate_apps, modify_settings, override_system_checks, + isolate_apps, modify_settings, override_settings, override_system_checks, ) +class EmptyRouter: + pass + + @isolate_apps('check_framework', attr_name='apps') @override_system_checks([checks.model_checks.check_all_models]) class DuplicateDBTableTests(SimpleTestCase): @@ -28,6 +32,30 @@ class Meta: ) ]) + @override_settings(DATABASE_ROUTERS=['check_framework.test_model_checks.EmptyRouter']) + def test_collision_in_same_app_database_routers_installed(self): + class Model1(models.Model): + class Meta: + db_table = 'test_table' + + class Model2(models.Model): + class Meta: + db_table = 'test_table' + + self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ + Warning( + "db_table 'test_table' is used by multiple models: " + "check_framework.Model1, check_framework.Model2.", + hint=( + 'You have configured settings.DATABASE_ROUTERS. Verify ' + 'that check_framework.Model1, check_framework.Model2 are ' + 'correctly routed to separate databases.' + ), + obj='test_table', + id='models.W035', + ) + ]) + @modify_settings(INSTALLED_APPS={'append': 'basic'}) @isolate_apps('basic', 'check_framework', kwarg_name='apps') def test_collision_across_apps(self, apps): @@ -50,6 +78,34 @@ class Meta: ) ]) + @modify_settings(INSTALLED_APPS={'append': 'basic'}) + @override_settings(DATABASE_ROUTERS=['check_framework.test_model_checks.EmptyRouter']) + @isolate_apps('basic', 'check_framework', kwarg_name='apps') + def test_collision_across_apps_database_routers_installed(self, apps): + class Model1(models.Model): + class Meta: + app_label = 'basic' + db_table = 'test_table' + + class Model2(models.Model): + class Meta: + app_label = 'check_framework' + db_table = 'test_table' + + self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [ + Warning( + "db_table 'test_table' is used by multiple models: " + "basic.Model1, check_framework.Model2.", + hint=( + 'You have configured settings.DATABASE_ROUTERS. Verify ' + 'that basic.Model1, check_framework.Model2 are correctly ' + 'routed to separate databases.' + ), + obj='test_table', + id='models.W035', + ) + ]) + def test_no_collision_for_unmanaged_models(self): class Unmanaged(models.Model): class Meta:
Django throws error when different apps with different models have the same name table name. Description Error message: table_name: (models.E028) db_table 'table_name' is used by multiple models: base.ModelName, app2.ModelName. We have a Base app that points to a central database and that has its own tables. We then have multiple Apps that talk to their own databases. Some share the same table names. We have used this setup for a while, but after upgrading to Django 2.2 we're getting an error saying we're not allowed 2 apps, with 2 different models to have the same table names. Is this correct behavior? We've had to roll back to Django 2.0 for now.
Regression in [5d25804eaf81795c7d457e5a2a9f0b9b0989136c], ticket #20098. My opinion is that as soon as the project has a non-empty DATABASE_ROUTERS setting, the error should be turned into a warning, as it becomes difficult to say for sure that it's an error. And then the project can add the warning in SILENCED_SYSTEM_CHECKS. I agree with your opinion. Assigning to myself, patch on its way Replying to Claude Paroz: Regression in [5d25804eaf81795c7d457e5a2a9f0b9b0989136c], ticket #20098. My opinion is that as soon as the project has a non-empty DATABASE_ROUTERS setting, the error should be turned into a warning, as it becomes difficult to say for sure that it's an error. And then the project can add the warning in SILENCED_SYSTEM_CHECKS.
2019-08-05T11:22:41Z
3.0
["test_collision_across_apps_database_routers_installed (check_framework.test_model_checks.DuplicateDBTableTests)", "test_collision_in_same_app_database_routers_installed (check_framework.test_model_checks.DuplicateDBTableTests)"]
["test_collision_abstract_model (check_framework.test_model_checks.IndexNameTests)", "test_collision_across_apps (check_framework.test_model_checks.IndexNameTests)", "test_collision_in_different_models (check_framework.test_model_checks.IndexNameTests)", "test_collision_in_same_model (check_framework.test_model_checks.IndexNameTests)", "test_no_collision_abstract_model_interpolation (check_framework.test_model_checks.IndexNameTests)", "test_no_collision_across_apps_interpolation (check_framework.test_model_checks.IndexNameTests)", "test_collision_abstract_model (check_framework.test_model_checks.ConstraintNameTests)", "test_collision_across_apps (check_framework.test_model_checks.ConstraintNameTests)", "test_collision_in_different_models (check_framework.test_model_checks.ConstraintNameTests)", "test_collision_in_same_model (check_framework.test_model_checks.ConstraintNameTests)", "test_no_collision_abstract_model_interpolation (check_framework.test_model_checks.ConstraintNameTests)", "test_no_collision_across_apps_interpolation (check_framework.test_model_checks.ConstraintNameTests)", "test_collision_across_apps (check_framework.test_model_checks.DuplicateDBTableTests)", "test_collision_in_same_app (check_framework.test_model_checks.DuplicateDBTableTests)", "test_no_collision_for_proxy_models (check_framework.test_model_checks.DuplicateDBTableTests)", "test_no_collision_for_unmanaged_models (check_framework.test_model_checks.DuplicateDBTableTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django/django
django__django-11742
fee75d2aed4e58ada6567c464cfd22e89dc65f4a
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 @@ -257,6 +257,7 @@ def is_value(value, accept_promise=True): ) ] + choice_max_length = 0 # Expect [group_name, [value, display]] for choices_group in self.choices: try: @@ -270,16 +271,32 @@ def is_value(value, accept_promise=True): for value, human_name in group_choices ): break + if self.max_length is not None and group_choices: + choice_max_length = max( + choice_max_length, + *(len(value) for value, _ in group_choices if isinstance(value, str)), + ) except (TypeError, ValueError): # No groups, choices in the form [value, display] value, human_name = group_name, group_choices if not is_value(value) or not is_value(human_name): break + if self.max_length is not None and isinstance(value, str): + choice_max_length = max(choice_max_length, len(value)) # Special case: choices=['ab'] if isinstance(choices_group, str): break else: + if self.max_length is not None and choice_max_length > self.max_length: + return [ + checks.Error( + "'max_length' is too small to fit the longest value " + "in 'choices' (%d characters)." % choice_max_length, + obj=self, + id='fields.E009', + ), + ] return [] return [
diff --git a/tests/invalid_models_tests/test_ordinary_fields.py b/tests/invalid_models_tests/test_ordinary_fields.py --- a/tests/invalid_models_tests/test_ordinary_fields.py +++ b/tests/invalid_models_tests/test_ordinary_fields.py @@ -304,6 +304,32 @@ class Model(models.Model): self.assertEqual(Model._meta.get_field('field').check(), []) + def test_choices_in_max_length(self): + class Model(models.Model): + field = models.CharField( + max_length=2, choices=[ + ('ABC', 'Value Too Long!'), ('OK', 'Good') + ], + ) + group = models.CharField( + max_length=2, choices=[ + ('Nested', [('OK', 'Good'), ('Longer', 'Longer')]), + ('Grouped', [('Bad', 'Bad')]), + ], + ) + + for name, choice_max_length in (('field', 3), ('group', 6)): + with self.subTest(name): + field = Model._meta.get_field(name) + self.assertEqual(field.check(), [ + Error( + "'max_length' is too small to fit the longest value " + "in 'choices' (%d characters)." % choice_max_length, + obj=field, + id='fields.E009', + ), + ]) + def test_bad_db_index_value(self): class Model(models.Model): field = models.CharField(max_length=10, db_index='bad')
Add check to ensure max_length fits longest choice. Description There is currently no check to ensure that Field.max_length is large enough to fit the longest value in Field.choices. This would be very helpful as often this mistake is not noticed until an attempt is made to save a record with those values that are too long.
2019-09-04T08:30:14Z
3.0
["test_choices_in_max_length (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group (invalid_models_tests.test_ordinary_fields.CharFieldTests)"]
["test_non_nullable_blank (invalid_models_tests.test_ordinary_fields.GenericIPAddressFieldTests)", "test_forbidden_files_and_folders (invalid_models_tests.test_ordinary_fields.FilePathFieldTests)", "test_max_length_warning (invalid_models_tests.test_ordinary_fields.IntegerFieldTests)", "test_primary_key (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_upload_to_callable_not_checked (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_upload_to_starts_with_slash (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_valid_case (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_valid_default_case (invalid_models_tests.test_ordinary_fields.FileFieldTests)", "test_str_default_value (invalid_models_tests.test_ordinary_fields.BinaryFieldTests)", "test_valid_default_value (invalid_models_tests.test_ordinary_fields.BinaryFieldTests)", "test_max_length_warning (invalid_models_tests.test_ordinary_fields.AutoFieldTests)", "test_primary_key (invalid_models_tests.test_ordinary_fields.AutoFieldTests)", "test_valid_case (invalid_models_tests.test_ordinary_fields.AutoFieldTests)", "test_fix_default_value (invalid_models_tests.test_ordinary_fields.DateTimeFieldTests)", "test_fix_default_value_tz (invalid_models_tests.test_ordinary_fields.DateTimeFieldTests)", "test_auto_now_and_auto_now_add_raise_error (invalid_models_tests.test_ordinary_fields.DateFieldTests)", "test_fix_default_value (invalid_models_tests.test_ordinary_fields.DateFieldTests)", "test_fix_default_value_tz (invalid_models_tests.test_ordinary_fields.DateFieldTests)", "test_fix_default_value (invalid_models_tests.test_ordinary_fields.TimeFieldTests)", "test_fix_default_value_tz (invalid_models_tests.test_ordinary_fields.TimeFieldTests)", "test_bad_values_of_max_digits_and_decimal_places (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_decimal_places_greater_than_max_digits (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_negative_max_digits_and_decimal_places (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_required_attributes (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_valid_field (invalid_models_tests.test_ordinary_fields.DecimalFieldTests)", "test_bad_db_index_value (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_bad_max_length_value (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_bad_validators (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_containing_lazy (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_containing_non_pairs (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group_bad_structure (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group_lazy (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_choices_named_group_non_pairs (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_iterable_of_iterable_choices (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_lazy_choices (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_missing_max_length (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_negative_max_length (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_non_iterable_choices (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "Two letters isn't a valid choice pair.", "test_str_max_length_type (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_str_max_length_value (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_valid_field (invalid_models_tests.test_ordinary_fields.CharFieldTests)", "test_pillow_installed (invalid_models_tests.test_ordinary_fields.ImageFieldTests)"]
419a78300f7cd27611196e1e464d50fd0385ff27
django/django
django__django-11797
3346b78a8a872286a245d1e77ef4718fc5e6be1a
diff --git a/django/db/models/lookups.py b/django/db/models/lookups.py --- a/django/db/models/lookups.py +++ b/django/db/models/lookups.py @@ -262,9 +262,9 @@ def process_rhs(self, compiler, connection): from django.db.models.sql.query import Query if isinstance(self.rhs, Query): if self.rhs.has_limit_one(): - # The subquery must select only the pk. - self.rhs.clear_select_clause() - self.rhs.add_fields(['pk']) + if not self.rhs.has_select_fields: + self.rhs.clear_select_clause() + self.rhs.add_fields(['pk']) else: raise ValueError( 'The QuerySet value for an exact lookup must be limited to '
diff --git a/tests/lookup/tests.py b/tests/lookup/tests.py --- a/tests/lookup/tests.py +++ b/tests/lookup/tests.py @@ -5,6 +5,7 @@ from django.core.exceptions import FieldError from django.db import connection +from django.db.models import Max from django.db.models.expressions import Exists, OuterRef from django.db.models.functions import Substr from django.test import TestCase, skipUnlessDBFeature @@ -956,3 +957,15 @@ def test_nested_outerref_lhs(self): ), ) self.assertEqual(qs.get(has_author_alias_match=True), tag) + + def test_exact_query_rhs_with_selected_columns(self): + newest_author = Author.objects.create(name='Author 2') + authors_max_ids = Author.objects.filter( + name='Author 2', + ).values( + 'name', + ).annotate( + max_id=Max('id'), + ).values('max_id') + authors = Author.objects.filter(id=authors_max_ids[:1]) + self.assertEqual(authors.get(), newest_author)
Filtering on query result overrides GROUP BY of internal query Description from django.contrib.auth import models a = models.User.objects.filter(email__isnull=True).values('email').annotate(m=Max('id')).values('m') print(a.query) # good # SELECT MAX("auth_user"."id") AS "m" FROM "auth_user" WHERE "auth_user"."email" IS NULL GROUP BY "auth_user"."email" print(a[:1].query) # good # SELECT MAX("auth_user"."id") AS "m" FROM "auth_user" WHERE "auth_user"."email" IS NULL GROUP BY "auth_user"."email" LIMIT 1 b = models.User.objects.filter(id=a[:1]) print(b.query) # GROUP BY U0."id" should be GROUP BY U0."email" # SELECT ... FROM "auth_user" WHERE "auth_user"."id" = (SELECT U0."id" FROM "auth_user" U0 WHERE U0."email" IS NULL GROUP BY U0."id" LIMIT 1)
Workaround: from django.contrib.auth import models a = models.User.objects.filter(email__isnull=True).values('email').aggregate(Max('id'))['id_max'] b = models.User.objects.filter(id=a) Thanks for tackling that one James! If I can provide you some guidance I'd suggest you have a look at lookups.Exact.process_rhs ​https://github.com/django/django/blob/ea25bdc2b94466bb1563000bf81628dea4d80612/django/db/models/lookups.py#L265-L267 We probably don't want to perform the clear_select_clause and add_fields(['pk']) when the query is already selecting fields. That's exactly what In.process_rhs ​does already by only performing these operations if not getattr(self.rhs, 'has_select_fields', True). Thanks so much for the help Simon! This is a great jumping-off point. There's something that I'm unclear about, which perhaps you can shed some light on. While I was able to replicate the bug with 2.2, when I try to create a test on Master to validate the bug, the group-by behavior seems to have changed. Here's the test that I created: def test_exact_selected_field_rhs_subquery(self): author_1 = Author.objects.create(name='one') author_2 = Author.objects.create(name='two') max_ids = Author.objects.filter(alias__isnull=True).values('alias').annotate(m=Max('id')).values('m') authors = Author.objects.filter(id=max_ids[:1]) self.assertFalse(str(max_ids.query)) # This was just to force the test-runner to output the query. self.assertEqual(authors[0], author_2) And here's the resulting query: SELECT MAX("lookup_author"."id") AS "m" FROM "lookup_author" WHERE "lookup_author"."alias" IS NULL GROUP BY "lookup_author"."alias", "lookup_author"."name" It no longer appears to be grouping by the 'alias' field listed in the initial .values() preceeding the .annotate(). I looked at the docs and release notes to see if there was a behavior change, but didn't see anything listed. Do you know if I'm just misunderstanding what's happening here? Or does this seem like a possible regression? It's possible that a regression was introduced in between. Could you try bisecting the commit that changed the behavior ​https://docs.djangoproject.com/en/dev/internals/contributing/triaging-tickets/#bisecting-a-regression Mmm actually disregard that. The second value in the GROUP BY is due to the ordering value in the Author class's Meta class. class Author(models.Model): name = models.CharField(max_length=100) alias = models.CharField(max_length=50, null=True, blank=True) class Meta: ordering = ('name',) Regarding the bug in question in this ticket, what should the desired behavior be if the inner query is returning multiple fields? With the fix, which allows the inner query to define a field to return/group by, if there are multiple fields used then it will throw a sqlite3.OperationalError: row value misused. Is this the desired behavior or should it avoid this problem by defaulting back to pk if more than one field is selected? I think that we should only default to pk if no fields are selected. The ORM has preliminary support for multi-column lookups and other interface dealing with subqueries doesn't prevent passing queries with multiple fields so I'd stick to the current __in lookup behavior.
2019-09-20T02:23:19Z
3.1
["test_exact_query_rhs_with_selected_columns (lookup.tests.LookupTests)"]
["test_chain_date_time_lookups (lookup.tests.LookupTests)", "test_count (lookup.tests.LookupTests)", "test_custom_field_none_rhs (lookup.tests.LookupTests)", "Lookup.can_use_none_as_rhs=True allows None as a lookup value.", "test_error_messages (lookup.tests.LookupTests)", "test_escaping (lookup.tests.LookupTests)", "test_exact_exists (lookup.tests.LookupTests)", "Transforms are used for __exact=None.", "test_exact_sliced_queryset_limit_one (lookup.tests.LookupTests)", "test_exact_sliced_queryset_limit_one_offset (lookup.tests.LookupTests)", "test_exact_sliced_queryset_not_limited_to_one (lookup.tests.LookupTests)", "test_exclude (lookup.tests.LookupTests)", "test_exists (lookup.tests.LookupTests)", "test_get_next_previous_by (lookup.tests.LookupTests)", "test_in (lookup.tests.LookupTests)", "test_in_bulk (lookup.tests.LookupTests)", "test_in_bulk_lots_of_ids (lookup.tests.LookupTests)", "test_in_bulk_non_unique_field (lookup.tests.LookupTests)", "test_in_bulk_with_field (lookup.tests.LookupTests)", "test_in_different_database (lookup.tests.LookupTests)", "test_in_keeps_value_ordering (lookup.tests.LookupTests)", "test_iterator (lookup.tests.LookupTests)", "test_lookup_collision (lookup.tests.LookupTests)", "test_lookup_date_as_str (lookup.tests.LookupTests)", "test_lookup_int_as_str (lookup.tests.LookupTests)", "test_nested_outerref_lhs (lookup.tests.LookupTests)", "test_none (lookup.tests.LookupTests)", "test_nonfield_lookups (lookup.tests.LookupTests)", "test_pattern_lookups_with_substr (lookup.tests.LookupTests)", "test_regex (lookup.tests.LookupTests)", "test_regex_backreferencing (lookup.tests.LookupTests)", "test_regex_non_ascii (lookup.tests.LookupTests)", "test_regex_non_string (lookup.tests.LookupTests)", "test_regex_null (lookup.tests.LookupTests)", "test_relation_nested_lookup_error (lookup.tests.LookupTests)", "test_unsupported_lookups (lookup.tests.LookupTests)", "test_values (lookup.tests.LookupTests)", "test_values_list (lookup.tests.LookupTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-11905
2f72480fbd27896c986c45193e1603e35c0b19a7
diff --git a/django/db/models/lookups.py b/django/db/models/lookups.py --- a/django/db/models/lookups.py +++ b/django/db/models/lookups.py @@ -1,5 +1,6 @@ import itertools import math +import warnings from copy import copy from django.core.exceptions import EmptyResultSet @@ -9,6 +10,7 @@ ) from django.db.models.query_utils import RegisterLookupMixin from django.utils.datastructures import OrderedSet +from django.utils.deprecation import RemovedInDjango40Warning from django.utils.functional import cached_property @@ -463,6 +465,17 @@ class IsNull(BuiltinLookup): prepare_rhs = False def as_sql(self, compiler, connection): + if not isinstance(self.rhs, bool): + # When the deprecation ends, replace with: + # raise ValueError( + # 'The QuerySet value for an isnull lookup must be True or ' + # 'False.' + # ) + warnings.warn( + 'Using a non-boolean value for an isnull lookup is ' + 'deprecated, use True or False instead.', + RemovedInDjango40Warning, + ) sql, params = compiler.compile(self.lhs) if self.rhs: return "%s IS NULL" % sql, params
diff --git a/tests/lookup/models.py b/tests/lookup/models.py --- a/tests/lookup/models.py +++ b/tests/lookup/models.py @@ -96,3 +96,15 @@ class Product(models.Model): class Stock(models.Model): product = models.ForeignKey(Product, models.CASCADE) qty_available = models.DecimalField(max_digits=6, decimal_places=2) + + +class Freebie(models.Model): + gift_product = models.ForeignKey(Product, models.CASCADE) + stock_id = models.IntegerField(blank=True, null=True) + + stock = models.ForeignObject( + Stock, + from_fields=['stock_id', 'gift_product'], + to_fields=['id', 'product'], + on_delete=models.CASCADE, + ) diff --git a/tests/lookup/tests.py b/tests/lookup/tests.py --- a/tests/lookup/tests.py +++ b/tests/lookup/tests.py @@ -9,9 +9,10 @@ from django.db.models.expressions import Exists, OuterRef from django.db.models.functions import Substr from django.test import TestCase, skipUnlessDBFeature +from django.utils.deprecation import RemovedInDjango40Warning from .models import ( - Article, Author, Game, IsNullWithNoneAsRHS, Player, Season, Tag, + Article, Author, Freebie, Game, IsNullWithNoneAsRHS, Player, Season, Tag, ) @@ -969,3 +970,24 @@ def test_exact_query_rhs_with_selected_columns(self): ).values('max_id') authors = Author.objects.filter(id=authors_max_ids[:1]) self.assertEqual(authors.get(), newest_author) + + def test_isnull_non_boolean_value(self): + # These tests will catch ValueError in Django 4.0 when using + # non-boolean values for an isnull lookup becomes forbidden. + # msg = ( + # 'The QuerySet value for an isnull lookup must be True or False.' + # ) + msg = ( + 'Using a non-boolean value for an isnull lookup is deprecated, ' + 'use True or False instead.' + ) + tests = [ + Author.objects.filter(alias__isnull=1), + Article.objects.filter(author__isnull=1), + Season.objects.filter(games__isnull=1), + Freebie.objects.filter(stock__isnull=1), + ] + for qs in tests: + with self.subTest(qs=qs): + with self.assertWarnsMessage(RemovedInDjango40Warning, msg): + qs.exists()
Prevent using __isnull lookup with non-boolean value. Description (last modified by Mariusz Felisiak) __isnull should not allow for non-boolean values. Using truthy/falsey doesn't promote INNER JOIN to an OUTER JOIN but works fine for a simple queries. Using non-boolean values is ​undocumented and untested. IMO we should raise an error for non-boolean values to avoid confusion and for consistency.
PR here: ​https://github.com/django/django/pull/11873 After the reconsideration I don't think that we should change this ​documented behavior (that is in Django from the very beginning). __isnull lookup expects boolean values in many places and IMO it would be confusing if we'll allow for truthy/falsy values, e.g. take a look at these examples field__isnull='false' or field__isnull='true' (both would return the same result). You can always call bool() on a right hand side. Sorry for my previous acceptation (I shouldn't triage tickets in the weekend). Replying to felixxm: After the reconsideration I don't think that we should change this ​documented behavior (that is in Django from the very beginning). __isnull lookup expects boolean values in many places and IMO it would be confusing if we'll allow for truthy/falsy values, e.g. take a look at these examples field__isnull='false' or field__isnull='true' (both would return the same result). You can always call bool() on a right hand side. Sorry for my previous acceptation (I shouldn't triage tickets in the weekend). I understand your point. But is there anything we can do to avoid people falling for the same pitfall I did? The problem, in my opinion, is that it works fine for simple queries but as soon as you add a join that needs promotion it will break, silently. Maybe we should make it raise an exception when a non-boolean is passed? One valid example is to have a class that implements __bool__. You can see here ​https://github.com/django/django/blob/d9881a025c15d87b2a7883ee50771117450ea90d/django/db/models/lookups.py#L465-L470 that non-bool value is converted to IS NULL and IS NOT NULL already using the truthy/falsy values. IMO it would be confusing if we'll allow for truthy/falsy values, e.g. take a look at these examples fieldisnull='false' or fieldisnull='true' (both would return the same result). This is already the case. It just is inconsistent, in lookups.py field__isnull='false' will be a positive condition but on the query.py it will be the negative condition. Maybe adding a note on the documentation? something like: "Although it might seem like it will work with non-bool fields, this is not supported and can lead to inconsistent behaviours" Agreed, we should raise an error for non-boolean values, e.g. diff --git a/django/db/models/lookups.py b/django/db/models/lookups.py index 9344979c56..fc4a38c4fe 100644 --- a/django/db/models/lookups.py +++ b/django/db/models/lookups.py @@ -463,6 +463,11 @@ class IsNull(BuiltinLookup): prepare_rhs = False def as_sql(self, compiler, connection): + if not isinstance(self.rhs, bool): + raise ValueError( + 'The QuerySet value for an isnull lookup must be True or ' + 'False.' + ) sql, params = compiler.compile(self.lhs) if self.rhs: return "%s IS NULL" % sql, params I changed the ticket description. Thanks, I'll work on it! Wouldn't that possibly break backward compatibility? I'm not familiar with how Django moves in that regard. We can add a release note in "Backwards incompatible changes" or deprecate this and remove in Django 4.0. I have to thing about it, please give me a day, maybe I will change my mind :) No problem. Thanks for taking the time to look into this! Another interesting example related to this: As an anecdote, I've also got bitten by this possibility. An attempt to write WHERE (field IS NULL) = boolean_field as .filter(field__isnull=F('boolean_field')) didn't go as I expected. Alexandr Aktsipetrov -- ​https://groups.google.com/forum/#!msg/django-developers/AhY2b3rxkfA/0sz3hNanCgAJ This example will generate the WHERE .... IS NULL. I guess we also would want an exception thrown here. André, IMO we should deprecate using non-boolean values in Django 3.1 (RemovedInDjango40Warning) and remove in Django 4.0 (even if it is untested and undocumented). I can imagine that a lot of people use e.g. 1 and 0 instead of booleans. Attached diff fixes also issue with passing a F() expression. def as_sql(self, compiler, connection): if not isinstance(self.rhs, bool): raise RemovedInDjango40Warning(...) .... Replying to felixxm: André, IMO we should deprecate using non-boolean values in Django 3.1 (RemovedInDjango40Warning) and remove in Django 4.0 (even if it is untested and undocumented). I can imagine that a lot of people use e.g. 1 and 0 instead of booleans. Attached diff fixes also issue with passing a F() expression. def as_sql(self, compiler, connection): if not isinstance(self.rhs, bool): raise RemovedInDjango40Warning(...) .... Sound like a good plan. Not super familiar with the branch structure of Django. So, I guess the path to follow is to make a PR to master adding the deprecation warning and eventually when master is 4.x we create the PR raising the ValueError. Is that right? Thanks! André, yes mostly. You can find more details about that ​from the documentation.
2019-10-11T18:19:39Z
3.1
["test_isnull_non_boolean_value (lookup.tests.LookupTests)", "test_iterator (lookup.tests.LookupTests)"]
["test_chain_date_time_lookups (lookup.tests.LookupTests)", "test_count (lookup.tests.LookupTests)", "test_custom_field_none_rhs (lookup.tests.LookupTests)", "Lookup.can_use_none_as_rhs=True allows None as a lookup value.", "test_error_messages (lookup.tests.LookupTests)", "test_escaping (lookup.tests.LookupTests)", "test_exact_exists (lookup.tests.LookupTests)", "Transforms are used for __exact=None.", "test_exact_query_rhs_with_selected_columns (lookup.tests.LookupTests)", "test_exact_sliced_queryset_limit_one (lookup.tests.LookupTests)", "test_exact_sliced_queryset_limit_one_offset (lookup.tests.LookupTests)", "test_exact_sliced_queryset_not_limited_to_one (lookup.tests.LookupTests)", "test_exclude (lookup.tests.LookupTests)", "test_exists (lookup.tests.LookupTests)", "test_get_next_previous_by (lookup.tests.LookupTests)", "test_in (lookup.tests.LookupTests)", "test_in_bulk (lookup.tests.LookupTests)", "test_in_bulk_lots_of_ids (lookup.tests.LookupTests)", "test_in_bulk_non_unique_field (lookup.tests.LookupTests)", "test_in_bulk_with_field (lookup.tests.LookupTests)", "test_in_different_database (lookup.tests.LookupTests)", "test_in_keeps_value_ordering (lookup.tests.LookupTests)", "test_lookup_collision (lookup.tests.LookupTests)", "test_lookup_date_as_str (lookup.tests.LookupTests)", "test_lookup_int_as_str (lookup.tests.LookupTests)", "test_nested_outerref_lhs (lookup.tests.LookupTests)", "test_none (lookup.tests.LookupTests)", "test_nonfield_lookups (lookup.tests.LookupTests)", "test_pattern_lookups_with_substr (lookup.tests.LookupTests)", "test_regex (lookup.tests.LookupTests)", "test_regex_backreferencing (lookup.tests.LookupTests)", "test_regex_non_ascii (lookup.tests.LookupTests)", "test_regex_non_string (lookup.tests.LookupTests)", "test_regex_null (lookup.tests.LookupTests)", "test_relation_nested_lookup_error (lookup.tests.LookupTests)", "test_unsupported_lookups (lookup.tests.LookupTests)", "test_values (lookup.tests.LookupTests)", "test_values_list (lookup.tests.LookupTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-11910
d232fd76a85870daf345fd8f8d617fe7802ae194
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 @@ -927,6 +927,10 @@ def generate_altered_fields(self): if remote_field_name: to_field_rename_key = rename_key + (remote_field_name,) if to_field_rename_key in self.renamed_fields: + # Repoint both model and field name because to_field + # inclusion in ForeignKey.deconstruct() is based on + # both. + new_field.remote_field.model = old_field.remote_field.model new_field.remote_field.field_name = old_field.remote_field.field_name # Handle ForeignObjects which can have multiple from_fields/to_fields. from_fields = getattr(new_field, 'from_fields', None)
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 @@ -932,6 +932,30 @@ def test_rename_foreign_object_fields(self): changes, 'app', 0, 1, model_name='bar', old_name='second', new_name='second_renamed', ) + def test_rename_referenced_primary_key(self): + before = [ + ModelState('app', 'Foo', [ + ('id', models.CharField(primary_key=True, serialize=False)), + ]), + ModelState('app', 'Bar', [ + ('id', models.AutoField(primary_key=True)), + ('foo', models.ForeignKey('app.Foo', models.CASCADE)), + ]), + ] + after = [ + ModelState('app', 'Foo', [ + ('renamed_id', models.CharField(primary_key=True, serialize=False)) + ]), + ModelState('app', 'Bar', [ + ('id', models.AutoField(primary_key=True)), + ('foo', models.ForeignKey('app.Foo', models.CASCADE)), + ]), + ] + changes = self.get_changes(before, after, MigrationQuestioner({'ask_rename': True})) + self.assertNumberMigrations(changes, 'app', 1) + self.assertOperationTypes(changes, 'app', 0, ['RenameField']) + self.assertOperationAttributes(changes, 'app', 0, 0, old_name='id', new_name='renamed_id') + def test_rename_field_preserved_db_column(self): """ RenameField is used if a field is renamed and db_column equal to the
ForeignKey's to_field parameter gets the old field's name when renaming a PrimaryKey. Description Having these two models class ModelA(models.Model): field_wrong = models.CharField('field1', max_length=50, primary_key=True) # I'm a Primary key. class ModelB(models.Model): field_fk = models.ForeignKey(ModelA, blank=True, null=True, on_delete=models.CASCADE) ... migrations applyed ... the ModelA.field_wrong field has been renamed ... and Django recognizes the "renaming" # Primary key renamed class ModelA(models.Model): field_fixed = models.CharField('field1', max_length=50, primary_key=True) # I'm a Primary key. Attempts to to_field parameter. The to_field points to the old_name (field_typo) and not to the new one ("field_fixed") class Migration(migrations.Migration): dependencies = [ ('app1', '0001_initial'), ] operations = [ migrations.RenameField( model_name='modela', old_name='field_wrong', new_name='field_fixed', ), migrations.AlterField( model_name='modelb', name='modela', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='app1.ModelB', to_field='field_wrong'), ), ]
Thanks for this ticket. It looks like a regression in dcdd219ee1e062dc6189f382e0298e0adf5d5ddf, because an AlterField operation wasn't generated in such cases before this change (and I don't think we need it).
2019-10-14T01:56:49Z
3.1
["test_rename_referenced_primary_key (migrations.test_autodetector.AutodetectorTests)"]
["test_add_alter_order_with_respect_to (migrations.test_autodetector.AutodetectorTests)", "test_add_blank_textfield_and_charfield (migrations.test_autodetector.AutodetectorTests)", "Test change detection of new constraints.", "test_add_date_fields_with_auto_now_add_asking_for_default (migrations.test_autodetector.AutodetectorTests)", "test_add_date_fields_with_auto_now_add_not_asking_for_null_addition (migrations.test_autodetector.AutodetectorTests)", "test_add_date_fields_with_auto_now_not_asking_for_default (migrations.test_autodetector.AutodetectorTests)", "Tests autodetection of new fields.", "test_add_field_and_foo_together (migrations.test_autodetector.AutodetectorTests)", "#22030 - Adding a field with a default should work.", "Tests index/unique_together detection.", "Test change detection of new indexes.", "#22435 - Adding a ManyToManyField should not prompt for a default.", "test_add_model_order_with_respect_to (migrations.test_autodetector.AutodetectorTests)", "test_add_non_blank_textfield_and_charfield (migrations.test_autodetector.AutodetectorTests)", "Tests detection for adding db_table in model's options.", "Tests detection for changing db_table in model's options'.", "test_alter_db_table_no_changes (migrations.test_autodetector.AutodetectorTests)", "Tests detection for removing db_table in model's options.", "test_alter_db_table_with_model_change (migrations.test_autodetector.AutodetectorTests)", "test_alter_field_to_fk_dependency_other_app (migrations.test_autodetector.AutodetectorTests)", "test_alter_field_to_not_null_oneoff_default (migrations.test_autodetector.AutodetectorTests)", "test_alter_field_to_not_null_with_default (migrations.test_autodetector.AutodetectorTests)", "test_alter_field_to_not_null_without_default (migrations.test_autodetector.AutodetectorTests)", "test_alter_fk_before_model_deletion (migrations.test_autodetector.AutodetectorTests)", "test_alter_many_to_many (migrations.test_autodetector.AutodetectorTests)", "test_alter_model_managers (migrations.test_autodetector.AutodetectorTests)", "Changing a model's options should make a change.", "Changing a proxy model's options should also make a change.", "Tests auto-naming of migrations for graph matching.", "Bases of other models come first.", "test_circular_dependency_mixed_addcreate (migrations.test_autodetector.AutodetectorTests)", "test_circular_dependency_swappable (migrations.test_autodetector.AutodetectorTests)", "test_circular_dependency_swappable2 (migrations.test_autodetector.AutodetectorTests)", "test_circular_dependency_swappable_self (migrations.test_autodetector.AutodetectorTests)", "test_circular_fk_dependency (migrations.test_autodetector.AutodetectorTests)", "test_concrete_field_changed_to_many_to_many (migrations.test_autodetector.AutodetectorTests)", "test_create_model_and_unique_together (migrations.test_autodetector.AutodetectorTests)", "Test creation of new model with constraints already defined.", "Test creation of new model with indexes already defined.", "test_create_with_through_model (migrations.test_autodetector.AutodetectorTests)", "test_custom_deconstructible (migrations.test_autodetector.AutodetectorTests)", "Tests custom naming of migrations for graph matching.", "Field instances are handled correctly by nested deconstruction.", "test_deconstruct_type (migrations.test_autodetector.AutodetectorTests)", "Nested deconstruction descends into dict values.", "Nested deconstruction descends into lists.", "Nested deconstruction descends into tuples.", "test_default_related_name_option (migrations.test_autodetector.AutodetectorTests)", "test_different_regex_does_alter (migrations.test_autodetector.AutodetectorTests)", "test_empty_foo_together (migrations.test_autodetector.AutodetectorTests)", "test_first_dependency (migrations.test_autodetector.AutodetectorTests)", "Having a ForeignKey automatically adds a dependency.", "test_fk_dependency_other_app (migrations.test_autodetector.AutodetectorTests)", "test_foo_together_no_changes (migrations.test_autodetector.AutodetectorTests)", "test_foo_together_ordering (migrations.test_autodetector.AutodetectorTests)", "Tests unique_together and field removal detection & ordering", "test_foreign_key_removed_before_target_model (migrations.test_autodetector.AutodetectorTests)", "test_identical_regex_doesnt_alter (migrations.test_autodetector.AutodetectorTests)", "test_keep_db_table_with_model_change (migrations.test_autodetector.AutodetectorTests)", "test_last_dependency (migrations.test_autodetector.AutodetectorTests)", "test_m2m_w_through_multistep_remove (migrations.test_autodetector.AutodetectorTests)", "test_managed_to_unmanaged (migrations.test_autodetector.AutodetectorTests)", "test_many_to_many_changed_to_concrete_field (migrations.test_autodetector.AutodetectorTests)", "test_many_to_many_removed_before_through_model (migrations.test_autodetector.AutodetectorTests)", "test_many_to_many_removed_before_through_model_2 (migrations.test_autodetector.AutodetectorTests)", "test_mti_inheritance_model_removal (migrations.test_autodetector.AutodetectorTests)", "#23956 - Inheriting models doesn't move *_ptr fields into AddField operations.", "test_nested_deconstructible_objects (migrations.test_autodetector.AutodetectorTests)", "Tests autodetection of new models.", "test_non_circular_foreignkey_dependency_removal (migrations.test_autodetector.AutodetectorTests)", "Tests deletion of old models.", "Test change detection of reordering of fields in indexes.", "test_pk_fk_included (migrations.test_autodetector.AutodetectorTests)", "The autodetector correctly deals with proxy models.", "Bases of proxies come first.", "test_proxy_custom_pk (migrations.test_autodetector.AutodetectorTests)", "FK dependencies still work on proxy models.", "test_proxy_to_mti_with_fk_to_proxy (migrations.test_autodetector.AutodetectorTests)", "test_proxy_to_mti_with_fk_to_proxy_proxy (migrations.test_autodetector.AutodetectorTests)", "test_remove_alter_order_with_respect_to (migrations.test_autodetector.AutodetectorTests)", "Test change detection of removed constraints.", "Tests autodetection of removed fields.", "test_remove_field_and_foo_together (migrations.test_autodetector.AutodetectorTests)", "Test change detection of removed indexes.", "Tests autodetection of renamed fields.", "test_rename_field_and_foo_together (migrations.test_autodetector.AutodetectorTests)", "test_rename_field_foreign_key_to_field (migrations.test_autodetector.AutodetectorTests)", "test_rename_field_preserved_db_column (migrations.test_autodetector.AutodetectorTests)", "test_rename_foreign_object_fields (migrations.test_autodetector.AutodetectorTests)", "test_rename_m2m_through_model (migrations.test_autodetector.AutodetectorTests)", "Tests autodetection of renamed models.", "test_rename_model_reverse_relation_dependencies (migrations.test_autodetector.AutodetectorTests)", "test_rename_model_with_fks_in_different_position (migrations.test_autodetector.AutodetectorTests)", "test_rename_model_with_renamed_rel_field (migrations.test_autodetector.AutodetectorTests)", "test_rename_related_field_preserved_db_column (migrations.test_autodetector.AutodetectorTests)", "test_replace_string_with_foreignkey (migrations.test_autodetector.AutodetectorTests)", "test_same_app_circular_fk_dependency (migrations.test_autodetector.AutodetectorTests)", "test_same_app_circular_fk_dependency_with_unique_together_and_indexes (migrations.test_autodetector.AutodetectorTests)", "test_same_app_no_fk_dependency (migrations.test_autodetector.AutodetectorTests)", "Setting order_with_respect_to adds a field.", "test_supports_functools_partial (migrations.test_autodetector.AutodetectorTests)", "test_swappable (migrations.test_autodetector.AutodetectorTests)", "test_swappable_changed (migrations.test_autodetector.AutodetectorTests)", "test_swappable_circular_multi_mti (migrations.test_autodetector.AutodetectorTests)", "Swappable models get their CreateModel first.", "test_trim_apps (migrations.test_autodetector.AutodetectorTests)", "The autodetector correctly deals with managed models.", "test_unmanaged_custom_pk (migrations.test_autodetector.AutodetectorTests)", "test_unmanaged_delete (migrations.test_autodetector.AutodetectorTests)", "test_unmanaged_to_managed (migrations.test_autodetector.AutodetectorTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-12113
62254c5202e80a68f4fe6572a2be46a3d953de1a
diff --git a/django/db/backends/sqlite3/creation.py b/django/db/backends/sqlite3/creation.py --- a/django/db/backends/sqlite3/creation.py +++ b/django/db/backends/sqlite3/creation.py @@ -98,4 +98,6 @@ def test_db_signature(self): sig = [self.connection.settings_dict['NAME']] if self.is_in_memory_db(test_database_name): sig.append(self.connection.alias) + else: + sig.append(test_database_name) return tuple(sig)
diff --git a/tests/backends/sqlite/test_creation.py b/tests/backends/sqlite/test_creation.py new file mode 100644 --- /dev/null +++ b/tests/backends/sqlite/test_creation.py @@ -0,0 +1,18 @@ +import copy +import unittest + +from django.db import connection +from django.test import SimpleTestCase + + [email protected](connection.vendor == 'sqlite', 'SQLite tests') +class TestDbSignatureTests(SimpleTestCase): + def test_custom_test_name(self): + saved_settings = copy.deepcopy(connection.settings_dict) + try: + connection.settings_dict['NAME'] = None + connection.settings_dict['TEST']['NAME'] = 'custom.sqlite.db' + signature = connection.creation.test_db_signature() + self.assertEqual(signature, (None, 'custom.sqlite.db')) + finally: + connection.settings_dict = saved_settings
admin_views.test_multidb fails with persistent test SQLite database. Description (last modified by Mariusz Felisiak) I've tried using persistent SQLite databases for the tests (to make use of --keepdb), but at least some test fails with: sqlite3.OperationalError: database is locked This is not an issue when only using TEST["NAME"] with "default" (which is good enough in terms of performance). diff --git i/tests/test_sqlite.py w/tests/test_sqlite.py index f1b65f7d01..9ce4e32e14 100644 --- i/tests/test_sqlite.py +++ w/tests/test_sqlite.py @@ -15,9 +15,15 @@ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', + 'TEST': { + 'NAME': 'test_default.sqlite3' + }, }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', + 'TEST': { + 'NAME': 'test_other.sqlite3' + }, } } % tests/runtests.py admin_views.test_multidb -v 3 --keepdb --parallel 1 … Operations to perform: Synchronize unmigrated apps: admin_views, auth, contenttypes, messages, sessions, staticfiles Apply all migrations: admin, sites Running pre-migrate handlers for application contenttypes Running pre-migrate handlers for application auth Running pre-migrate handlers for application sites Running pre-migrate handlers for application sessions Running pre-migrate handlers for application admin Running pre-migrate handlers for application admin_views Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: No migrations to apply. Running post-migrate handlers for application contenttypes Running post-migrate handlers for application auth Running post-migrate handlers for application sites Running post-migrate handlers for application sessions Running post-migrate handlers for application admin Running post-migrate handlers for application admin_views System check identified no issues (0 silenced). ERROR ====================================================================== ERROR: setUpClass (admin_views.test_multidb.MultiDatabaseTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "…/Vcs/django/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "…/Vcs/django/django/db/backends/sqlite3/base.py", line 391, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: database is locked The above exception was the direct cause of the following exception: Traceback (most recent call last): File "…/Vcs/django/django/test/testcases.py", line 1137, in setUpClass cls.setUpTestData() File "…/Vcs/django/tests/admin_views/test_multidb.py", line 40, in setUpTestData username='admin', password='something', email='[email protected]', File "…/Vcs/django/django/contrib/auth/models.py", line 158, in create_superuser return self._create_user(username, email, password, **extra_fields) File "…/Vcs/django/django/contrib/auth/models.py", line 141, in _create_user user.save(using=self._db) File "…/Vcs/django/django/contrib/auth/base_user.py", line 66, in save super().save(*args, **kwargs) File "…/Vcs/django/django/db/models/base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "…/Vcs/django/django/db/models/base.py", line 779, in save_base force_update, using, update_fields, File "…/Vcs/django/django/db/models/base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "…/Vcs/django/django/db/models/base.py", line 908, in _do_insert using=using, raw=raw) File "…/Vcs/django/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "…/Vcs/django/django/db/models/query.py", line 1175, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "…/Vcs/django/django/db/models/sql/compiler.py", line 1321, in execute_sql cursor.execute(sql, params) File "…/Vcs/django/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "…/Vcs/django/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "…/Vcs/django/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "…/Vcs/django/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "…/Vcs/django/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "…/Vcs/django/django/db/backends/sqlite3/base.py", line 391, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: database is locked
This is only an issue when setting TEST["NAME"], but not NAME. The following works: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'django_tests_default.sqlite3', }, 'other': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'django_tests_other.sqlite3', } } Reproduced at 0dd2308cf6f559a4f4b50edd7c005c7cf025d1aa. Created ​PR Hey, I am able to replicate this bug and was able to fix it as well with the help of ​https://github.com/django/django/pull/11678, but the point I am stuck at is how to test it, I am not able to manipulate the cls variable so the next option that is left is create a file like test_sqlite and pass it as a parameter in runtests, should I be doing that? I think we should add tests/backends/sqlite/test_creation.py with regressions tests for test_db_signature(), you can take a look at tests/backends/base/test_creation.py with similar tests.
2019-11-20T17:49:06Z
3.1
["test_custom_test_name (backends.sqlite.test_creation.TestDbSignatureTests)"]
[]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-12184
5d674eac871a306405b0fbbaeb17bbeba9c68bf3
diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py --- a/django/urls/resolvers.py +++ b/django/urls/resolvers.py @@ -158,8 +158,9 @@ def match(self, path): # If there are any named groups, use those as kwargs, ignoring # non-named groups. Otherwise, pass all non-named arguments as # positional arguments. - kwargs = {k: v for k, v in match.groupdict().items() if v is not None} + kwargs = match.groupdict() args = () if kwargs else match.groups() + kwargs = {k: v for k, v in kwargs.items() if v is not None} return path[match.end():], args, kwargs return None
diff --git a/tests/urlpatterns/path_urls.py b/tests/urlpatterns/path_urls.py --- a/tests/urlpatterns/path_urls.py +++ b/tests/urlpatterns/path_urls.py @@ -12,6 +12,11 @@ path('included_urls/', include('urlpatterns.included_urls')), re_path(r'^regex/(?P<pk>[0-9]+)/$', views.empty_view, name='regex'), re_path(r'^regex_optional/(?P<arg1>\d+)/(?:(?P<arg2>\d+)/)?', views.empty_view, name='regex_optional'), + re_path( + r'^regex_only_optional/(?:(?P<arg1>\d+)/)?', + views.empty_view, + name='regex_only_optional', + ), path('', include('urlpatterns.more_urls')), path('<lang>/<path:url>/', views.empty_view, name='lang-and-path'), ] diff --git a/tests/urlpatterns/tests.py b/tests/urlpatterns/tests.py --- a/tests/urlpatterns/tests.py +++ b/tests/urlpatterns/tests.py @@ -68,6 +68,16 @@ def test_re_path_with_optional_parameter(self): r'^regex_optional/(?P<arg1>\d+)/(?:(?P<arg2>\d+)/)?', ) + def test_re_path_with_missing_optional_parameter(self): + match = resolve('/regex_only_optional/') + self.assertEqual(match.url_name, 'regex_only_optional') + self.assertEqual(match.kwargs, {}) + self.assertEqual(match.args, ()) + self.assertEqual( + match.route, + r'^regex_only_optional/(?:(?P<arg1>\d+)/)?', + ) + def test_path_lookup_with_inclusion(self): match = resolve('/included_urls/extra/something/') self.assertEqual(match.url_name, 'inner-extra')
Optional URL params crash some view functions. Description My use case, running fine with Django until 2.2: URLConf: urlpatterns += [ ... re_path(r'^module/(?P<format>(html|json|xml))?/?$', views.modules, name='modules'), ] View: def modules(request, format='html'): ... return render(...) With Django 3.0, this is now producing an error: Traceback (most recent call last): File "/l10n/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/l10n/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/l10n/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /module/ Exception Value: modules() takes from 1 to 2 positional arguments but 3 were given
Tracked regression in 76b993a117b61c41584e95149a67d8a1e9f49dd1. It seems to work if you remove the extra parentheses: re_path(r'^module/(?P<format>html|json|xml)?/?$', views.modules, name='modules'), It seems Django is getting confused by the nested groups.
2019-12-05T13:09:48Z
3.1
["test_re_path_with_missing_optional_parameter (urlpatterns.tests.SimplifiedURLTests)"]
["test_allows_non_ascii_but_valid_identifiers (urlpatterns.tests.ParameterRestrictionTests)", "test_non_identifier_parameter_name_causes_exception (urlpatterns.tests.ParameterRestrictionTests)", "test_matching_urls (urlpatterns.tests.ConverterTests)", "test_nonmatching_urls (urlpatterns.tests.ConverterTests)", "test_resolve_type_error_propagates (urlpatterns.tests.ConversionExceptionTests)", "test_resolve_value_error_means_no_match (urlpatterns.tests.ConversionExceptionTests)", "test_reverse_value_error_propagates (urlpatterns.tests.ConversionExceptionTests)", "test_converter_resolve (urlpatterns.tests.SimplifiedURLTests)", "test_converter_reverse (urlpatterns.tests.SimplifiedURLTests)", "test_converter_reverse_with_second_layer_instance_namespace (urlpatterns.tests.SimplifiedURLTests)", "test_invalid_converter (urlpatterns.tests.SimplifiedURLTests)", "test_path_inclusion_is_matchable (urlpatterns.tests.SimplifiedURLTests)", "test_path_inclusion_is_reversible (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_with_double_inclusion (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_with_empty_string_inclusion (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_with_inclusion (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_with_multiple_parameters (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_with_typed_parameters (urlpatterns.tests.SimplifiedURLTests)", "test_path_lookup_without_parameters (urlpatterns.tests.SimplifiedURLTests)", "test_path_reverse_with_parameter (urlpatterns.tests.SimplifiedURLTests)", "test_path_reverse_without_parameter (urlpatterns.tests.SimplifiedURLTests)", "test_re_path (urlpatterns.tests.SimplifiedURLTests)", "test_re_path_with_optional_parameter (urlpatterns.tests.SimplifiedURLTests)", "test_space_in_route (urlpatterns.tests.SimplifiedURLTests)", "test_two_variable_at_start_of_path_pattern (urlpatterns.tests.SimplifiedURLTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
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 value: return format_html('<a href="{}">{}</a>', value.url, value) + elif isinstance(field, models.JSONField) and value: + try: + return field.get_prep_value(value) + except TypeError: + return display_for_value(value, empty_value_display) else: return display_for_value(value, empty_value_display)
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_value, self.empty_value) + display_value = display_for_field(None, models.JSONField(), self.empty_value) + self.assertEqual(display_value, self.empty_value) + + def test_json_display_for_field(self): + tests = [ + ({'a': {'b': 'c'}}, '{"a": {"b": "c"}}'), + (['a', 'b'], '["a", "b"]'), + ('a', '"a"'), + ({('a', 'b'): 'c'}, "{('a', 'b'): 'c'}"), # Invalid JSON. + ] + for value, display_value in tests: + with self.subTest(value=value): + self.assertEqual( + display_for_field(value, models.JSONField(), self.empty_value), + display_value, + ) + def test_number_formats_display_for_field(self): display_value = display_for_field(12345.6789, models.FloatField(), self.empty_value) self.assertEqual(display_value, '12345.6789')
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.display_for_field to call the prepare_value of the JSONField (not calling json.dumps directly to take care of the InvalidJSONInput case).
​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.models.JSONField instance checks from that point.
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_siblings (admin_utils.tests.NestedObjectsTests)", "test_unrelated_roots (admin_utils.tests.NestedObjectsTests)", "test_flatten (admin_utils.tests.UtilsTests)", "test_flatten_fieldsets (admin_utils.tests.UtilsTests)", "test_label_for_field_form_argument (admin_utils.tests.UtilsTests)", "test_label_for_property (admin_utils.tests.UtilsTests)", "test_list_display_for_value (admin_utils.tests.UtilsTests)", "test_list_display_for_value_boolean (admin_utils.tests.UtilsTests)", "test_null_display_for_field (admin_utils.tests.UtilsTests)", "test_number_formats_display_for_field (admin_utils.tests.UtilsTests)", "test_number_formats_with_thousand_separator_display_for_field (admin_utils.tests.UtilsTests)", "test_quote (admin_utils.tests.UtilsTests)", "test_related_name (admin_utils.tests.UtilsTests)", "test_safestring_in_field_label (admin_utils.tests.UtilsTests)", "test_values_from_lookup_field (admin_utils.tests.UtilsTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-12470
142ab6846ac09d6d401e26fc8b6b988a583ac0f5
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 @@ -709,9 +709,9 @@ def find_ordering_name(self, name, opts, alias=None, default_order='ASC', field, targets, alias, joins, path, opts, transform_function = self._setup_joins(pieces, opts, alias) # If we get to this point and the field is a relation to another model, - # append the default ordering for that model unless the attribute name - # of the field is specified. - if field.is_relation and opts.ordering and getattr(field, 'attname', None) != name: + # append the default ordering for that model unless it is the pk + # shortcut or the attribute name of the field that is specified. + if field.is_relation and opts.ordering and getattr(field, 'attname', None) != name and name != 'pk': # Firstly, avoid infinite loops. already_seen = already_seen or set() join_tuple = tuple(getattr(self.query.alias_map[j], 'join_cols', None) for j in joins)
diff --git a/tests/model_inheritance/models.py b/tests/model_inheritance/models.py --- a/tests/model_inheritance/models.py +++ b/tests/model_inheritance/models.py @@ -181,6 +181,8 @@ class GrandParent(models.Model): place = models.ForeignKey(Place, models.CASCADE, null=True, related_name='+') class Meta: + # Ordering used by test_inherited_ordering_pk_desc. + ordering = ['-pk'] unique_together = ('first_name', 'last_name') diff --git a/tests/model_inheritance/tests.py b/tests/model_inheritance/tests.py --- a/tests/model_inheritance/tests.py +++ b/tests/model_inheritance/tests.py @@ -7,7 +7,7 @@ from .models import ( Base, Chef, CommonInfo, GrandChild, GrandParent, ItalianRestaurant, - MixinModel, ParkingLot, Place, Post, Restaurant, Student, SubBase, + MixinModel, Parent, ParkingLot, Place, Post, Restaurant, Student, SubBase, Supplier, Title, Worker, ) @@ -204,6 +204,19 @@ class A(models.Model): self.assertEqual(A.attr.called, (A, 'attr')) + def test_inherited_ordering_pk_desc(self): + p1 = Parent.objects.create(first_name='Joe', email='[email protected]') + p2 = Parent.objects.create(first_name='Jon', email='[email protected]') + expected_order_by_sql = 'ORDER BY %s.%s DESC' % ( + connection.ops.quote_name(Parent._meta.db_table), + connection.ops.quote_name( + Parent._meta.get_field('grandparent_ptr').column + ), + ) + qs = Parent.objects.all() + self.assertSequenceEqual(qs, [p2, p1]) + self.assertIn(expected_order_by_sql, str(qs.query)) + class ModelInheritanceDataTests(TestCase): @classmethod
Inherited model doesn't correctly order by "-pk" when specified on Parent.Meta.ordering Description Given the following model definition: from django.db import models class Parent(models.Model): class Meta: ordering = ["-pk"] class Child(Parent): pass Querying the Child class results in the following: >>> print(Child.objects.all().query) SELECT "myapp_parent"."id", "myapp_child"."parent_ptr_id" FROM "myapp_child" INNER JOIN "myapp_parent" ON ("myapp_child"."parent_ptr_id" = "myapp_parent"."id") ORDER BY "myapp_parent"."id" ASC The query is ordered ASC but I expect the order to be DESC.
2020-02-19T04:48:55Z
3.1
["test_inherited_ordering_pk_desc (model_inheritance.tests.ModelInheritanceTests)"]
["test_abstract_fk_related_name (model_inheritance.tests.InheritanceSameModelNameTests)", "test_unique (model_inheritance.tests.InheritanceUniqueTests)", "test_unique_together (model_inheritance.tests.InheritanceUniqueTests)", "test_abstract (model_inheritance.tests.ModelInheritanceTests)", "test_abstract_parent_link (model_inheritance.tests.ModelInheritanceTests)", "Creating a child with non-abstract parents only issues INSERTs.", "test_custompk_m2m (model_inheritance.tests.ModelInheritanceTests)", "test_eq (model_inheritance.tests.ModelInheritanceTests)", "test_init_subclass (model_inheritance.tests.ModelInheritanceTests)", "test_meta_fields_and_ordering (model_inheritance.tests.ModelInheritanceTests)", "test_mixin_init (model_inheritance.tests.ModelInheritanceTests)", "test_model_with_distinct_accessors (model_inheritance.tests.ModelInheritanceTests)", "test_model_with_distinct_related_query_name (model_inheritance.tests.ModelInheritanceTests)", "test_reverse_relation_for_different_hierarchy_tree (model_inheritance.tests.ModelInheritanceTests)", "test_set_name (model_inheritance.tests.ModelInheritanceTests)", "test_update_parent_filtering (model_inheritance.tests.ModelInheritanceTests)", "test_exclude_inherited_on_null (model_inheritance.tests.ModelInheritanceDataTests)", "test_filter_inherited_model (model_inheritance.tests.ModelInheritanceDataTests)", "test_filter_inherited_on_null (model_inheritance.tests.ModelInheritanceDataTests)", "test_filter_on_parent_returns_object_of_parent_type (model_inheritance.tests.ModelInheritanceDataTests)", "test_inherited_does_not_exist_exception (model_inheritance.tests.ModelInheritanceDataTests)", "test_inherited_multiple_objects_returned_exception (model_inheritance.tests.ModelInheritanceDataTests)", "test_parent_cache_reuse (model_inheritance.tests.ModelInheritanceDataTests)", "test_parent_child_one_to_one_link (model_inheritance.tests.ModelInheritanceDataTests)", "test_parent_child_one_to_one_link_on_nonrelated_objects (model_inheritance.tests.ModelInheritanceDataTests)", "test_parent_fields_available_for_filtering_in_child_model (model_inheritance.tests.ModelInheritanceDataTests)", "test_related_objects_for_inherited_models (model_inheritance.tests.ModelInheritanceDataTests)", "test_select_related_defer (model_inheritance.tests.ModelInheritanceDataTests)", "test_select_related_works_on_parent_model_fields (model_inheritance.tests.ModelInheritanceDataTests)", "test_update_inherited_model (model_inheritance.tests.ModelInheritanceDataTests)", "test_update_query_counts (model_inheritance.tests.ModelInheritanceDataTests)", "test_update_works_on_parent_and_child_models_at_once (model_inheritance.tests.ModelInheritanceDataTests)", "test_values_works_on_parent_model_fields (model_inheritance.tests.ModelInheritanceDataTests)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
django/django
django__django-12589
895f28f9cbed817c00ab68770433170d83132d90
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 @@ -1927,6 +1927,19 @@ def set_group_by(self, allow_aliases=True): primary key, and the query would be equivalent, the optimization will be made automatically. """ + # Column names from JOINs to check collisions with aliases. + if allow_aliases: + column_names = set() + seen_models = set() + for join in list(self.alias_map.values())[1:]: # Skip base table. + model = join.join_field.related_model + if model not in seen_models: + column_names.update({ + field.column + for field in model._meta.local_concrete_fields + }) + seen_models.add(model) + group_by = list(self.select) if self.annotation_select: for alias, annotation in self.annotation_select.items(): @@ -1940,7 +1953,7 @@ def set_group_by(self, allow_aliases=True): warnings.warn(msg, category=RemovedInDjango40Warning) group_by_cols = annotation.get_group_by_cols() else: - if not allow_aliases: + if not allow_aliases or alias in column_names: alias = None group_by_cols = annotation.get_group_by_cols(alias=alias) group_by.extend(group_by_cols)
diff --git a/tests/aggregation/models.py b/tests/aggregation/models.py --- a/tests/aggregation/models.py +++ b/tests/aggregation/models.py @@ -5,6 +5,7 @@ class Author(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() friends = models.ManyToManyField('self', blank=True) + rating = models.FloatField(null=True) def __str__(self): return self.name diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py --- a/tests/aggregation/tests.py +++ b/tests/aggregation/tests.py @@ -1191,6 +1191,22 @@ def test_aggregation_subquery_annotation_values(self): }, ]) + def test_aggregation_subquery_annotation_values_collision(self): + books_rating_qs = Book.objects.filter( + publisher=OuterRef('pk'), + price=Decimal('29.69'), + ).values('rating') + publisher_qs = Publisher.objects.filter( + book__contact__age__gt=20, + name=self.p1.name, + ).annotate( + rating=Subquery(books_rating_qs), + contacts_count=Count('book__contact'), + ).values('rating').annotate(total_count=Count('rating')) + self.assertEqual(list(publisher_qs), [ + {'rating': 4.0, 'total_count': 2}, + ]) + @skipUnlessDBFeature('supports_subqueries_in_group_by') @skipIf( connection.vendor == 'mysql' and 'ONLY_FULL_GROUP_BY' in connection.sql_mode,
Django 3.0: "GROUP BY" clauses error with tricky field annotation Description Let's pretend that we have next model structure with next model's relations: class A(models.Model): bs = models.ManyToManyField('B', related_name="a", through="AB") class B(models.Model): pass class AB(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE, related_name="ab_a") b = models.ForeignKey(B, on_delete=models.CASCADE, related_name="ab_b") status = models.IntegerField() class C(models.Model): a = models.ForeignKey( A, null=True, blank=True, on_delete=models.SET_NULL, related_name="c", verbose_name=_("a") ) status = models.IntegerField() Let's try to evaluate next query ab_query = AB.objects.filter(a=OuterRef("pk"), b=1) filter_conditions = Q(pk=1) | Q(ab_a__b=1) query = A.objects.\ filter(filter_conditions).\ annotate( status=Subquery(ab_query.values("status")), c_count=Count("c"), ) answer = query.values("status").annotate(total_count=Count("status")) print(answer.query) print(answer) On Django 3.0.4 we have an error django.db.utils.ProgrammingError: column reference "status" is ambiguous and query is next: SELECT (SELECT U0."status" FROM "test_app_ab" U0 WHERE (U0."a_id" = "test_app_a"."id" AND U0."b_id" = 1)) AS "status", COUNT((SELECT U0."status" FROM "test_app_ab" U0 WHERE (U0."a_id" = "test_app_a"."id" AND U0."b_id" = 1))) AS "total_count" FROM "test_app_a" LEFT OUTER JOIN "test_app_ab" ON ("test_app_a"."id" = "test_app_ab"."a_id") LEFT OUTER JOIN "test_app_c" ON ("test_app_a"."id" = "test_app_c"."a_id") WHERE ("test_app_a"."id" = 1 OR "test_app_ab"."b_id" = 1) GROUP BY "status" However, Django 2.2.11 processed this query properly with the next query: SELECT (SELECT U0."status" FROM "test_app_ab" U0 WHERE (U0."a_id" = ("test_app_a"."id") AND U0."b_id" = 1)) AS "status", COUNT((SELECT U0."status" FROM "test_app_ab" U0 WHERE (U0."a_id" = ("test_app_a"."id") AND U0."b_id" = 1))) AS "total_count" FROM "test_app_a" LEFT OUTER JOIN "test_app_ab" ON ("test_app_a"."id" = "test_app_ab"."a_id") LEFT OUTER JOIN "test_app_c" ON ("test_app_a"."id" = "test_app_c"."a_id") WHERE ("test_app_a"."id" = 1 OR "test_app_ab"."b_id" = 1) GROUP BY (SELECT U0."status" FROM "test_app_ab" U0 WHERE (U0."a_id" = ("test_app_a"."id") AND U0."b_id" = 1)) so, the difference in "GROUP BY" clauses (as DB provider uses "django.db.backends.postgresql", postgresql 11)
This is due to a collision of AB.status and the status annotation. The easiest way to solve this issue is to disable group by alias when a collision is detected with involved table columns. This can be easily worked around by avoiding to use an annotation name that conflicts with involved table column names. @Simon I think we have the ​check for collision in annotation alias and model fields . How can we find the involved tables columns? Thanks Hasan this is another kind of collision, these fields are not selected and part of join tables so they won't be part of names. We can't change the behavior at the annotate() level as it would be backward incompatible and require extra checks every time an additional table is joined. What needs to be adjust is sql.Query.set_group_by to set alias=None if alias is not None and alias in {... set of all column names of tables in alias_map ...} before calling annotation.get_group_by_cols ​https://github.com/django/django/blob/fc0fa72ff4cdbf5861a366e31cb8bbacd44da22d/django/db/models/sql/query.py#L1943-L1945
2020-03-19T19:04:17Z
3.1
["test_aggregation_subquery_annotation_values_collision (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.AggregateTestCase)", "test_aggregate_over_complex_annotation (aggregation.tests.AggregateTestCase)", "test_aggregation_exists_annotation (aggregation.tests.AggregateTestCase)", "test_aggregation_expressions (aggregation.tests.AggregateTestCase)", "test_aggregation_order_by_not_selected_annotation_values (aggregation.tests.AggregateTestCase)", "Subquery annotations are excluded from the GROUP BY if they are", "test_aggregation_subquery_annotation_exists (aggregation.tests.AggregateTestCase)", "test_aggregation_subquery_annotation_multivalued (aggregation.tests.AggregateTestCase)", "test_aggregation_subquery_annotation_related_field (aggregation.tests.AggregateTestCase)", "test_aggregation_subquery_annotation_values (aggregation.tests.AggregateTestCase)", "test_annotate_basic (aggregation.tests.AggregateTestCase)", "test_annotate_defer (aggregation.tests.AggregateTestCase)", "test_annotate_defer_select_related (aggregation.tests.AggregateTestCase)", "test_annotate_m2m (aggregation.tests.AggregateTestCase)", "test_annotate_ordering (aggregation.tests.AggregateTestCase)", "test_annotate_over_annotate (aggregation.tests.AggregateTestCase)", "test_annotate_values (aggregation.tests.AggregateTestCase)", "test_annotate_values_aggregate (aggregation.tests.AggregateTestCase)", "test_annotate_values_list (aggregation.tests.AggregateTestCase)", "test_annotated_aggregate_over_annotated_aggregate (aggregation.tests.AggregateTestCase)", "test_annotation (aggregation.tests.AggregateTestCase)", "test_annotation_expressions (aggregation.tests.AggregateTestCase)", "test_arguments_must_be_expressions (aggregation.tests.AggregateTestCase)", "test_avg_decimal_field (aggregation.tests.AggregateTestCase)", "test_avg_duration_field (aggregation.tests.AggregateTestCase)", "test_backwards_m2m_annotate (aggregation.tests.AggregateTestCase)", "test_combine_different_types (aggregation.tests.AggregateTestCase)", "test_complex_aggregations_require_kwarg (aggregation.tests.AggregateTestCase)", "test_complex_values_aggregation (aggregation.tests.AggregateTestCase)", "test_count (aggregation.tests.AggregateTestCase)", "test_count_distinct_expression (aggregation.tests.AggregateTestCase)", "test_count_star (aggregation.tests.AggregateTestCase)", "test_dates_with_aggregation (aggregation.tests.AggregateTestCase)", "test_decimal_max_digits_has_no_effect (aggregation.tests.AggregateTestCase)", "test_distinct_on_aggregate (aggregation.tests.AggregateTestCase)", "test_empty_aggregate (aggregation.tests.AggregateTestCase)", "test_even_more_aggregate (aggregation.tests.AggregateTestCase)", "test_expression_on_aggregation (aggregation.tests.AggregateTestCase)", "test_filter_aggregate (aggregation.tests.AggregateTestCase)", "test_filtering (aggregation.tests.AggregateTestCase)", "test_fkey_aggregate (aggregation.tests.AggregateTestCase)", "test_group_by_exists_annotation (aggregation.tests.AggregateTestCase)", "test_group_by_subquery_annotation (aggregation.tests.AggregateTestCase)", "test_grouped_annotation_in_group_by (aggregation.tests.AggregateTestCase)", "test_missing_output_field_raises_error (aggregation.tests.AggregateTestCase)", "test_more_aggregation (aggregation.tests.AggregateTestCase)", "test_multi_arg_aggregate (aggregation.tests.AggregateTestCase)", "test_multiple_aggregates (aggregation.tests.AggregateTestCase)", "test_non_grouped_annotation_not_in_group_by (aggregation.tests.AggregateTestCase)", "test_nonaggregate_aggregation_throws (aggregation.tests.AggregateTestCase)", "test_nonfield_annotation (aggregation.tests.AggregateTestCase)", "test_order_of_precedence (aggregation.tests.AggregateTestCase)", "test_related_aggregate (aggregation.tests.AggregateTestCase)", "test_reverse_fkey_annotate (aggregation.tests.AggregateTestCase)", "test_single_aggregate (aggregation.tests.AggregateTestCase)", "test_sum_distinct_aggregate (aggregation.tests.AggregateTestCase)", "test_sum_duration_field (aggregation.tests.AggregateTestCase)", "test_ticket11881 (aggregation.tests.AggregateTestCase)", "test_ticket12886 (aggregation.tests.AggregateTestCase)", "test_ticket17424 (aggregation.tests.AggregateTestCase)", "test_values_aggregation (aggregation.tests.AggregateTestCase)", "test_values_annotation_with_expression (aggregation.tests.AggregateTestCase)"]
0668164b4ac93a5be79f5b87fae83c657124d9ab
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card