hash
stringlengths
64
64
content
stringlengths
0
1.51M
637e9b4883b36e5a3f72d458e688be4407d9a30488e2a765ce72da31ee736b5a
from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class Book(models.Model): title = models.CharField(max_length=50) year = models.PositiveIntegerField(null=True, blank=True) author = models.ForeignKey( User, models.SET_NULL, verbose_name="Verbose Author", related_name="books_authored", blank=True, null=True, ) contributors = models.ManyToManyField( User, verbose_name="Verbose Contributors", related_name="books_contributed", blank=True, ) employee = models.ForeignKey( "Employee", models.SET_NULL, verbose_name="Employee", blank=True, null=True, ) is_best_seller = models.BooleanField(default=0, null=True) date_registered = models.DateField(null=True) availability = models.BooleanField( choices=( (False, "Paid"), (True, "Free"), (None, "Obscure"), ), null=True, ) # This field name is intentionally 2 characters long (#16080). no = models.IntegerField(verbose_name="number", blank=True, null=True) CHOICES = [ ("non-fiction", "Non-Fictional"), ("fiction", "Fictional"), (None, "Not categorized"), ("", "We don't know"), ] category = models.CharField(max_length=20, choices=CHOICES, blank=True, null=True) def __str__(self): return self.title class ImprovedBook(models.Model): book = models.OneToOneField(Book, models.CASCADE) class Department(models.Model): code = models.CharField(max_length=4, unique=True) description = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.description class Employee(models.Model): department = models.ForeignKey(Department, models.CASCADE, to_field="code") name = models.CharField(max_length=100) def __str__(self): return self.name class TaggedItem(models.Model): tag = models.SlugField() content_type = models.ForeignKey( ContentType, models.CASCADE, related_name="tagged_items" ) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") def __str__(self): return self.tag class Bookmark(models.Model): url = models.URLField() tags = GenericRelation(TaggedItem) CHOICES = [ ("a", "A"), (None, "None"), ("", "-"), ] none_or_null = models.CharField( max_length=20, choices=CHOICES, blank=True, null=True ) def __str__(self): return self.url
b0b24617af225964f7ebf0167d563e292855787d3200117266de2038d85d4991
from django.db import connection, transaction from django.db.models import ( CharField, F, Func, IntegerField, JSONField, OuterRef, Q, Subquery, Value, Window, ) from django.db.models.fields.json import KeyTextTransform, KeyTransform from django.db.models.functions import Cast, Concat, Substr from django.test import skipUnlessDBFeature from django.test.utils import Approximate, ignore_warnings from django.utils import timezone from django.utils.deprecation import RemovedInDjango51Warning from . import PostgreSQLTestCase from .models import AggregateTestModel, HotelReservation, Room, StatTestModel try: from django.contrib.postgres.aggregates import ( ArrayAgg, BitAnd, BitOr, BitXor, BoolAnd, BoolOr, Corr, CovarPop, JSONBAgg, RegrAvgX, RegrAvgY, RegrCount, RegrIntercept, RegrR2, RegrSlope, RegrSXX, RegrSXY, RegrSYY, StatAggregate, StringAgg, ) from django.contrib.postgres.fields import ArrayField except ImportError: pass # psycopg2 is not installed class TestGeneralAggregate(PostgreSQLTestCase): @classmethod def setUpTestData(cls): cls.aggs = AggregateTestModel.objects.bulk_create( [ AggregateTestModel( boolean_field=True, char_field="Foo1", text_field="Text1", integer_field=0, ), AggregateTestModel( boolean_field=False, char_field="Foo2", text_field="Text2", integer_field=1, json_field={"lang": "pl"}, ), AggregateTestModel( boolean_field=False, char_field="Foo4", text_field="Text4", integer_field=2, json_field={"lang": "en"}, ), AggregateTestModel( boolean_field=True, char_field="Foo3", text_field="Text3", integer_field=0, json_field={"breed": "collie"}, ), ] ) def test_empty_result_set(self): AggregateTestModel.objects.all().delete() tests = [ ArrayAgg("char_field"), ArrayAgg("integer_field"), ArrayAgg("boolean_field"), BitAnd("integer_field"), BitOr("integer_field"), BoolAnd("boolean_field"), BoolOr("boolean_field"), JSONBAgg("integer_field"), StringAgg("char_field", delimiter=";"), ] if connection.features.has_bit_xor: tests.append(BitXor("integer_field")) for aggregation in tests: with self.subTest(aggregation=aggregation): # Empty result with non-execution optimization. with self.assertNumQueries(0): values = AggregateTestModel.objects.none().aggregate( aggregation=aggregation, ) self.assertEqual(values, {"aggregation": None}) # Empty result when query must be executed. with self.assertNumQueries(1): values = AggregateTestModel.objects.aggregate( aggregation=aggregation, ) self.assertEqual(values, {"aggregation": None}) def test_default_argument(self): AggregateTestModel.objects.all().delete() tests = [ (ArrayAgg("char_field", default=["<empty>"]), ["<empty>"]), (ArrayAgg("integer_field", default=[0]), [0]), (ArrayAgg("boolean_field", default=[False]), [False]), (BitAnd("integer_field", default=0), 0), (BitOr("integer_field", default=0), 0), (BoolAnd("boolean_field", default=False), False), (BoolOr("boolean_field", default=False), False), (JSONBAgg("integer_field", default=["<empty>"]), ["<empty>"]), ( JSONBAgg("integer_field", default=Value(["<empty>"], JSONField())), ["<empty>"], ), (StringAgg("char_field", delimiter=";", default="<empty>"), "<empty>"), ( StringAgg("char_field", delimiter=";", default=Value("<empty>")), "<empty>", ), ] if connection.features.has_bit_xor: tests.append((BitXor("integer_field", default=0), 0)) for aggregation, expected_result in tests: with self.subTest(aggregation=aggregation): # Empty result with non-execution optimization. with self.assertNumQueries(0): values = AggregateTestModel.objects.none().aggregate( aggregation=aggregation, ) self.assertEqual(values, {"aggregation": expected_result}) # Empty result when query must be executed. with transaction.atomic(), self.assertNumQueries(1): values = AggregateTestModel.objects.aggregate( aggregation=aggregation, ) self.assertEqual(values, {"aggregation": expected_result}) @ignore_warnings(category=RemovedInDjango51Warning) def test_jsonb_agg_default_str_value(self): AggregateTestModel.objects.all().delete() queryset = AggregateTestModel.objects.all() self.assertEqual( queryset.aggregate( aggregation=JSONBAgg("integer_field", default=Value("<empty>")) ), {"aggregation": "<empty>"}, ) def test_jsonb_agg_default_str_value_deprecation(self): queryset = AggregateTestModel.objects.all() msg = ( "Passing a Value() with an output_field that isn't a JSONField as " "JSONBAgg(default) is deprecated. Pass default=Value('<empty>', " "output_field=JSONField()) instead." ) with self.assertWarnsMessage(RemovedInDjango51Warning, msg): queryset.aggregate( aggregation=JSONBAgg("integer_field", default=Value("<empty>")) ) with self.assertWarnsMessage(RemovedInDjango51Warning, msg): queryset.none().aggregate( aggregation=JSONBAgg("integer_field", default=Value("<empty>")) ), @ignore_warnings(category=RemovedInDjango51Warning) def test_jsonb_agg_default_encoded_json_string(self): AggregateTestModel.objects.all().delete() queryset = AggregateTestModel.objects.all() self.assertEqual( queryset.aggregate( aggregation=JSONBAgg("integer_field", default=Value("[]")) ), {"aggregation": []}, ) def test_jsonb_agg_default_encoded_json_string_deprecation(self): queryset = AggregateTestModel.objects.all() msg = ( "Passing an encoded JSON string as JSONBAgg(default) is deprecated. Pass " "default=[] instead." ) with self.assertWarnsMessage(RemovedInDjango51Warning, msg): queryset.aggregate( aggregation=JSONBAgg("integer_field", default=Value("[]")) ) with self.assertWarnsMessage(RemovedInDjango51Warning, msg): queryset.none().aggregate( aggregation=JSONBAgg("integer_field", default=Value("[]")) ) def test_array_agg_charfield(self): values = AggregateTestModel.objects.aggregate(arrayagg=ArrayAgg("char_field")) self.assertEqual(values, {"arrayagg": ["Foo1", "Foo2", "Foo4", "Foo3"]}) def test_array_agg_charfield_ordering(self): ordering_test_cases = ( (F("char_field").desc(), ["Foo4", "Foo3", "Foo2", "Foo1"]), (F("char_field").asc(), ["Foo1", "Foo2", "Foo3", "Foo4"]), (F("char_field"), ["Foo1", "Foo2", "Foo3", "Foo4"]), ( [F("boolean_field"), F("char_field").desc()], ["Foo4", "Foo2", "Foo3", "Foo1"], ), ( (F("boolean_field"), F("char_field").desc()), ["Foo4", "Foo2", "Foo3", "Foo1"], ), ("char_field", ["Foo1", "Foo2", "Foo3", "Foo4"]), ("-char_field", ["Foo4", "Foo3", "Foo2", "Foo1"]), (Concat("char_field", Value("@")), ["Foo1", "Foo2", "Foo3", "Foo4"]), (Concat("char_field", Value("@")).desc(), ["Foo4", "Foo3", "Foo2", "Foo1"]), ( ( Substr("char_field", 1, 1), F("integer_field"), Substr("char_field", 4, 1).desc(), ), ["Foo3", "Foo1", "Foo2", "Foo4"], ), ) for ordering, expected_output in ordering_test_cases: with self.subTest(ordering=ordering, expected_output=expected_output): values = AggregateTestModel.objects.aggregate( arrayagg=ArrayAgg("char_field", ordering=ordering) ) self.assertEqual(values, {"arrayagg": expected_output}) def test_array_agg_integerfield(self): values = AggregateTestModel.objects.aggregate( arrayagg=ArrayAgg("integer_field") ) self.assertEqual(values, {"arrayagg": [0, 1, 2, 0]}) def test_array_agg_integerfield_ordering(self): values = AggregateTestModel.objects.aggregate( arrayagg=ArrayAgg("integer_field", ordering=F("integer_field").desc()) ) self.assertEqual(values, {"arrayagg": [2, 1, 0, 0]}) def test_array_agg_booleanfield(self): values = AggregateTestModel.objects.aggregate( arrayagg=ArrayAgg("boolean_field") ) self.assertEqual(values, {"arrayagg": [True, False, False, True]}) def test_array_agg_booleanfield_ordering(self): ordering_test_cases = ( (F("boolean_field").asc(), [False, False, True, True]), (F("boolean_field").desc(), [True, True, False, False]), (F("boolean_field"), [False, False, True, True]), ) for ordering, expected_output in ordering_test_cases: with self.subTest(ordering=ordering, expected_output=expected_output): values = AggregateTestModel.objects.aggregate( arrayagg=ArrayAgg("boolean_field", ordering=ordering) ) self.assertEqual(values, {"arrayagg": expected_output}) def test_array_agg_jsonfield(self): values = AggregateTestModel.objects.aggregate( arrayagg=ArrayAgg( KeyTransform("lang", "json_field"), filter=Q(json_field__lang__isnull=False), ), ) self.assertEqual(values, {"arrayagg": ["pl", "en"]}) def test_array_agg_jsonfield_ordering(self): values = AggregateTestModel.objects.aggregate( arrayagg=ArrayAgg( KeyTransform("lang", "json_field"), filter=Q(json_field__lang__isnull=False), ordering=KeyTransform("lang", "json_field"), ), ) self.assertEqual(values, {"arrayagg": ["en", "pl"]}) def test_array_agg_filter(self): values = AggregateTestModel.objects.aggregate( arrayagg=ArrayAgg("integer_field", filter=Q(integer_field__gt=0)), ) self.assertEqual(values, {"arrayagg": [1, 2]}) def test_array_agg_lookups(self): aggr1 = AggregateTestModel.objects.create() aggr2 = AggregateTestModel.objects.create() StatTestModel.objects.create(related_field=aggr1, int1=1, int2=0) StatTestModel.objects.create(related_field=aggr1, int1=2, int2=0) StatTestModel.objects.create(related_field=aggr2, int1=3, int2=0) StatTestModel.objects.create(related_field=aggr2, int1=4, int2=0) qs = ( StatTestModel.objects.values("related_field") .annotate(array=ArrayAgg("int1")) .filter(array__overlap=[2]) .values_list("array", flat=True) ) self.assertCountEqual(qs.get(), [1, 2]) def test_array_agg_filter_index(self): aggr1 = AggregateTestModel.objects.create(integer_field=1) aggr2 = AggregateTestModel.objects.create(integer_field=2) StatTestModel.objects.bulk_create( [ StatTestModel(related_field=aggr1, int1=1, int2=0), StatTestModel(related_field=aggr1, int1=2, int2=1), StatTestModel(related_field=aggr2, int1=3, int2=0), StatTestModel(related_field=aggr2, int1=4, int2=1), ] ) qs = ( AggregateTestModel.objects.filter(pk__in=[aggr1.pk, aggr2.pk]) .annotate( array=ArrayAgg("stattestmodel__int1", filter=Q(stattestmodel__int2=0)) ) .annotate(array_value=F("array__0")) .values_list("array_value", flat=True) ) self.assertCountEqual(qs, [1, 3]) def test_array_agg_filter_slice(self): aggr1 = AggregateTestModel.objects.create(integer_field=1) aggr2 = AggregateTestModel.objects.create(integer_field=2) StatTestModel.objects.bulk_create( [ StatTestModel(related_field=aggr1, int1=1, int2=0), StatTestModel(related_field=aggr1, int1=2, int2=1), StatTestModel(related_field=aggr2, int1=3, int2=0), StatTestModel(related_field=aggr2, int1=4, int2=1), StatTestModel(related_field=aggr2, int1=5, int2=0), ] ) qs = ( AggregateTestModel.objects.filter(pk__in=[aggr1.pk, aggr2.pk]) .annotate( array=ArrayAgg("stattestmodel__int1", filter=Q(stattestmodel__int2=0)) ) .annotate(array_value=F("array__1_2")) .values_list("array_value", flat=True) ) self.assertCountEqual(qs, [[], [5]]) def test_bit_and_general(self): values = AggregateTestModel.objects.filter(integer_field__in=[0, 1]).aggregate( bitand=BitAnd("integer_field") ) self.assertEqual(values, {"bitand": 0}) def test_bit_and_on_only_true_values(self): values = AggregateTestModel.objects.filter(integer_field=1).aggregate( bitand=BitAnd("integer_field") ) self.assertEqual(values, {"bitand": 1}) def test_bit_and_on_only_false_values(self): values = AggregateTestModel.objects.filter(integer_field=0).aggregate( bitand=BitAnd("integer_field") ) self.assertEqual(values, {"bitand": 0}) def test_bit_or_general(self): values = AggregateTestModel.objects.filter(integer_field__in=[0, 1]).aggregate( bitor=BitOr("integer_field") ) self.assertEqual(values, {"bitor": 1}) def test_bit_or_on_only_true_values(self): values = AggregateTestModel.objects.filter(integer_field=1).aggregate( bitor=BitOr("integer_field") ) self.assertEqual(values, {"bitor": 1}) def test_bit_or_on_only_false_values(self): values = AggregateTestModel.objects.filter(integer_field=0).aggregate( bitor=BitOr("integer_field") ) self.assertEqual(values, {"bitor": 0}) @skipUnlessDBFeature("has_bit_xor") def test_bit_xor_general(self): AggregateTestModel.objects.create(integer_field=3) values = AggregateTestModel.objects.filter( integer_field__in=[1, 3], ).aggregate(bitxor=BitXor("integer_field")) self.assertEqual(values, {"bitxor": 2}) @skipUnlessDBFeature("has_bit_xor") def test_bit_xor_on_only_true_values(self): values = AggregateTestModel.objects.filter( integer_field=1, ).aggregate(bitxor=BitXor("integer_field")) self.assertEqual(values, {"bitxor": 1}) @skipUnlessDBFeature("has_bit_xor") def test_bit_xor_on_only_false_values(self): values = AggregateTestModel.objects.filter( integer_field=0, ).aggregate(bitxor=BitXor("integer_field")) self.assertEqual(values, {"bitxor": 0}) def test_bool_and_general(self): values = AggregateTestModel.objects.aggregate(booland=BoolAnd("boolean_field")) self.assertEqual(values, {"booland": False}) def test_bool_and_q_object(self): values = AggregateTestModel.objects.aggregate( booland=BoolAnd(Q(integer_field__gt=2)), ) self.assertEqual(values, {"booland": False}) def test_bool_or_general(self): values = AggregateTestModel.objects.aggregate(boolor=BoolOr("boolean_field")) self.assertEqual(values, {"boolor": True}) def test_bool_or_q_object(self): values = AggregateTestModel.objects.aggregate( boolor=BoolOr(Q(integer_field__gt=2)), ) self.assertEqual(values, {"boolor": False}) def test_string_agg_requires_delimiter(self): with self.assertRaises(TypeError): AggregateTestModel.objects.aggregate(stringagg=StringAgg("char_field")) def test_string_agg_delimiter_escaping(self): values = AggregateTestModel.objects.aggregate( stringagg=StringAgg("char_field", delimiter="'") ) self.assertEqual(values, {"stringagg": "Foo1'Foo2'Foo4'Foo3"}) def test_string_agg_charfield(self): values = AggregateTestModel.objects.aggregate( stringagg=StringAgg("char_field", delimiter=";") ) self.assertEqual(values, {"stringagg": "Foo1;Foo2;Foo4;Foo3"}) def test_string_agg_default_output_field(self): values = AggregateTestModel.objects.aggregate( stringagg=StringAgg("text_field", delimiter=";"), ) self.assertEqual(values, {"stringagg": "Text1;Text2;Text4;Text3"}) def test_string_agg_charfield_ordering(self): ordering_test_cases = ( (F("char_field").desc(), "Foo4;Foo3;Foo2;Foo1"), (F("char_field").asc(), "Foo1;Foo2;Foo3;Foo4"), (F("char_field"), "Foo1;Foo2;Foo3;Foo4"), ("char_field", "Foo1;Foo2;Foo3;Foo4"), ("-char_field", "Foo4;Foo3;Foo2;Foo1"), (Concat("char_field", Value("@")), "Foo1;Foo2;Foo3;Foo4"), (Concat("char_field", Value("@")).desc(), "Foo4;Foo3;Foo2;Foo1"), ) for ordering, expected_output in ordering_test_cases: with self.subTest(ordering=ordering, expected_output=expected_output): values = AggregateTestModel.objects.aggregate( stringagg=StringAgg("char_field", delimiter=";", ordering=ordering) ) self.assertEqual(values, {"stringagg": expected_output}) def test_string_agg_jsonfield_ordering(self): values = AggregateTestModel.objects.aggregate( stringagg=StringAgg( KeyTextTransform("lang", "json_field"), delimiter=";", ordering=KeyTextTransform("lang", "json_field"), output_field=CharField(), ), ) self.assertEqual(values, {"stringagg": "en;pl"}) def test_string_agg_filter(self): values = AggregateTestModel.objects.aggregate( stringagg=StringAgg( "char_field", delimiter=";", filter=Q(char_field__endswith="3") | Q(char_field__endswith="1"), ) ) self.assertEqual(values, {"stringagg": "Foo1;Foo3"}) def test_orderable_agg_alternative_fields(self): values = AggregateTestModel.objects.aggregate( arrayagg=ArrayAgg("integer_field", ordering=F("char_field").asc()) ) self.assertEqual(values, {"arrayagg": [0, 1, 0, 2]}) def test_jsonb_agg(self): values = AggregateTestModel.objects.aggregate(jsonbagg=JSONBAgg("char_field")) self.assertEqual(values, {"jsonbagg": ["Foo1", "Foo2", "Foo4", "Foo3"]}) def test_jsonb_agg_charfield_ordering(self): ordering_test_cases = ( (F("char_field").desc(), ["Foo4", "Foo3", "Foo2", "Foo1"]), (F("char_field").asc(), ["Foo1", "Foo2", "Foo3", "Foo4"]), (F("char_field"), ["Foo1", "Foo2", "Foo3", "Foo4"]), ("char_field", ["Foo1", "Foo2", "Foo3", "Foo4"]), ("-char_field", ["Foo4", "Foo3", "Foo2", "Foo1"]), (Concat("char_field", Value("@")), ["Foo1", "Foo2", "Foo3", "Foo4"]), (Concat("char_field", Value("@")).desc(), ["Foo4", "Foo3", "Foo2", "Foo1"]), ) for ordering, expected_output in ordering_test_cases: with self.subTest(ordering=ordering, expected_output=expected_output): values = AggregateTestModel.objects.aggregate( jsonbagg=JSONBAgg("char_field", ordering=ordering), ) self.assertEqual(values, {"jsonbagg": expected_output}) def test_jsonb_agg_integerfield_ordering(self): values = AggregateTestModel.objects.aggregate( jsonbagg=JSONBAgg("integer_field", ordering=F("integer_field").desc()), ) self.assertEqual(values, {"jsonbagg": [2, 1, 0, 0]}) def test_jsonb_agg_booleanfield_ordering(self): ordering_test_cases = ( (F("boolean_field").asc(), [False, False, True, True]), (F("boolean_field").desc(), [True, True, False, False]), (F("boolean_field"), [False, False, True, True]), ) for ordering, expected_output in ordering_test_cases: with self.subTest(ordering=ordering, expected_output=expected_output): values = AggregateTestModel.objects.aggregate( jsonbagg=JSONBAgg("boolean_field", ordering=ordering), ) self.assertEqual(values, {"jsonbagg": expected_output}) def test_jsonb_agg_jsonfield_ordering(self): values = AggregateTestModel.objects.aggregate( jsonbagg=JSONBAgg( KeyTransform("lang", "json_field"), filter=Q(json_field__lang__isnull=False), ordering=KeyTransform("lang", "json_field"), ), ) self.assertEqual(values, {"jsonbagg": ["en", "pl"]}) def test_jsonb_agg_key_index_transforms(self): room101 = Room.objects.create(number=101) room102 = Room.objects.create(number=102) datetimes = [ timezone.datetime(2018, 6, 20), timezone.datetime(2018, 6, 24), timezone.datetime(2018, 6, 28), ] HotelReservation.objects.create( datespan=(datetimes[0].date(), datetimes[1].date()), start=datetimes[0], end=datetimes[1], room=room102, requirements={"double_bed": True, "parking": True}, ) HotelReservation.objects.create( datespan=(datetimes[1].date(), datetimes[2].date()), start=datetimes[1], end=datetimes[2], room=room102, requirements={"double_bed": False, "sea_view": True, "parking": False}, ) HotelReservation.objects.create( datespan=(datetimes[0].date(), datetimes[2].date()), start=datetimes[0], end=datetimes[2], room=room101, requirements={"sea_view": False}, ) values = ( Room.objects.annotate( requirements=JSONBAgg( "hotelreservation__requirements", ordering="-hotelreservation__start", ) ) .filter(requirements__0__sea_view=True) .values("number", "requirements") ) self.assertSequenceEqual( values, [ { "number": 102, "requirements": [ {"double_bed": False, "sea_view": True, "parking": False}, {"double_bed": True, "parking": True}, ], }, ], ) def test_string_agg_array_agg_ordering_in_subquery(self): stats = [] for i, agg in enumerate(AggregateTestModel.objects.order_by("char_field")): stats.append(StatTestModel(related_field=agg, int1=i, int2=i + 1)) stats.append(StatTestModel(related_field=agg, int1=i + 1, int2=i)) StatTestModel.objects.bulk_create(stats) for aggregate, expected_result in ( ( ArrayAgg("stattestmodel__int1", ordering="-stattestmodel__int2"), [ ("Foo1", [0, 1]), ("Foo2", [1, 2]), ("Foo3", [2, 3]), ("Foo4", [3, 4]), ], ), ( StringAgg( Cast("stattestmodel__int1", CharField()), delimiter=";", ordering="-stattestmodel__int2", ), [("Foo1", "0;1"), ("Foo2", "1;2"), ("Foo3", "2;3"), ("Foo4", "3;4")], ), ): with self.subTest(aggregate=aggregate.__class__.__name__): subquery = ( AggregateTestModel.objects.filter( pk=OuterRef("pk"), ) .annotate(agg=aggregate) .values("agg") ) values = ( AggregateTestModel.objects.annotate( agg=Subquery(subquery), ) .order_by("char_field") .values_list("char_field", "agg") ) self.assertEqual(list(values), expected_result) def test_string_agg_array_agg_filter_in_subquery(self): StatTestModel.objects.bulk_create( [ StatTestModel(related_field=self.aggs[0], int1=0, int2=5), StatTestModel(related_field=self.aggs[0], int1=1, int2=4), StatTestModel(related_field=self.aggs[0], int1=2, int2=3), ] ) for aggregate, expected_result in ( ( ArrayAgg("stattestmodel__int1", filter=Q(stattestmodel__int2__gt=3)), [("Foo1", [0, 1]), ("Foo2", None)], ), ( StringAgg( Cast("stattestmodel__int2", CharField()), delimiter=";", filter=Q(stattestmodel__int1__lt=2), ), [("Foo1", "5;4"), ("Foo2", None)], ), ): with self.subTest(aggregate=aggregate.__class__.__name__): subquery = ( AggregateTestModel.objects.filter( pk=OuterRef("pk"), ) .annotate(agg=aggregate) .values("agg") ) values = ( AggregateTestModel.objects.annotate( agg=Subquery(subquery), ) .filter( char_field__in=["Foo1", "Foo2"], ) .order_by("char_field") .values_list("char_field", "agg") ) self.assertEqual(list(values), expected_result) def test_string_agg_filter_in_subquery_with_exclude(self): subquery = ( AggregateTestModel.objects.annotate( stringagg=StringAgg( "char_field", delimiter=";", filter=Q(char_field__endswith="1"), ) ) .exclude(stringagg="") .values("id") ) self.assertSequenceEqual( AggregateTestModel.objects.filter(id__in=Subquery(subquery)), [self.aggs[0]], ) def test_ordering_isnt_cleared_for_array_subquery(self): inner_qs = AggregateTestModel.objects.order_by("-integer_field") qs = AggregateTestModel.objects.annotate( integers=Func( Subquery(inner_qs.values("integer_field")), function="ARRAY", output_field=ArrayField(base_field=IntegerField()), ), ) self.assertSequenceEqual( qs.first().integers, inner_qs.values_list("integer_field", flat=True), ) def test_window(self): self.assertCountEqual( AggregateTestModel.objects.annotate( integers=Window( expression=ArrayAgg("char_field"), partition_by=F("integer_field"), ) ).values("integers", "char_field"), [ {"integers": ["Foo1", "Foo3"], "char_field": "Foo1"}, {"integers": ["Foo1", "Foo3"], "char_field": "Foo3"}, {"integers": ["Foo2"], "char_field": "Foo2"}, {"integers": ["Foo4"], "char_field": "Foo4"}, ], ) def test_values_list(self): tests = [ArrayAgg("integer_field"), JSONBAgg("integer_field")] for aggregation in tests: with self.subTest(aggregation=aggregation): self.assertCountEqual( AggregateTestModel.objects.values_list(aggregation), [([0],), ([1],), ([2],), ([0],)], ) class TestAggregateDistinct(PostgreSQLTestCase): @classmethod def setUpTestData(cls): AggregateTestModel.objects.create(char_field="Foo") AggregateTestModel.objects.create(char_field="Foo") AggregateTestModel.objects.create(char_field="Bar") def test_string_agg_distinct_false(self): values = AggregateTestModel.objects.aggregate( stringagg=StringAgg("char_field", delimiter=" ", distinct=False) ) self.assertEqual(values["stringagg"].count("Foo"), 2) self.assertEqual(values["stringagg"].count("Bar"), 1) def test_string_agg_distinct_true(self): values = AggregateTestModel.objects.aggregate( stringagg=StringAgg("char_field", delimiter=" ", distinct=True) ) self.assertEqual(values["stringagg"].count("Foo"), 1) self.assertEqual(values["stringagg"].count("Bar"), 1) def test_array_agg_distinct_false(self): values = AggregateTestModel.objects.aggregate( arrayagg=ArrayAgg("char_field", distinct=False) ) self.assertEqual(sorted(values["arrayagg"]), ["Bar", "Foo", "Foo"]) def test_array_agg_distinct_true(self): values = AggregateTestModel.objects.aggregate( arrayagg=ArrayAgg("char_field", distinct=True) ) self.assertEqual(sorted(values["arrayagg"]), ["Bar", "Foo"]) def test_jsonb_agg_distinct_false(self): values = AggregateTestModel.objects.aggregate( jsonbagg=JSONBAgg("char_field", distinct=False), ) self.assertEqual(sorted(values["jsonbagg"]), ["Bar", "Foo", "Foo"]) def test_jsonb_agg_distinct_true(self): values = AggregateTestModel.objects.aggregate( jsonbagg=JSONBAgg("char_field", distinct=True), ) self.assertEqual(sorted(values["jsonbagg"]), ["Bar", "Foo"]) class TestStatisticsAggregate(PostgreSQLTestCase): @classmethod def setUpTestData(cls): StatTestModel.objects.create( int1=1, int2=3, related_field=AggregateTestModel.objects.create(integer_field=0), ) StatTestModel.objects.create( int1=2, int2=2, related_field=AggregateTestModel.objects.create(integer_field=1), ) StatTestModel.objects.create( int1=3, int2=1, related_field=AggregateTestModel.objects.create(integer_field=2), ) # Tests for base class (StatAggregate) def test_missing_arguments_raises_exception(self): with self.assertRaisesMessage(ValueError, "Both y and x must be provided."): StatAggregate(x=None, y=None) def test_correct_source_expressions(self): func = StatAggregate(x="test", y=13) self.assertIsInstance(func.source_expressions[0], Value) self.assertIsInstance(func.source_expressions[1], F) def test_alias_is_required(self): class SomeFunc(StatAggregate): function = "TEST" with self.assertRaisesMessage(TypeError, "Complex aggregates require an alias"): StatTestModel.objects.aggregate(SomeFunc(y="int2", x="int1")) # Test aggregates def test_empty_result_set(self): StatTestModel.objects.all().delete() tests = [ (Corr(y="int2", x="int1"), None), (CovarPop(y="int2", x="int1"), None), (CovarPop(y="int2", x="int1", sample=True), None), (RegrAvgX(y="int2", x="int1"), None), (RegrAvgY(y="int2", x="int1"), None), (RegrCount(y="int2", x="int1"), 0), (RegrIntercept(y="int2", x="int1"), None), (RegrR2(y="int2", x="int1"), None), (RegrSlope(y="int2", x="int1"), None), (RegrSXX(y="int2", x="int1"), None), (RegrSXY(y="int2", x="int1"), None), (RegrSYY(y="int2", x="int1"), None), ] for aggregation, expected_result in tests: with self.subTest(aggregation=aggregation): # Empty result with non-execution optimization. with self.assertNumQueries(0): values = StatTestModel.objects.none().aggregate( aggregation=aggregation, ) self.assertEqual(values, {"aggregation": expected_result}) # Empty result when query must be executed. with self.assertNumQueries(1): values = StatTestModel.objects.aggregate( aggregation=aggregation, ) self.assertEqual(values, {"aggregation": expected_result}) def test_default_argument(self): StatTestModel.objects.all().delete() tests = [ (Corr(y="int2", x="int1", default=0), 0), (CovarPop(y="int2", x="int1", default=0), 0), (CovarPop(y="int2", x="int1", sample=True, default=0), 0), (RegrAvgX(y="int2", x="int1", default=0), 0), (RegrAvgY(y="int2", x="int1", default=0), 0), # RegrCount() doesn't support the default argument. (RegrIntercept(y="int2", x="int1", default=0), 0), (RegrR2(y="int2", x="int1", default=0), 0), (RegrSlope(y="int2", x="int1", default=0), 0), (RegrSXX(y="int2", x="int1", default=0), 0), (RegrSXY(y="int2", x="int1", default=0), 0), (RegrSYY(y="int2", x="int1", default=0), 0), ] for aggregation, expected_result in tests: with self.subTest(aggregation=aggregation): # Empty result with non-execution optimization. with self.assertNumQueries(0): values = StatTestModel.objects.none().aggregate( aggregation=aggregation, ) self.assertEqual(values, {"aggregation": expected_result}) # Empty result when query must be executed. with self.assertNumQueries(1): values = StatTestModel.objects.aggregate( aggregation=aggregation, ) self.assertEqual(values, {"aggregation": expected_result}) def test_corr_general(self): values = StatTestModel.objects.aggregate(corr=Corr(y="int2", x="int1")) self.assertEqual(values, {"corr": -1.0}) def test_covar_pop_general(self): values = StatTestModel.objects.aggregate(covarpop=CovarPop(y="int2", x="int1")) self.assertEqual(values, {"covarpop": Approximate(-0.66, places=1)}) def test_covar_pop_sample(self): values = StatTestModel.objects.aggregate( covarpop=CovarPop(y="int2", x="int1", sample=True) ) self.assertEqual(values, {"covarpop": -1.0}) def test_regr_avgx_general(self): values = StatTestModel.objects.aggregate(regravgx=RegrAvgX(y="int2", x="int1")) self.assertEqual(values, {"regravgx": 2.0}) def test_regr_avgy_general(self): values = StatTestModel.objects.aggregate(regravgy=RegrAvgY(y="int2", x="int1")) self.assertEqual(values, {"regravgy": 2.0}) def test_regr_count_general(self): values = StatTestModel.objects.aggregate( regrcount=RegrCount(y="int2", x="int1") ) self.assertEqual(values, {"regrcount": 3}) def test_regr_count_default(self): msg = "RegrCount does not allow default." with self.assertRaisesMessage(TypeError, msg): RegrCount(y="int2", x="int1", default=0) def test_regr_intercept_general(self): values = StatTestModel.objects.aggregate( regrintercept=RegrIntercept(y="int2", x="int1") ) self.assertEqual(values, {"regrintercept": 4}) def test_regr_r2_general(self): values = StatTestModel.objects.aggregate(regrr2=RegrR2(y="int2", x="int1")) self.assertEqual(values, {"regrr2": 1}) def test_regr_slope_general(self): values = StatTestModel.objects.aggregate( regrslope=RegrSlope(y="int2", x="int1") ) self.assertEqual(values, {"regrslope": -1}) def test_regr_sxx_general(self): values = StatTestModel.objects.aggregate(regrsxx=RegrSXX(y="int2", x="int1")) self.assertEqual(values, {"regrsxx": 2.0}) def test_regr_sxy_general(self): values = StatTestModel.objects.aggregate(regrsxy=RegrSXY(y="int2", x="int1")) self.assertEqual(values, {"regrsxy": -2.0}) def test_regr_syy_general(self): values = StatTestModel.objects.aggregate(regrsyy=RegrSYY(y="int2", x="int1")) self.assertEqual(values, {"regrsyy": 2.0}) def test_regr_avgx_with_related_obj_and_number_as_argument(self): """ This is more complex test to check if JOIN on field and number as argument works as expected. """ values = StatTestModel.objects.aggregate( complex_regravgx=RegrAvgX(y=5, x="related_field__integer_field") ) self.assertEqual(values, {"complex_regravgx": 1.0})
981824abc9c7f758d4d97c9e8c95b4df0311f0bfe134da984798d7a0307699d0
import unittest from decimal import Decimal from django.db import connection from django.db.backends.signals import connection_created from django.db.migrations.writer import MigrationWriter from django.test import TestCase from django.test.utils import modify_settings try: from django.contrib.postgres.fields import ( DateRangeField, DateTimeRangeField, DecimalRangeField, IntegerRangeField, ) from django.db.backends.postgresql.psycopg_any import ( DateRange, DateTimeRange, DateTimeTZRange, NumericRange, is_psycopg3, ) except ImportError: pass @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests") class PostgresConfigTests(TestCase): def test_register_type_handlers_connection(self): from django.contrib.postgres.signals import register_type_handlers self.assertNotIn( register_type_handlers, connection_created._live_receivers(None)[0] ) with modify_settings(INSTALLED_APPS={"append": "django.contrib.postgres"}): self.assertIn( register_type_handlers, connection_created._live_receivers(None)[0] ) self.assertNotIn( register_type_handlers, connection_created._live_receivers(None)[0] ) def test_register_serializer_for_migrations(self): tests = ( (DateRange(empty=True), DateRangeField), (DateTimeRange(empty=True), DateRangeField), (DateTimeTZRange(None, None, "[]"), DateTimeRangeField), (NumericRange(Decimal("1.0"), Decimal("5.0"), "()"), DecimalRangeField), (NumericRange(1, 10), IntegerRangeField), ) def assertNotSerializable(): for default, test_field in tests: with self.subTest(default=default): field = test_field(default=default) with self.assertRaisesMessage( ValueError, "Cannot serialize: %s" % default.__class__.__name__ ): MigrationWriter.serialize(field) assertNotSerializable() import_name = "psycopg.types.range" if is_psycopg3 else "psycopg2.extras" with self.modify_settings(INSTALLED_APPS={"append": "django.contrib.postgres"}): for default, test_field in tests: with self.subTest(default=default): field = test_field(default=default) serialized_field, imports = MigrationWriter.serialize(field) self.assertEqual( imports, { "import django.contrib.postgres.fields.ranges", f"import {import_name}", }, ) self.assertIn( f"{field.__module__}.{field.__class__.__name__}" f"(default={import_name}.{default!r})", serialized_field, ) assertNotSerializable()
50692b317b4476334fe2a3edd91b344bbf6feb83f0e7f10efe610a285343cf0f
import re from io import StringIO from unittest import mock, skipUnless from django.core.management import call_command from django.db import connection from django.db.backends.base.introspection import TableInfo from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature from .models import PeopleMoreData, test_collation def inspectdb_tables_only(table_name): """ Limit introspection to tables created for models of this app. Some databases such as Oracle are extremely slow at introspection. """ return table_name.startswith("inspectdb_") def inspectdb_views_only(table_name): return table_name.startswith("inspectdb_") and table_name.endswith( ("_materialized", "_view") ) def special_table_only(table_name): return table_name.startswith("inspectdb_special") class InspectDBTestCase(TestCase): unique_re = re.compile(r".*unique_together = \((.+),\).*") def test_stealth_table_name_filter_option(self): out = StringIO() call_command("inspectdb", table_name_filter=inspectdb_tables_only, stdout=out) error_message = ( "inspectdb has examined a table that should have been filtered out." ) # contrib.contenttypes is one of the apps always installed when running # the Django test suite, check that one of its tables hasn't been # inspected self.assertNotIn( "class DjangoContentType(models.Model):", out.getvalue(), msg=error_message ) def test_table_option(self): """ inspectdb can inspect a subset of tables by passing the table names as arguments. """ out = StringIO() call_command("inspectdb", "inspectdb_people", stdout=out) output = out.getvalue() self.assertIn("class InspectdbPeople(models.Model):", output) self.assertNotIn("InspectdbPeopledata", output) def make_field_type_asserter(self): """ Call inspectdb and return a function to validate a field type in its output. """ out = StringIO() call_command("inspectdb", "inspectdb_columntypes", stdout=out) output = out.getvalue() def assertFieldType(name, definition): out_def = re.search(r"^\s*%s = (models.*)$" % name, output, re.MULTILINE)[1] self.assertEqual(definition, out_def) return assertFieldType def test_field_types(self): """Test introspection of various Django field types""" assertFieldType = self.make_field_type_asserter() introspected_field_types = connection.features.introspected_field_types char_field_type = introspected_field_types["CharField"] # Inspecting Oracle DB doesn't produce correct results (#19884): # - it reports fields as blank=True when they aren't. if ( not connection.features.interprets_empty_strings_as_nulls and char_field_type == "CharField" ): assertFieldType("char_field", "models.CharField(max_length=10)") assertFieldType( "null_char_field", "models.CharField(max_length=10, blank=True, null=True)", ) assertFieldType("email_field", "models.CharField(max_length=254)") assertFieldType("file_field", "models.CharField(max_length=100)") assertFieldType("file_path_field", "models.CharField(max_length=100)") assertFieldType("slug_field", "models.CharField(max_length=50)") assertFieldType("text_field", "models.TextField()") assertFieldType("url_field", "models.CharField(max_length=200)") if char_field_type == "TextField": assertFieldType("char_field", "models.TextField()") assertFieldType( "null_char_field", "models.TextField(blank=True, null=True)" ) assertFieldType("email_field", "models.TextField()") assertFieldType("file_field", "models.TextField()") assertFieldType("file_path_field", "models.TextField()") assertFieldType("slug_field", "models.TextField()") assertFieldType("text_field", "models.TextField()") assertFieldType("url_field", "models.TextField()") assertFieldType("date_field", "models.DateField()") assertFieldType("date_time_field", "models.DateTimeField()") if introspected_field_types["GenericIPAddressField"] == "GenericIPAddressField": assertFieldType("gen_ip_address_field", "models.GenericIPAddressField()") elif not connection.features.interprets_empty_strings_as_nulls: assertFieldType("gen_ip_address_field", "models.CharField(max_length=39)") assertFieldType( "time_field", "models.%s()" % introspected_field_types["TimeField"] ) if connection.features.has_native_uuid_field: assertFieldType("uuid_field", "models.UUIDField()") elif not connection.features.interprets_empty_strings_as_nulls: assertFieldType("uuid_field", "models.CharField(max_length=32)") @skipUnlessDBFeature("can_introspect_json_field", "supports_json_field") def test_json_field(self): out = StringIO() call_command("inspectdb", "inspectdb_jsonfieldcolumntype", stdout=out) output = out.getvalue() if not connection.features.interprets_empty_strings_as_nulls: self.assertIn("json_field = models.JSONField()", output) self.assertIn( "null_json_field = models.JSONField(blank=True, null=True)", output ) @skipUnlessDBFeature("supports_comments") def test_db_comments(self): out = StringIO() call_command("inspectdb", "inspectdb_dbcomment", stdout=out) output = out.getvalue() integer_field_type = connection.features.introspected_field_types[ "IntegerField" ] self.assertIn( f"rank = models.{integer_field_type}(" f"db_comment=\"'Rank' column comment\")", output, ) self.assertIn( " db_table_comment = 'Custom table comment'", output, ) @skipUnlessDBFeature("supports_collation_on_charfield") @skipUnless(test_collation, "Language collations are not supported.") def test_char_field_db_collation(self): out = StringIO() call_command("inspectdb", "inspectdb_charfielddbcollation", stdout=out) output = out.getvalue() if not connection.features.interprets_empty_strings_as_nulls: self.assertIn( "char_field = models.CharField(max_length=10, " "db_collation='%s')" % test_collation, output, ) else: self.assertIn( "char_field = models.CharField(max_length=10, " "db_collation='%s', blank=True, null=True)" % test_collation, output, ) @skipUnlessDBFeature("supports_collation_on_textfield") @skipUnless(test_collation, "Language collations are not supported.") def test_text_field_db_collation(self): out = StringIO() call_command("inspectdb", "inspectdb_textfielddbcollation", stdout=out) output = out.getvalue() if not connection.features.interprets_empty_strings_as_nulls: self.assertIn( "text_field = models.TextField(db_collation='%s')" % test_collation, output, ) else: self.assertIn( "text_field = models.TextField(db_collation='%s, blank=True, " "null=True)" % test_collation, output, ) @skipUnlessDBFeature("supports_unlimited_charfield") def test_char_field_unlimited(self): out = StringIO() call_command("inspectdb", "inspectdb_charfieldunlimited", stdout=out) output = out.getvalue() self.assertIn("char_field = models.CharField()", output) def test_number_field_types(self): """Test introspection of various Django field types""" assertFieldType = self.make_field_type_asserter() introspected_field_types = connection.features.introspected_field_types auto_field_type = connection.features.introspected_field_types["AutoField"] if auto_field_type != "AutoField": assertFieldType( "id", "models.%s(primary_key=True) # AutoField?" % auto_field_type ) assertFieldType( "big_int_field", "models.%s()" % introspected_field_types["BigIntegerField"] ) bool_field_type = introspected_field_types["BooleanField"] assertFieldType("bool_field", "models.{}()".format(bool_field_type)) assertFieldType( "null_bool_field", "models.{}(blank=True, null=True)".format(bool_field_type), ) if connection.vendor != "sqlite": assertFieldType( "decimal_field", "models.DecimalField(max_digits=6, decimal_places=1)" ) else: # Guessed arguments on SQLite, see #5014 assertFieldType( "decimal_field", "models.DecimalField(max_digits=10, decimal_places=5) " "# max_digits and decimal_places have been guessed, " "as this database handles decimal fields as float", ) assertFieldType("float_field", "models.FloatField()") assertFieldType( "int_field", "models.%s()" % introspected_field_types["IntegerField"] ) assertFieldType( "pos_int_field", "models.%s()" % introspected_field_types["PositiveIntegerField"], ) assertFieldType( "pos_big_int_field", "models.%s()" % introspected_field_types["PositiveBigIntegerField"], ) assertFieldType( "pos_small_int_field", "models.%s()" % introspected_field_types["PositiveSmallIntegerField"], ) assertFieldType( "small_int_field", "models.%s()" % introspected_field_types["SmallIntegerField"], ) @skipUnlessDBFeature("can_introspect_foreign_keys") def test_attribute_name_not_python_keyword(self): out = StringIO() call_command("inspectdb", table_name_filter=inspectdb_tables_only, stdout=out) output = out.getvalue() error_message = ( "inspectdb generated an attribute name which is a Python keyword" ) # Recursive foreign keys should be set to 'self' self.assertIn("parent = models.ForeignKey('self', models.DO_NOTHING)", output) self.assertNotIn( "from = models.ForeignKey(InspectdbPeople, models.DO_NOTHING)", output, msg=error_message, ) # As InspectdbPeople model is defined after InspectdbMessage, it should # be quoted. self.assertIn( "from_field = models.ForeignKey('InspectdbPeople', models.DO_NOTHING, " "db_column='from_id')", output, ) self.assertIn( "people_pk = models.OneToOneField(InspectdbPeople, models.DO_NOTHING, " "primary_key=True)", output, ) self.assertIn( "people_unique = models.OneToOneField(InspectdbPeople, models.DO_NOTHING)", output, ) @skipUnlessDBFeature("can_introspect_foreign_keys") def test_foreign_key_to_field(self): out = StringIO() call_command("inspectdb", "inspectdb_foreignkeytofield", stdout=out) self.assertIn( "to_field_fk = models.ForeignKey('InspectdbPeoplemoredata', " "models.DO_NOTHING, to_field='people_unique_id')", out.getvalue(), ) def test_digits_column_name_introspection(self): """Introspection of column names consist/start with digits (#16536/#17676)""" char_field_type = connection.features.introspected_field_types["CharField"] out = StringIO() call_command("inspectdb", "inspectdb_digitsincolumnname", stdout=out) output = out.getvalue() error_message = "inspectdb generated a model field name which is a number" self.assertNotIn( " 123 = models.%s" % char_field_type, output, msg=error_message ) self.assertIn("number_123 = models.%s" % char_field_type, output) error_message = ( "inspectdb generated a model field name which starts with a digit" ) self.assertNotIn( " 4extra = models.%s" % char_field_type, output, msg=error_message ) self.assertIn("number_4extra = models.%s" % char_field_type, output) self.assertNotIn( " 45extra = models.%s" % char_field_type, output, msg=error_message ) self.assertIn("number_45extra = models.%s" % char_field_type, output) def test_special_column_name_introspection(self): """ Introspection of column names containing special characters, unsuitable for Python identifiers """ out = StringIO() call_command("inspectdb", table_name_filter=special_table_only, stdout=out) output = out.getvalue() base_name = connection.introspection.identifier_converter("Field") integer_field_type = connection.features.introspected_field_types[ "IntegerField" ] self.assertIn("field = models.%s()" % integer_field_type, output) self.assertIn( "field_field = models.%s(db_column='%s_')" % (integer_field_type, base_name), output, ) self.assertIn( "field_field_0 = models.%s(db_column='%s__')" % (integer_field_type, base_name), output, ) self.assertIn( "field_field_1 = models.%s(db_column='__field')" % integer_field_type, output, ) self.assertIn( "prc_x = models.{}(db_column='prc(%) x')".format(integer_field_type), output ) self.assertIn("tamaño = models.%s()" % integer_field_type, output) def test_table_name_introspection(self): """ Introspection of table names containing special characters, unsuitable for Python identifiers """ out = StringIO() call_command("inspectdb", table_name_filter=special_table_only, stdout=out) output = out.getvalue() self.assertIn("class InspectdbSpecialTableName(models.Model):", output) @skipUnlessDBFeature("supports_expression_indexes") def test_table_with_func_unique_constraint(self): out = StringIO() call_command("inspectdb", "inspectdb_funcuniqueconstraint", stdout=out) output = out.getvalue() self.assertIn("class InspectdbFuncuniqueconstraint(models.Model):", output) def test_managed_models(self): """ By default the command generates models with `Meta.managed = False`. """ out = StringIO() call_command("inspectdb", "inspectdb_columntypes", stdout=out) output = out.getvalue() self.longMessage = False self.assertIn( " managed = False", output, msg="inspectdb should generate unmanaged models.", ) def test_unique_together_meta(self): out = StringIO() call_command("inspectdb", "inspectdb_uniquetogether", stdout=out) output = out.getvalue() self.assertIn(" unique_together = (('", output) unique_together_match = self.unique_re.findall(output) # There should be one unique_together tuple. self.assertEqual(len(unique_together_match), 1) fields = unique_together_match[0] # Fields with db_column = field name. self.assertIn("('field1', 'field2')", fields) # Fields from columns whose names are Python keywords. self.assertIn("('field1', 'field2')", fields) # Fields whose names normalize to the same Python field name and hence # are given an integer suffix. self.assertIn("('non_unique_column', 'non_unique_column_0')", fields) @skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL") def test_unsupported_unique_together(self): """Unsupported index types (COALESCE here) are skipped.""" with connection.cursor() as c: c.execute( "CREATE UNIQUE INDEX Findex ON %s " "(id, people_unique_id, COALESCE(message_id, -1))" % PeopleMoreData._meta.db_table ) try: out = StringIO() call_command( "inspectdb", table_name_filter=lambda tn: tn.startswith( PeopleMoreData._meta.db_table ), stdout=out, ) output = out.getvalue() self.assertIn("# A unique constraint could not be introspected.", output) self.assertEqual( self.unique_re.findall(output), ["('id', 'people_unique')"] ) finally: with connection.cursor() as c: c.execute("DROP INDEX Findex") @skipUnless( connection.vendor == "sqlite", "Only patched sqlite's DatabaseIntrospection.data_types_reverse for this test", ) def test_custom_fields(self): """ Introspection of columns with a custom field (#21090) """ out = StringIO() with mock.patch( "django.db.connection.introspection.data_types_reverse." "base_data_types_reverse", { "text": "myfields.TextField", "bigint": "BigIntegerField", }, ): call_command("inspectdb", "inspectdb_columntypes", stdout=out) output = out.getvalue() self.assertIn("text_field = myfields.TextField()", output) self.assertIn("big_int_field = models.BigIntegerField()", output) def test_introspection_errors(self): """ Introspection errors should not crash the command, and the error should be visible in the output. """ out = StringIO() with mock.patch( "django.db.connection.introspection.get_table_list", return_value=[TableInfo(name="nonexistent", type="t")], ): call_command("inspectdb", stdout=out) output = out.getvalue() self.assertIn("# Unable to inspect table 'nonexistent'", output) # The error message depends on the backend self.assertIn("# The error was:", output) def test_same_relations(self): out = StringIO() call_command("inspectdb", "inspectdb_message", stdout=out) self.assertIn( "author = models.ForeignKey('InspectdbPeople', models.DO_NOTHING, " "related_name='inspectdbmessage_author_set')", out.getvalue(), ) class InspectDBTransactionalTests(TransactionTestCase): available_apps = ["inspectdb"] def test_include_views(self): """inspectdb --include-views creates models for database views.""" with connection.cursor() as cursor: cursor.execute( "CREATE VIEW inspectdb_people_view AS " "SELECT id, name FROM inspectdb_people" ) out = StringIO() view_model = "class InspectdbPeopleView(models.Model):" view_managed = "managed = False # Created from a view." try: call_command( "inspectdb", table_name_filter=inspectdb_views_only, stdout=out, ) no_views_output = out.getvalue() self.assertNotIn(view_model, no_views_output) self.assertNotIn(view_managed, no_views_output) call_command( "inspectdb", table_name_filter=inspectdb_views_only, include_views=True, stdout=out, ) with_views_output = out.getvalue() self.assertIn(view_model, with_views_output) self.assertIn(view_managed, with_views_output) finally: with connection.cursor() as cursor: cursor.execute("DROP VIEW inspectdb_people_view") @skipUnlessDBFeature("can_introspect_materialized_views") def test_include_materialized_views(self): """inspectdb --include-views creates models for materialized views.""" with connection.cursor() as cursor: cursor.execute( "CREATE MATERIALIZED VIEW inspectdb_people_materialized AS " "SELECT id, name FROM inspectdb_people" ) out = StringIO() view_model = "class InspectdbPeopleMaterialized(models.Model):" view_managed = "managed = False # Created from a view." try: call_command( "inspectdb", table_name_filter=inspectdb_views_only, stdout=out, ) no_views_output = out.getvalue() self.assertNotIn(view_model, no_views_output) self.assertNotIn(view_managed, no_views_output) call_command( "inspectdb", table_name_filter=inspectdb_views_only, include_views=True, stdout=out, ) with_views_output = out.getvalue() self.assertIn(view_model, with_views_output) self.assertIn(view_managed, with_views_output) finally: with connection.cursor() as cursor: cursor.execute("DROP MATERIALIZED VIEW inspectdb_people_materialized") @skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL") def test_include_partitions(self): """inspectdb --include-partitions creates models for partitions.""" with connection.cursor() as cursor: cursor.execute( """\ CREATE TABLE inspectdb_partition_parent (name text not null) PARTITION BY LIST (left(upper(name), 1)) """ ) cursor.execute( """\ CREATE TABLE inspectdb_partition_child PARTITION OF inspectdb_partition_parent FOR VALUES IN ('A', 'B', 'C') """ ) out = StringIO() partition_model_parent = "class InspectdbPartitionParent(models.Model):" partition_model_child = "class InspectdbPartitionChild(models.Model):" partition_managed = "managed = False # Created from a partition." try: call_command( "inspectdb", table_name_filter=inspectdb_tables_only, stdout=out ) no_partitions_output = out.getvalue() self.assertIn(partition_model_parent, no_partitions_output) self.assertNotIn(partition_model_child, no_partitions_output) self.assertNotIn(partition_managed, no_partitions_output) call_command( "inspectdb", table_name_filter=inspectdb_tables_only, include_partitions=True, stdout=out, ) with_partitions_output = out.getvalue() self.assertIn(partition_model_parent, with_partitions_output) self.assertIn(partition_model_child, with_partitions_output) self.assertIn(partition_managed, with_partitions_output) finally: with connection.cursor() as cursor: cursor.execute("DROP TABLE IF EXISTS inspectdb_partition_child") cursor.execute("DROP TABLE IF EXISTS inspectdb_partition_parent") @skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL") def test_foreign_data_wrapper(self): with connection.cursor() as cursor: cursor.execute("CREATE EXTENSION IF NOT EXISTS file_fdw") cursor.execute( "CREATE SERVER inspectdb_server FOREIGN DATA WRAPPER file_fdw" ) cursor.execute( """ CREATE FOREIGN TABLE inspectdb_iris_foreign_table ( petal_length real, petal_width real, sepal_length real, sepal_width real ) SERVER inspectdb_server OPTIONS ( program 'echo 1,2,3,4', format 'csv' ) """ ) out = StringIO() foreign_table_model = "class InspectdbIrisForeignTable(models.Model):" foreign_table_managed = "managed = False" try: call_command( "inspectdb", table_name_filter=inspectdb_tables_only, stdout=out, ) output = out.getvalue() self.assertIn(foreign_table_model, output) self.assertIn(foreign_table_managed, output) finally: with connection.cursor() as cursor: cursor.execute( "DROP FOREIGN TABLE IF EXISTS inspectdb_iris_foreign_table" ) cursor.execute("DROP SERVER IF EXISTS inspectdb_server") cursor.execute("DROP EXTENSION IF EXISTS file_fdw") @skipUnlessDBFeature("create_test_table_with_composite_primary_key") def test_composite_primary_key(self): table_name = "test_table_composite_pk" with connection.cursor() as cursor: cursor.execute( connection.features.create_test_table_with_composite_primary_key ) out = StringIO() if connection.vendor == "sqlite": field_type = connection.features.introspected_field_types["AutoField"] else: field_type = connection.features.introspected_field_types["IntegerField"] try: call_command("inspectdb", table_name, stdout=out) output = out.getvalue() self.assertIn( f"column_1 = models.{field_type}(primary_key=True) # The composite " f"primary key (column_1, column_2) found, that is not supported. The " f"first column is selected.", output, ) self.assertIn( "column_2 = models.%s()" % connection.features.introspected_field_types["IntegerField"], output, ) finally: with connection.cursor() as cursor: cursor.execute("DROP TABLE %s" % table_name)
da23d31da23fdf7bb1620380f6096e3e7cc654ed113674a5b9b3f2e8d3143743
from unittest import mock from asgiref.sync import markcoroutinefunction from django import dispatch from django.apps.registry import Apps from django.db import models from django.db.models import signals from django.dispatch import receiver from django.test import SimpleTestCase, TestCase from django.test.utils import isolate_apps from .models import Author, Book, Car, Page, Person class BaseSignalSetup: def setUp(self): # Save up the number of connected signals so that we can check at the # end that all the signals we register get properly unregistered (#9989) self.pre_signals = ( len(signals.pre_save.receivers), len(signals.post_save.receivers), len(signals.pre_delete.receivers), len(signals.post_delete.receivers), ) def tearDown(self): # All our signals got disconnected properly. post_signals = ( len(signals.pre_save.receivers), len(signals.post_save.receivers), len(signals.pre_delete.receivers), len(signals.post_delete.receivers), ) self.assertEqual(self.pre_signals, post_signals) class SignalTests(BaseSignalSetup, TestCase): def test_model_pre_init_and_post_init(self): data = [] def pre_init_callback(sender, args, **kwargs): data.append(kwargs["kwargs"]) signals.pre_init.connect(pre_init_callback) def post_init_callback(sender, instance, **kwargs): data.append(instance) signals.post_init.connect(post_init_callback) p1 = Person(first_name="John", last_name="Doe") self.assertEqual(data, [{}, p1]) def test_save_signals(self): data = [] def pre_save_handler(signal, sender, instance, **kwargs): data.append((instance, sender, kwargs.get("raw", False))) def post_save_handler(signal, sender, instance, **kwargs): data.append( (instance, sender, kwargs.get("created"), kwargs.get("raw", False)) ) signals.pre_save.connect(pre_save_handler, weak=False) signals.post_save.connect(post_save_handler, weak=False) try: p1 = Person.objects.create(first_name="John", last_name="Smith") self.assertEqual( data, [ (p1, Person, False), (p1, Person, True, False), ], ) data[:] = [] p1.first_name = "Tom" p1.save() self.assertEqual( data, [ (p1, Person, False), (p1, Person, False, False), ], ) data[:] = [] # Calling an internal method purely so that we can trigger a "raw" save. p1.save_base(raw=True) self.assertEqual( data, [ (p1, Person, True), (p1, Person, False, True), ], ) data[:] = [] p2 = Person(first_name="James", last_name="Jones") p2.id = 99999 p2.save() self.assertEqual( data, [ (p2, Person, False), (p2, Person, True, False), ], ) data[:] = [] p2.id = 99998 p2.save() self.assertEqual( data, [ (p2, Person, False), (p2, Person, True, False), ], ) # The sender should stay the same when using defer(). data[:] = [] p3 = Person.objects.defer("first_name").get(pk=p1.pk) p3.last_name = "Reese" p3.save() self.assertEqual( data, [ (p3, Person, False), (p3, Person, False, False), ], ) finally: signals.pre_save.disconnect(pre_save_handler) signals.post_save.disconnect(post_save_handler) def test_delete_signals(self): data = [] def pre_delete_handler(signal, sender, instance, origin, **kwargs): data.append((instance, sender, instance.id is None, origin)) # #8285: signals can be any callable class PostDeleteHandler: def __init__(self, data): self.data = data def __call__(self, signal, sender, instance, origin, **kwargs): self.data.append((instance, sender, instance.id is None, origin)) post_delete_handler = PostDeleteHandler(data) signals.pre_delete.connect(pre_delete_handler, weak=False) signals.post_delete.connect(post_delete_handler, weak=False) try: p1 = Person.objects.create(first_name="John", last_name="Smith") p1.delete() self.assertEqual( data, [ (p1, Person, False, p1), (p1, Person, False, p1), ], ) data[:] = [] p2 = Person(first_name="James", last_name="Jones") p2.id = 99999 p2.save() p2.id = 99998 p2.save() p2.delete() self.assertEqual( data, [ (p2, Person, False, p2), (p2, Person, False, p2), ], ) data[:] = [] self.assertQuerySetEqual( Person.objects.all(), [ "James Jones", ], str, ) finally: signals.pre_delete.disconnect(pre_delete_handler) signals.post_delete.disconnect(post_delete_handler) def test_delete_signals_origin_model(self): data = [] def pre_delete_handler(signal, sender, instance, origin, **kwargs): data.append((sender, origin)) def post_delete_handler(signal, sender, instance, origin, **kwargs): data.append((sender, origin)) person = Person.objects.create(first_name="John", last_name="Smith") book = Book.objects.create(name="Rayuela") Page.objects.create(text="Page 1", book=book) Page.objects.create(text="Page 2", book=book) signals.pre_delete.connect(pre_delete_handler, weak=False) signals.post_delete.connect(post_delete_handler, weak=False) try: # Instance deletion. person.delete() self.assertEqual(data, [(Person, person), (Person, person)]) data[:] = [] # Cascade deletion. book.delete() self.assertEqual( data, [ (Page, book), (Page, book), (Book, book), (Page, book), (Page, book), (Book, book), ], ) finally: signals.pre_delete.disconnect(pre_delete_handler) signals.post_delete.disconnect(post_delete_handler) def test_delete_signals_origin_queryset(self): data = [] def pre_delete_handler(signal, sender, instance, origin, **kwargs): data.append((sender, origin)) def post_delete_handler(signal, sender, instance, origin, **kwargs): data.append((sender, origin)) Person.objects.create(first_name="John", last_name="Smith") book = Book.objects.create(name="Rayuela") Page.objects.create(text="Page 1", book=book) Page.objects.create(text="Page 2", book=book) signals.pre_delete.connect(pre_delete_handler, weak=False) signals.post_delete.connect(post_delete_handler, weak=False) try: # Queryset deletion. qs = Person.objects.all() qs.delete() self.assertEqual(data, [(Person, qs), (Person, qs)]) data[:] = [] # Cascade deletion. qs = Book.objects.all() qs.delete() self.assertEqual( data, [ (Page, qs), (Page, qs), (Book, qs), (Page, qs), (Page, qs), (Book, qs), ], ) finally: signals.pre_delete.disconnect(pre_delete_handler) signals.post_delete.disconnect(post_delete_handler) def test_decorators(self): data = [] @receiver(signals.pre_save, weak=False) def decorated_handler(signal, sender, instance, **kwargs): data.append(instance) @receiver(signals.pre_save, sender=Car, weak=False) def decorated_handler_with_sender_arg(signal, sender, instance, **kwargs): data.append(instance) try: c1 = Car.objects.create(make="Volkswagen", model="Passat") self.assertEqual(data, [c1, c1]) finally: signals.pre_save.disconnect(decorated_handler) signals.pre_save.disconnect(decorated_handler_with_sender_arg, sender=Car) def test_save_and_delete_signals_with_m2m(self): data = [] def pre_save_handler(signal, sender, instance, **kwargs): data.append("pre_save signal, %s" % instance) if kwargs.get("raw"): data.append("Is raw") def post_save_handler(signal, sender, instance, **kwargs): data.append("post_save signal, %s" % instance) if "created" in kwargs: if kwargs["created"]: data.append("Is created") else: data.append("Is updated") if kwargs.get("raw"): data.append("Is raw") def pre_delete_handler(signal, sender, instance, **kwargs): data.append("pre_delete signal, %s" % instance) data.append("instance.id is not None: %s" % (instance.id is not None)) def post_delete_handler(signal, sender, instance, **kwargs): data.append("post_delete signal, %s" % instance) data.append("instance.id is not None: %s" % (instance.id is not None)) signals.pre_save.connect(pre_save_handler, weak=False) signals.post_save.connect(post_save_handler, weak=False) signals.pre_delete.connect(pre_delete_handler, weak=False) signals.post_delete.connect(post_delete_handler, weak=False) try: a1 = Author.objects.create(name="Neal Stephenson") self.assertEqual( data, [ "pre_save signal, Neal Stephenson", "post_save signal, Neal Stephenson", "Is created", ], ) data[:] = [] b1 = Book.objects.create(name="Snow Crash") self.assertEqual( data, [ "pre_save signal, Snow Crash", "post_save signal, Snow Crash", "Is created", ], ) data[:] = [] # Assigning and removing to/from m2m shouldn't generate an m2m signal. b1.authors.set([a1]) self.assertEqual(data, []) b1.authors.set([]) self.assertEqual(data, []) finally: signals.pre_save.disconnect(pre_save_handler) signals.post_save.disconnect(post_save_handler) signals.pre_delete.disconnect(pre_delete_handler) signals.post_delete.disconnect(post_delete_handler) def test_disconnect_in_dispatch(self): """ Signals that disconnect when being called don't mess future dispatching. """ class Handler: def __init__(self, param): self.param = param self._run = False def __call__(self, signal, sender, **kwargs): self._run = True signal.disconnect(receiver=self, sender=sender) a, b = Handler(1), Handler(2) signals.post_save.connect(a, sender=Person, weak=False) signals.post_save.connect(b, sender=Person, weak=False) Person.objects.create(first_name="John", last_name="Smith") self.assertTrue(a._run) self.assertTrue(b._run) self.assertEqual(signals.post_save.receivers, []) @mock.patch("weakref.ref") def test_lazy_model_signal(self, ref): def callback(sender, args, **kwargs): pass signals.pre_init.connect(callback) signals.pre_init.disconnect(callback) self.assertTrue(ref.called) ref.reset_mock() signals.pre_init.connect(callback, weak=False) signals.pre_init.disconnect(callback) ref.assert_not_called() @isolate_apps("signals", kwarg_name="apps") def test_disconnect_model(self, apps): received = [] def receiver(**kwargs): received.append(kwargs) class Created(models.Model): pass signals.post_init.connect(receiver, sender=Created, apps=apps) try: self.assertIs( signals.post_init.disconnect(receiver, sender=Created, apps=apps), True, ) self.assertIs( signals.post_init.disconnect(receiver, sender=Created, apps=apps), False, ) Created() self.assertEqual(received, []) finally: signals.post_init.disconnect(receiver, sender=Created) class LazyModelRefTests(BaseSignalSetup, SimpleTestCase): def setUp(self): super().setUp() self.received = [] def receiver(self, **kwargs): self.received.append(kwargs) def test_invalid_sender_model_name(self): msg = ( "Invalid model reference 'invalid'. String model references must be of the " "form 'app_label.ModelName'." ) with self.assertRaisesMessage(ValueError, msg): signals.post_init.connect(self.receiver, sender="invalid") def test_already_loaded_model(self): signals.post_init.connect(self.receiver, sender="signals.Book", weak=False) try: instance = Book() self.assertEqual( self.received, [{"signal": signals.post_init, "sender": Book, "instance": instance}], ) finally: signals.post_init.disconnect(self.receiver, sender=Book) @isolate_apps("signals", kwarg_name="apps") def test_not_loaded_model(self, apps): signals.post_init.connect( self.receiver, sender="signals.Created", weak=False, apps=apps ) try: class Created(models.Model): pass instance = Created() self.assertEqual( self.received, [ { "signal": signals.post_init, "sender": Created, "instance": instance, } ], ) finally: signals.post_init.disconnect(self.receiver, sender=Created) @isolate_apps("signals", kwarg_name="apps") def test_disconnect_registered_model(self, apps): received = [] def receiver(**kwargs): received.append(kwargs) class Created(models.Model): pass signals.post_init.connect(receiver, sender="signals.Created", apps=apps) try: self.assertIsNone( signals.post_init.disconnect( receiver, sender="signals.Created", apps=apps ) ) self.assertIsNone( signals.post_init.disconnect( receiver, sender="signals.Created", apps=apps ) ) Created() self.assertEqual(received, []) finally: signals.post_init.disconnect(receiver, sender="signals.Created") @isolate_apps("signals", kwarg_name="apps") def test_disconnect_unregistered_model(self, apps): received = [] def receiver(**kwargs): received.append(kwargs) signals.post_init.connect(receiver, sender="signals.Created", apps=apps) try: self.assertIsNone( signals.post_init.disconnect( receiver, sender="signals.Created", apps=apps ) ) self.assertIsNone( signals.post_init.disconnect( receiver, sender="signals.Created", apps=apps ) ) class Created(models.Model): pass Created() self.assertEqual(received, []) finally: signals.post_init.disconnect(receiver, sender="signals.Created") def test_register_model_class_senders_immediately(self): """ Model signals registered with model classes as senders don't use the Apps.lazy_model_operation() mechanism. """ # Book isn't registered with apps2, so it will linger in # apps2._pending_operations if ModelSignal does the wrong thing. apps2 = Apps() signals.post_init.connect(self.receiver, sender=Book, apps=apps2) self.assertEqual(list(apps2._pending_operations), []) class SyncHandler: param = 0 def __call__(self, **kwargs): self.param += 1 return self.param class AsyncHandler: param = 0 def __init__(self): markcoroutinefunction(self) async def __call__(self, **kwargs): self.param += 1 return self.param class AsyncReceiversTests(SimpleTestCase): async def test_asend(self): sync_handler = SyncHandler() async_handler = AsyncHandler() signal = dispatch.Signal() signal.connect(sync_handler) signal.connect(async_handler) result = await signal.asend(self.__class__) self.assertEqual(result, [(sync_handler, 1), (async_handler, 1)]) def test_send(self): sync_handler = SyncHandler() async_handler = AsyncHandler() signal = dispatch.Signal() signal.connect(sync_handler) signal.connect(async_handler) result = signal.send(self.__class__) self.assertEqual(result, [(sync_handler, 1), (async_handler, 1)]) def test_send_robust(self): class ReceiverException(Exception): pass receiver_exception = ReceiverException() async def failing_async_handler(**kwargs): raise receiver_exception sync_handler = SyncHandler() async_handler = AsyncHandler() signal = dispatch.Signal() signal.connect(failing_async_handler) signal.connect(async_handler) signal.connect(sync_handler) result = signal.send_robust(self.__class__) # The ordering here is different than the order that signals were # connected in. self.assertEqual( result, [ (sync_handler, 1), (failing_async_handler, receiver_exception), (async_handler, 1), ], ) async def test_asend_robust(self): class ReceiverException(Exception): pass receiver_exception = ReceiverException() async def failing_async_handler(**kwargs): raise receiver_exception sync_handler = SyncHandler() async_handler = AsyncHandler() signal = dispatch.Signal() signal.connect(failing_async_handler) signal.connect(async_handler) signal.connect(sync_handler) result = await signal.asend_robust(self.__class__) # The ordering here is different than the order that signals were # connected in. self.assertEqual( result, [ (sync_handler, 1), (failing_async_handler, receiver_exception), (async_handler, 1), ], )
bd41ecb366b308bdce27c9e9ff31fc436a6d747c9ed8ce9f78f08ede1fb64335
import datetime from unittest import mock from django.contrib import admin from django.contrib.admin.models import LogEntry from django.contrib.admin.options import IncorrectLookupParameters from django.contrib.admin.templatetags.admin_list import pagination from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.admin.views.main import ( ALL_VAR, IS_FACETS_VAR, IS_POPUP_VAR, ORDER_VAR, PAGE_VAR, SEARCH_VAR, TO_FIELD_VAR, ) from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.messages.storage.cookie import CookieStorage from django.db import DatabaseError, connection, models from django.db.models import F, Field, IntegerField from django.db.models.functions import Upper from django.db.models.lookups import Contains, Exact from django.template import Context, Template, TemplateSyntaxError from django.test import TestCase, override_settings, skipUnlessDBFeature from django.test.client import RequestFactory from django.test.utils import CaptureQueriesContext, isolate_apps, register_lookup from django.urls import reverse from django.utils import formats from .admin import ( BandAdmin, ChildAdmin, ChordsBandAdmin, ConcertAdmin, CustomPaginationAdmin, CustomPaginator, DynamicListDisplayChildAdmin, DynamicListDisplayLinksChildAdmin, DynamicListFilterChildAdmin, DynamicSearchFieldsChildAdmin, EmptyValueChildAdmin, EventAdmin, FilteredChildAdmin, GroupAdmin, InvitationAdmin, NoListDisplayLinksParentAdmin, ParentAdmin, ParentAdminTwoSearchFields, QuartetAdmin, SwallowAdmin, ) from .admin import site as custom_site from .models import ( Band, CharPK, Child, ChordsBand, ChordsMusician, Concert, CustomIdUser, Event, Genre, Group, Invitation, Membership, Musician, OrderedObject, Parent, Quartet, Swallow, SwallowOneToOne, UnorderedObject, ) def build_tbody_html(obj, href, extra_fields): return ( "<tbody><tr>" '<td class="action-checkbox">' '<input type="checkbox" name="_selected_action" value="{}" ' 'class="action-select" aria-label="Select this object for an action - {}"></td>' '<th class="field-name"><a href="{}">name</a></th>' "{}</tr></tbody>" ).format(obj.pk, str(obj), href, extra_fields) @override_settings(ROOT_URLCONF="admin_changelist.urls") class ChangeListTests(TestCase): factory = RequestFactory() @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", email="[email protected]", password="xxx" ) def _create_superuser(self, username): return User.objects.create_superuser( username=username, email="[email protected]", password="xxx" ) def _mocked_authenticated_request(self, url, user): request = self.factory.get(url) request.user = user return request def test_repr(self): m = ChildAdmin(Child, custom_site) request = self.factory.get("/child/") request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(repr(cl), "<ChangeList: model=Child model_admin=ChildAdmin>") def test_specified_ordering_by_f_expression(self): class OrderedByFBandAdmin(admin.ModelAdmin): list_display = ["name", "genres", "nr_of_members"] ordering = ( F("nr_of_members").desc(nulls_last=True), Upper(F("name")).asc(), F("genres").asc(), ) m = OrderedByFBandAdmin(Band, custom_site) request = self.factory.get("/band/") request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.get_ordering_field_columns(), {3: "desc", 2: "asc"}) def test_specified_ordering_by_f_expression_without_asc_desc(self): class OrderedByFBandAdmin(admin.ModelAdmin): list_display = ["name", "genres", "nr_of_members"] ordering = (F("nr_of_members"), Upper("name"), F("genres")) m = OrderedByFBandAdmin(Band, custom_site) request = self.factory.get("/band/") request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.get_ordering_field_columns(), {3: "asc", 2: "asc"}) def test_select_related_preserved(self): """ Regression test for #10348: ChangeList.get_queryset() shouldn't overwrite a custom select_related provided by ModelAdmin.get_queryset(). """ m = ChildAdmin(Child, custom_site) request = self.factory.get("/child/") request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.query.select_related, {"parent": {}}) def test_select_related_preserved_when_multi_valued_in_search_fields(self): parent = Parent.objects.create(name="Mary") Child.objects.create(parent=parent, name="Danielle") Child.objects.create(parent=parent, name="Daniel") m = ParentAdmin(Parent, custom_site) request = self.factory.get("/parent/", data={SEARCH_VAR: "daniel"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 1) # select_related is preserved. self.assertEqual(cl.queryset.query.select_related, {"child": {}}) def test_select_related_as_tuple(self): ia = InvitationAdmin(Invitation, custom_site) request = self.factory.get("/invitation/") request.user = self.superuser cl = ia.get_changelist_instance(request) self.assertEqual(cl.queryset.query.select_related, {"player": {}}) def test_select_related_as_empty_tuple(self): ia = InvitationAdmin(Invitation, custom_site) ia.list_select_related = () request = self.factory.get("/invitation/") request.user = self.superuser cl = ia.get_changelist_instance(request) self.assertIs(cl.queryset.query.select_related, False) def test_get_select_related_custom_method(self): class GetListSelectRelatedAdmin(admin.ModelAdmin): list_display = ("band", "player") def get_list_select_related(self, request): return ("band", "player") ia = GetListSelectRelatedAdmin(Invitation, custom_site) request = self.factory.get("/invitation/") request.user = self.superuser cl = ia.get_changelist_instance(request) self.assertEqual(cl.queryset.query.select_related, {"player": {}, "band": {}}) def test_many_search_terms(self): parent = Parent.objects.create(name="Mary") Child.objects.create(parent=parent, name="Danielle") Child.objects.create(parent=parent, name="Daniel") m = ParentAdmin(Parent, custom_site) request = self.factory.get("/parent/", data={SEARCH_VAR: "daniel " * 80}) request.user = self.superuser cl = m.get_changelist_instance(request) with CaptureQueriesContext(connection) as context: object_count = cl.queryset.count() self.assertEqual(object_count, 1) self.assertEqual(context.captured_queries[0]["sql"].count("JOIN"), 1) def test_related_field_multiple_search_terms(self): """ Searches over multi-valued relationships return rows from related models only when all searched fields match that row. """ parent = Parent.objects.create(name="Mary") Child.objects.create(parent=parent, name="Danielle", age=18) Child.objects.create(parent=parent, name="Daniel", age=19) m = ParentAdminTwoSearchFields(Parent, custom_site) request = self.factory.get("/parent/", data={SEARCH_VAR: "danielle 19"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 0) request = self.factory.get("/parent/", data={SEARCH_VAR: "daniel 19"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 1) def test_result_list_empty_changelist_value(self): """ Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored for relationship fields """ new_child = Child.objects.create(name="name", parent=None) request = self.factory.get("/child/") request.user = self.superuser m = ChildAdmin(Child, custom_site) cl = m.get_changelist_instance(request) cl.formset = None template = Template( "{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}" ) context = Context({"cl": cl, "opts": Child._meta}) table_output = template.render(context) link = reverse("admin:admin_changelist_child_change", args=(new_child.id,)) row_html = build_tbody_html( new_child, link, '<td class="field-parent nowrap">-</td>' ) self.assertNotEqual( table_output.find(row_html), -1, "Failed to find expected row element: %s" % table_output, ) def test_result_list_set_empty_value_display_on_admin_site(self): """ Empty value display can be set on AdminSite. """ new_child = Child.objects.create(name="name", parent=None) request = self.factory.get("/child/") request.user = self.superuser # Set a new empty display value on AdminSite. admin.site.empty_value_display = "???" m = ChildAdmin(Child, admin.site) cl = m.get_changelist_instance(request) cl.formset = None template = Template( "{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}" ) context = Context({"cl": cl, "opts": Child._meta}) table_output = template.render(context) link = reverse("admin:admin_changelist_child_change", args=(new_child.id,)) row_html = build_tbody_html( new_child, link, '<td class="field-parent nowrap">???</td>' ) self.assertNotEqual( table_output.find(row_html), -1, "Failed to find expected row element: %s" % table_output, ) def test_result_list_set_empty_value_display_in_model_admin(self): """ Empty value display can be set in ModelAdmin or individual fields. """ new_child = Child.objects.create(name="name", parent=None) request = self.factory.get("/child/") request.user = self.superuser m = EmptyValueChildAdmin(Child, admin.site) cl = m.get_changelist_instance(request) cl.formset = None template = Template( "{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}" ) context = Context({"cl": cl, "opts": Child._meta}) table_output = template.render(context) link = reverse("admin:admin_changelist_child_change", args=(new_child.id,)) row_html = build_tbody_html( new_child, link, '<td class="field-age_display">&amp;dagger;</td>' '<td class="field-age">-empty-</td>', ) self.assertNotEqual( table_output.find(row_html), -1, "Failed to find expected row element: %s" % table_output, ) def test_result_list_html(self): """ Inclusion tag result_list generates a table when with default ModelAdmin settings. """ new_parent = Parent.objects.create(name="parent") new_child = Child.objects.create(name="name", parent=new_parent) request = self.factory.get("/child/") request.user = self.superuser m = ChildAdmin(Child, custom_site) cl = m.get_changelist_instance(request) cl.formset = None template = Template( "{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}" ) context = Context({"cl": cl, "opts": Child._meta}) table_output = template.render(context) link = reverse("admin:admin_changelist_child_change", args=(new_child.id,)) row_html = build_tbody_html( new_child, link, '<td class="field-parent nowrap">%s</td>' % new_parent ) self.assertNotEqual( table_output.find(row_html), -1, "Failed to find expected row element: %s" % table_output, ) self.assertInHTML( '<input type="checkbox" id="action-toggle" ' 'aria-label="Select all objects on this page for an action">', table_output, ) def test_result_list_editable_html(self): """ Regression tests for #11791: Inclusion tag result_list generates a table and this checks that the items are nested within the table element tags. Also a regression test for #13599, verifies that hidden fields when list_editable is enabled are rendered in a div outside the table. """ new_parent = Parent.objects.create(name="parent") new_child = Child.objects.create(name="name", parent=new_parent) request = self.factory.get("/child/") request.user = self.superuser m = ChildAdmin(Child, custom_site) # Test with list_editable fields m.list_display = ["id", "name", "parent"] m.list_display_links = ["id"] m.list_editable = ["name"] cl = m.get_changelist_instance(request) FormSet = m.get_changelist_formset(request) cl.formset = FormSet(queryset=cl.result_list) template = Template( "{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}" ) context = Context({"cl": cl, "opts": Child._meta}) table_output = template.render(context) # make sure that hidden fields are in the correct place hiddenfields_div = ( '<div class="hiddenfields">' '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id">' "</div>" ) % new_child.id self.assertInHTML( hiddenfields_div, table_output, msg_prefix="Failed to find hidden fields" ) # make sure that list editable fields are rendered in divs correctly editable_name_field = ( '<input name="form-0-name" value="name" class="vTextField" ' 'maxlength="30" type="text" id="id_form-0-name">' ) self.assertInHTML( '<td class="field-name">%s</td>' % editable_name_field, table_output, msg_prefix='Failed to find "name" list_editable field', ) def test_result_list_editable(self): """ Regression test for #14312: list_editable with pagination """ new_parent = Parent.objects.create(name="parent") for i in range(1, 201): Child.objects.create(name="name %s" % i, parent=new_parent) request = self.factory.get("/child/", data={"p": -1}) # Anything outside range request.user = self.superuser m = ChildAdmin(Child, custom_site) # Test with list_editable fields m.list_display = ["id", "name", "parent"] m.list_display_links = ["id"] m.list_editable = ["name"] with self.assertRaises(IncorrectLookupParameters): m.get_changelist_instance(request) @skipUnlessDBFeature("supports_transactions") def test_list_editable_atomicity(self): a = Swallow.objects.create(origin="Swallow A", load=4, speed=1) b = Swallow.objects.create(origin="Swallow B", load=2, speed=2) self.client.force_login(self.superuser) changelist_url = reverse("admin:admin_changelist_swallow_changelist") data = { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "2", "form-MIN_NUM_FORMS": "0", "form-MAX_NUM_FORMS": "1000", "form-0-uuid": str(a.pk), "form-1-uuid": str(b.pk), "form-0-load": "9.0", "form-0-speed": "3.0", "form-1-load": "5.0", "form-1-speed": "1.0", "_save": "Save", } with mock.patch( "django.contrib.admin.ModelAdmin.log_change", side_effect=DatabaseError ): with self.assertRaises(DatabaseError): self.client.post(changelist_url, data) # Original values are preserved. a.refresh_from_db() self.assertEqual(a.load, 4) self.assertEqual(a.speed, 1) b.refresh_from_db() self.assertEqual(b.load, 2) self.assertEqual(b.speed, 2) with mock.patch( "django.contrib.admin.ModelAdmin.log_change", side_effect=[None, DatabaseError], ): with self.assertRaises(DatabaseError): self.client.post(changelist_url, data) # Original values are preserved. a.refresh_from_db() self.assertEqual(a.load, 4) self.assertEqual(a.speed, 1) b.refresh_from_db() self.assertEqual(b.load, 2) self.assertEqual(b.speed, 2) def test_custom_paginator(self): new_parent = Parent.objects.create(name="parent") for i in range(1, 201): Child.objects.create(name="name %s" % i, parent=new_parent) request = self.factory.get("/child/") request.user = self.superuser m = CustomPaginationAdmin(Child, custom_site) cl = m.get_changelist_instance(request) cl.get_results(request) self.assertIsInstance(cl.paginator, CustomPaginator) def test_no_duplicates_for_m2m_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't appear more than once. Basic ManyToMany. """ blues = Genre.objects.create(name="Blues") band = Band.objects.create(name="B.B. King Review", nr_of_members=11) band.genres.add(blues) band.genres.add(blues) m = BandAdmin(Band, custom_site) request = self.factory.get("/band/", data={"genres": blues.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) cl.get_results(request) # There's only one Group instance self.assertEqual(cl.result_count, 1) # Queryset must be deletable. self.assertIs(cl.queryset.query.distinct, False) cl.queryset.delete() self.assertEqual(cl.queryset.count(), 0) def test_no_duplicates_for_through_m2m_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't appear more than once. With an intermediate model. """ lead = Musician.objects.create(name="Vox") band = Group.objects.create(name="The Hype") Membership.objects.create(group=band, music=lead, role="lead voice") Membership.objects.create(group=band, music=lead, role="bass player") m = GroupAdmin(Group, custom_site) request = self.factory.get("/group/", data={"members": lead.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) cl.get_results(request) # There's only one Group instance self.assertEqual(cl.result_count, 1) # Queryset must be deletable. self.assertIs(cl.queryset.query.distinct, False) cl.queryset.delete() self.assertEqual(cl.queryset.count(), 0) def test_no_duplicates_for_through_m2m_at_second_level_in_list_filter(self): """ When using a ManyToMany in list_filter at the second level behind a ForeignKey, results shouldn't appear more than once. """ lead = Musician.objects.create(name="Vox") band = Group.objects.create(name="The Hype") Concert.objects.create(name="Woodstock", group=band) Membership.objects.create(group=band, music=lead, role="lead voice") Membership.objects.create(group=band, music=lead, role="bass player") m = ConcertAdmin(Concert, custom_site) request = self.factory.get("/concert/", data={"group__members": lead.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) cl.get_results(request) # There's only one Concert instance self.assertEqual(cl.result_count, 1) # Queryset must be deletable. self.assertIs(cl.queryset.query.distinct, False) cl.queryset.delete() self.assertEqual(cl.queryset.count(), 0) def test_no_duplicates_for_inherited_m2m_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't appear more than once. Model managed in the admin inherits from the one that defines the relationship. """ lead = Musician.objects.create(name="John") four = Quartet.objects.create(name="The Beatles") Membership.objects.create(group=four, music=lead, role="lead voice") Membership.objects.create(group=four, music=lead, role="guitar player") m = QuartetAdmin(Quartet, custom_site) request = self.factory.get("/quartet/", data={"members": lead.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) cl.get_results(request) # There's only one Quartet instance self.assertEqual(cl.result_count, 1) # Queryset must be deletable. self.assertIs(cl.queryset.query.distinct, False) cl.queryset.delete() self.assertEqual(cl.queryset.count(), 0) def test_no_duplicates_for_m2m_to_inherited_in_list_filter(self): """ Regression test for #13902: When using a ManyToMany in list_filter, results shouldn't appear more than once. Target of the relationship inherits from another. """ lead = ChordsMusician.objects.create(name="Player A") three = ChordsBand.objects.create(name="The Chords Trio") Invitation.objects.create(band=three, player=lead, instrument="guitar") Invitation.objects.create(band=three, player=lead, instrument="bass") m = ChordsBandAdmin(ChordsBand, custom_site) request = self.factory.get("/chordsband/", data={"members": lead.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) cl.get_results(request) # There's only one ChordsBand instance self.assertEqual(cl.result_count, 1) # Queryset must be deletable. self.assertIs(cl.queryset.query.distinct, False) cl.queryset.delete() self.assertEqual(cl.queryset.count(), 0) def test_no_duplicates_for_non_unique_related_object_in_list_filter(self): """ Regressions tests for #15819: If a field listed in list_filters is a non-unique related object, results shouldn't appear more than once. """ parent = Parent.objects.create(name="Mary") # Two children with the same name Child.objects.create(parent=parent, name="Daniel") Child.objects.create(parent=parent, name="Daniel") m = ParentAdmin(Parent, custom_site) request = self.factory.get("/parent/", data={"child__name": "Daniel"}) request.user = self.superuser cl = m.get_changelist_instance(request) # Exists() is applied. self.assertEqual(cl.queryset.count(), 1) # Queryset must be deletable. self.assertIs(cl.queryset.query.distinct, False) cl.queryset.delete() self.assertEqual(cl.queryset.count(), 0) def test_changelist_search_form_validation(self): m = ConcertAdmin(Concert, custom_site) tests = [ ({SEARCH_VAR: "\x00"}, "Null characters are not allowed."), ({SEARCH_VAR: "some\x00thing"}, "Null characters are not allowed."), ] for case, error in tests: with self.subTest(case=case): request = self.factory.get("/concert/", case) request.user = self.superuser request._messages = CookieStorage(request) m.get_changelist_instance(request) messages = [m.message for m in request._messages] self.assertEqual(1, len(messages)) self.assertEqual(error, messages[0]) def test_no_duplicates_for_non_unique_related_object_in_search_fields(self): """ Regressions tests for #15819: If a field listed in search_fields is a non-unique related object, Exists() must be applied. """ parent = Parent.objects.create(name="Mary") Child.objects.create(parent=parent, name="Danielle") Child.objects.create(parent=parent, name="Daniel") m = ParentAdmin(Parent, custom_site) request = self.factory.get("/parent/", data={SEARCH_VAR: "daniel"}) request.user = self.superuser cl = m.get_changelist_instance(request) # Exists() is applied. self.assertEqual(cl.queryset.count(), 1) # Queryset must be deletable. self.assertIs(cl.queryset.query.distinct, False) cl.queryset.delete() self.assertEqual(cl.queryset.count(), 0) def test_no_duplicates_for_many_to_many_at_second_level_in_search_fields(self): """ When using a ManyToMany in search_fields at the second level behind a ForeignKey, Exists() must be applied and results shouldn't appear more than once. """ lead = Musician.objects.create(name="Vox") band = Group.objects.create(name="The Hype") Concert.objects.create(name="Woodstock", group=band) Membership.objects.create(group=band, music=lead, role="lead voice") Membership.objects.create(group=band, music=lead, role="bass player") m = ConcertAdmin(Concert, custom_site) request = self.factory.get("/concert/", data={SEARCH_VAR: "vox"}) request.user = self.superuser cl = m.get_changelist_instance(request) # There's only one Concert instance self.assertEqual(cl.queryset.count(), 1) # Queryset must be deletable. self.assertIs(cl.queryset.query.distinct, False) cl.queryset.delete() self.assertEqual(cl.queryset.count(), 0) def test_multiple_search_fields(self): """ All rows containing each of the searched words are returned, where each word must be in one of search_fields. """ band_duo = Group.objects.create(name="Duo") band_hype = Group.objects.create(name="The Hype") mary = Musician.objects.create(name="Mary Halvorson") jonathan = Musician.objects.create(name="Jonathan Finlayson") band_duo.members.set([mary, jonathan]) Concert.objects.create(name="Tiny desk concert", group=band_duo) Concert.objects.create(name="Woodstock concert", group=band_hype) # FK lookup. concert_model_admin = ConcertAdmin(Concert, custom_site) concert_model_admin.search_fields = ["group__name", "name"] # Reverse FK lookup. group_model_admin = GroupAdmin(Group, custom_site) group_model_admin.search_fields = ["name", "concert__name", "members__name"] for search_string, result_count in ( ("Duo Concert", 1), ("Tiny Desk Concert", 1), ("Concert", 2), ("Other Concert", 0), ("Duo Woodstock", 0), ): with self.subTest(search_string=search_string): # FK lookup. request = self.factory.get( "/concert/", data={SEARCH_VAR: search_string} ) request.user = self.superuser concert_changelist = concert_model_admin.get_changelist_instance( request ) self.assertEqual(concert_changelist.queryset.count(), result_count) # Reverse FK lookup. request = self.factory.get("/group/", data={SEARCH_VAR: search_string}) request.user = self.superuser group_changelist = group_model_admin.get_changelist_instance(request) self.assertEqual(group_changelist.queryset.count(), result_count) # Many-to-many lookup. for search_string, result_count in ( ("Finlayson Duo Tiny", 1), ("Finlayson", 1), ("Finlayson Hype", 0), ("Jonathan Finlayson Duo", 1), ("Mary Jonathan Duo", 0), ("Oscar Finlayson Duo", 0), ): with self.subTest(search_string=search_string): request = self.factory.get("/group/", data={SEARCH_VAR: search_string}) request.user = self.superuser group_changelist = group_model_admin.get_changelist_instance(request) self.assertEqual(group_changelist.queryset.count(), result_count) def test_pk_in_search_fields(self): band = Group.objects.create(name="The Hype") Concert.objects.create(name="Woodstock", group=band) m = ConcertAdmin(Concert, custom_site) m.search_fields = ["group__pk"] request = self.factory.get("/concert/", data={SEARCH_VAR: band.pk}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 1) request = self.factory.get("/concert/", data={SEARCH_VAR: band.pk + 5}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 0) def test_builtin_lookup_in_search_fields(self): band = Group.objects.create(name="The Hype") concert = Concert.objects.create(name="Woodstock", group=band) m = ConcertAdmin(Concert, custom_site) m.search_fields = ["name__iexact"] request = self.factory.get("/", data={SEARCH_VAR: "woodstock"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [concert]) request = self.factory.get("/", data={SEARCH_VAR: "wood"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, []) def test_custom_lookup_in_search_fields(self): band = Group.objects.create(name="The Hype") concert = Concert.objects.create(name="Woodstock", group=band) m = ConcertAdmin(Concert, custom_site) m.search_fields = ["group__name__cc"] with register_lookup(Field, Contains, lookup_name="cc"): request = self.factory.get("/", data={SEARCH_VAR: "Hype"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [concert]) request = self.factory.get("/", data={SEARCH_VAR: "Woodstock"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, []) def test_spanning_relations_with_custom_lookup_in_search_fields(self): hype = Group.objects.create(name="The Hype") concert = Concert.objects.create(name="Woodstock", group=hype) vox = Musician.objects.create(name="Vox", age=20) Membership.objects.create(music=vox, group=hype) # Register a custom lookup on IntegerField to ensure that field # traversing logic in ModelAdmin.get_search_results() works. with register_lookup(IntegerField, Exact, lookup_name="exactly"): m = ConcertAdmin(Concert, custom_site) m.search_fields = ["group__members__age__exactly"] request = self.factory.get("/", data={SEARCH_VAR: "20"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [concert]) request = self.factory.get("/", data={SEARCH_VAR: "21"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, []) def test_custom_lookup_with_pk_shortcut(self): self.assertEqual(CharPK._meta.pk.name, "char_pk") # Not equal to 'pk'. m = admin.ModelAdmin(CustomIdUser, custom_site) abc = CharPK.objects.create(char_pk="abc") abcd = CharPK.objects.create(char_pk="abcd") m = admin.ModelAdmin(CharPK, custom_site) m.search_fields = ["pk__exact"] request = self.factory.get("/", data={SEARCH_VAR: "abc"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [abc]) request = self.factory.get("/", data={SEARCH_VAR: "abcd"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertCountEqual(cl.queryset, [abcd]) def test_no_exists_for_m2m_in_list_filter_without_params(self): """ If a ManyToManyField is in list_filter but isn't in any lookup params, the changelist's query shouldn't have Exists(). """ m = BandAdmin(Band, custom_site) for lookup_params in ({}, {"name": "test"}): request = self.factory.get("/band/", lookup_params) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertNotIn(" EXISTS", str(cl.queryset.query)) # A ManyToManyField in params does have Exists() applied. request = self.factory.get("/band/", {"genres": "0"}) request.user = self.superuser cl = m.get_changelist_instance(request) self.assertIn(" EXISTS", str(cl.queryset.query)) def test_pagination(self): """ Regression tests for #12893: Pagination in admins changelist doesn't use queryset set by modeladmin. """ parent = Parent.objects.create(name="anything") for i in range(1, 31): Child.objects.create(name="name %s" % i, parent=parent) Child.objects.create(name="filtered %s" % i, parent=parent) request = self.factory.get("/child/") request.user = self.superuser # Test default queryset m = ChildAdmin(Child, custom_site) cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 60) self.assertEqual(cl.paginator.count, 60) self.assertEqual(list(cl.paginator.page_range), [1, 2, 3, 4, 5, 6]) # Test custom queryset m = FilteredChildAdmin(Child, custom_site) cl = m.get_changelist_instance(request) self.assertEqual(cl.queryset.count(), 30) self.assertEqual(cl.paginator.count, 30) self.assertEqual(list(cl.paginator.page_range), [1, 2, 3]) def test_computed_list_display_localization(self): """ Regression test for #13196: output of functions should be localized in the changelist. """ self.client.force_login(self.superuser) event = Event.objects.create(date=datetime.date.today()) response = self.client.get(reverse("admin:admin_changelist_event_changelist")) self.assertContains(response, formats.localize(event.date)) self.assertNotContains(response, str(event.date)) def test_dynamic_list_display(self): """ Regression tests for #14206: dynamic list_display support. """ parent = Parent.objects.create(name="parent") for i in range(10): Child.objects.create(name="child %s" % i, parent=parent) user_noparents = self._create_superuser("noparents") user_parents = self._create_superuser("parents") # Test with user 'noparents' m = custom_site._registry[Child] request = self._mocked_authenticated_request("/child/", user_noparents) response = m.changelist_view(request) self.assertNotContains(response, "Parent object") list_display = m.get_list_display(request) list_display_links = m.get_list_display_links(request, list_display) self.assertEqual(list_display, ["name", "age"]) self.assertEqual(list_display_links, ["name"]) # Test with user 'parents' m = DynamicListDisplayChildAdmin(Child, custom_site) request = self._mocked_authenticated_request("/child/", user_parents) response = m.changelist_view(request) self.assertContains(response, "Parent object") custom_site.unregister(Child) list_display = m.get_list_display(request) list_display_links = m.get_list_display_links(request, list_display) self.assertEqual(list_display, ("parent", "name", "age")) self.assertEqual(list_display_links, ["parent"]) # Test default implementation custom_site.register(Child, ChildAdmin) m = custom_site._registry[Child] request = self._mocked_authenticated_request("/child/", user_noparents) response = m.changelist_view(request) self.assertContains(response, "Parent object") def test_show_all(self): parent = Parent.objects.create(name="anything") for i in range(1, 31): Child.objects.create(name="name %s" % i, parent=parent) Child.objects.create(name="filtered %s" % i, parent=parent) # Add "show all" parameter to request request = self.factory.get("/child/", data={ALL_VAR: ""}) request.user = self.superuser # Test valid "show all" request (number of total objects is under max) m = ChildAdmin(Child, custom_site) m.list_max_show_all = 200 # 200 is the max we'll pass to ChangeList cl = m.get_changelist_instance(request) cl.get_results(request) self.assertEqual(len(cl.result_list), 60) # Test invalid "show all" request (number of total objects over max) # falls back to paginated pages m = ChildAdmin(Child, custom_site) m.list_max_show_all = 30 # 30 is the max we'll pass to ChangeList for this test cl = m.get_changelist_instance(request) cl.get_results(request) self.assertEqual(len(cl.result_list), 10) def test_dynamic_list_display_links(self): """ Regression tests for #16257: dynamic list_display_links support. """ parent = Parent.objects.create(name="parent") for i in range(1, 10): Child.objects.create(id=i, name="child %s" % i, parent=parent, age=i) m = DynamicListDisplayLinksChildAdmin(Child, custom_site) superuser = self._create_superuser("superuser") request = self._mocked_authenticated_request("/child/", superuser) response = m.changelist_view(request) for i in range(1, 10): link = reverse("admin:admin_changelist_child_change", args=(i,)) self.assertContains(response, '<a href="%s">%s</a>' % (link, i)) list_display = m.get_list_display(request) list_display_links = m.get_list_display_links(request, list_display) self.assertEqual(list_display, ("parent", "name", "age")) self.assertEqual(list_display_links, ["age"]) def test_no_list_display_links(self): """#15185 -- Allow no links from the 'change list' view grid.""" p = Parent.objects.create(name="parent") m = NoListDisplayLinksParentAdmin(Parent, custom_site) superuser = self._create_superuser("superuser") request = self._mocked_authenticated_request("/parent/", superuser) response = m.changelist_view(request) link = reverse("admin:admin_changelist_parent_change", args=(p.pk,)) self.assertNotContains(response, '<a href="%s">' % link) def test_clear_all_filters_link(self): self.client.force_login(self.superuser) url = reverse("admin:auth_user_changelist") response = self.client.get(url) self.assertNotContains(response, "&#10006; Clear all filters") link = '<a href="%s">&#10006; Clear all filters</a>' for data, href in ( ({"is_staff__exact": "0"}, "?"), ( {"is_staff__exact": "0", "username__startswith": "test"}, "?username__startswith=test", ), ( {"is_staff__exact": "0", SEARCH_VAR: "test"}, "?%s=test" % SEARCH_VAR, ), ( {"is_staff__exact": "0", IS_POPUP_VAR: "id"}, "?%s=id" % IS_POPUP_VAR, ), ): with self.subTest(data=data): response = self.client.get(url, data=data) self.assertContains(response, link % href) def test_clear_all_filters_link_callable_filter(self): self.client.force_login(self.superuser) url = reverse("admin:admin_changelist_band_changelist") response = self.client.get(url) self.assertNotContains(response, "&#10006; Clear all filters") link = '<a href="%s">&#10006; Clear all filters</a>' for data, href in ( ({"nr_of_members_partition": "5"}, "?"), ( {"nr_of_members_partition": "more", "name__startswith": "test"}, "?name__startswith=test", ), ( {"nr_of_members_partition": "5", IS_POPUP_VAR: "id"}, "?%s=id" % IS_POPUP_VAR, ), ): with self.subTest(data=data): response = self.client.get(url, data=data) self.assertContains(response, link % href) def test_no_clear_all_filters_link(self): self.client.force_login(self.superuser) url = reverse("admin:auth_user_changelist") link = ">&#10006; Clear all filters</a>" for data in ( {SEARCH_VAR: "test"}, {ORDER_VAR: "-1"}, {TO_FIELD_VAR: "id"}, {PAGE_VAR: "1"}, {IS_POPUP_VAR: "1"}, {IS_FACETS_VAR: ""}, {"username__startswith": "test"}, ): with self.subTest(data=data): response = self.client.get(url, data=data) self.assertNotContains(response, link) def test_tuple_list_display(self): swallow = Swallow.objects.create(origin="Africa", load="12.34", speed="22.2") swallow2 = Swallow.objects.create(origin="Africa", load="12.34", speed="22.2") swallow_o2o = SwallowOneToOne.objects.create(swallow=swallow2) model_admin = SwallowAdmin(Swallow, custom_site) superuser = self._create_superuser("superuser") request = self._mocked_authenticated_request("/swallow/", superuser) response = model_admin.changelist_view(request) # just want to ensure it doesn't blow up during rendering self.assertContains(response, str(swallow.origin)) self.assertContains(response, str(swallow.load)) self.assertContains(response, str(swallow.speed)) # Reverse one-to-one relations should work. self.assertContains(response, '<td class="field-swallowonetoone">-</td>') self.assertContains( response, '<td class="field-swallowonetoone">%s</td>' % swallow_o2o ) def test_multiuser_edit(self): """ Simultaneous edits of list_editable fields on the changelist by different users must not result in one user's edits creating a new object instead of modifying the correct existing object (#11313). """ # To replicate this issue, simulate the following steps: # 1. User1 opens an admin changelist with list_editable fields. # 2. User2 edits object "Foo" such that it moves to another page in # the pagination order and saves. # 3. User1 edits object "Foo" and saves. # 4. The edit made by User1 does not get applied to object "Foo" but # instead is used to create a new object (bug). # For this test, order the changelist by the 'speed' attribute and # display 3 objects per page (SwallowAdmin.list_per_page = 3). # Setup the test to reflect the DB state after step 2 where User2 has # edited the first swallow object's speed from '4' to '1'. a = Swallow.objects.create(origin="Swallow A", load=4, speed=1) b = Swallow.objects.create(origin="Swallow B", load=2, speed=2) c = Swallow.objects.create(origin="Swallow C", load=5, speed=5) d = Swallow.objects.create(origin="Swallow D", load=9, speed=9) superuser = self._create_superuser("superuser") self.client.force_login(superuser) changelist_url = reverse("admin:admin_changelist_swallow_changelist") # Send the POST from User1 for step 3. It's still using the changelist # ordering from before User2's edits in step 2. data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MIN_NUM_FORMS": "0", "form-MAX_NUM_FORMS": "1000", "form-0-uuid": str(d.pk), "form-1-uuid": str(c.pk), "form-2-uuid": str(a.pk), "form-0-load": "9.0", "form-0-speed": "9.0", "form-1-load": "5.0", "form-1-speed": "5.0", "form-2-load": "5.0", "form-2-speed": "4.0", "_save": "Save", } response = self.client.post( changelist_url, data, follow=True, extra={"o": "-2"} ) # The object User1 edited in step 3 is displayed on the changelist and # has the correct edits applied. self.assertContains(response, "1 swallow was changed successfully.") self.assertContains(response, a.origin) a.refresh_from_db() self.assertEqual(a.load, float(data["form-2-load"])) self.assertEqual(a.speed, float(data["form-2-speed"])) b.refresh_from_db() self.assertEqual(b.load, 2) self.assertEqual(b.speed, 2) c.refresh_from_db() self.assertEqual(c.load, float(data["form-1-load"])) self.assertEqual(c.speed, float(data["form-1-speed"])) d.refresh_from_db() self.assertEqual(d.load, float(data["form-0-load"])) self.assertEqual(d.speed, float(data["form-0-speed"])) # No new swallows were created. self.assertEqual(len(Swallow.objects.all()), 4) def test_get_edited_object_ids(self): a = Swallow.objects.create(origin="Swallow A", load=4, speed=1) b = Swallow.objects.create(origin="Swallow B", load=2, speed=2) c = Swallow.objects.create(origin="Swallow C", load=5, speed=5) superuser = self._create_superuser("superuser") self.client.force_login(superuser) changelist_url = reverse("admin:admin_changelist_swallow_changelist") m = SwallowAdmin(Swallow, custom_site) data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MIN_NUM_FORMS": "0", "form-MAX_NUM_FORMS": "1000", "form-0-uuid": str(a.pk), "form-1-uuid": str(b.pk), "form-2-uuid": str(c.pk), "form-0-load": "9.0", "form-0-speed": "9.0", "form-1-load": "5.0", "form-1-speed": "5.0", "form-2-load": "5.0", "form-2-speed": "4.0", "_save": "Save", } request = self.factory.post(changelist_url, data=data) pks = m._get_edited_object_pks(request, prefix="form") self.assertEqual(sorted(pks), sorted([str(a.pk), str(b.pk), str(c.pk)])) def test_get_list_editable_queryset(self): a = Swallow.objects.create(origin="Swallow A", load=4, speed=1) Swallow.objects.create(origin="Swallow B", load=2, speed=2) data = { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "2", "form-MIN_NUM_FORMS": "0", "form-MAX_NUM_FORMS": "1000", "form-0-uuid": str(a.pk), "form-0-load": "10", "_save": "Save", } superuser = self._create_superuser("superuser") self.client.force_login(superuser) changelist_url = reverse("admin:admin_changelist_swallow_changelist") m = SwallowAdmin(Swallow, custom_site) request = self.factory.post(changelist_url, data=data) queryset = m._get_list_editable_queryset(request, prefix="form") self.assertEqual(queryset.count(), 1) data["form-0-uuid"] = "INVALD_PRIMARY_KEY" # The unfiltered queryset is returned if there's invalid data. request = self.factory.post(changelist_url, data=data) queryset = m._get_list_editable_queryset(request, prefix="form") self.assertEqual(queryset.count(), 2) def test_get_list_editable_queryset_with_regex_chars_in_prefix(self): a = Swallow.objects.create(origin="Swallow A", load=4, speed=1) Swallow.objects.create(origin="Swallow B", load=2, speed=2) data = { "form$-TOTAL_FORMS": "2", "form$-INITIAL_FORMS": "2", "form$-MIN_NUM_FORMS": "0", "form$-MAX_NUM_FORMS": "1000", "form$-0-uuid": str(a.pk), "form$-0-load": "10", "_save": "Save", } superuser = self._create_superuser("superuser") self.client.force_login(superuser) changelist_url = reverse("admin:admin_changelist_swallow_changelist") m = SwallowAdmin(Swallow, custom_site) request = self.factory.post(changelist_url, data=data) queryset = m._get_list_editable_queryset(request, prefix="form$") self.assertEqual(queryset.count(), 1) def test_changelist_view_list_editable_changed_objects_uses_filter(self): """list_editable edits use a filtered queryset to limit memory usage.""" a = Swallow.objects.create(origin="Swallow A", load=4, speed=1) Swallow.objects.create(origin="Swallow B", load=2, speed=2) data = { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "2", "form-MIN_NUM_FORMS": "0", "form-MAX_NUM_FORMS": "1000", "form-0-uuid": str(a.pk), "form-0-load": "10", "_save": "Save", } superuser = self._create_superuser("superuser") self.client.force_login(superuser) changelist_url = reverse("admin:admin_changelist_swallow_changelist") with CaptureQueriesContext(connection) as context: response = self.client.post(changelist_url, data=data) self.assertEqual(response.status_code, 200) self.assertIn("WHERE", context.captured_queries[4]["sql"]) self.assertIn("IN", context.captured_queries[4]["sql"]) # Check only the first few characters since the UUID may have dashes. self.assertIn(str(a.pk)[:8], context.captured_queries[4]["sql"]) def test_deterministic_order_for_unordered_model(self): """ The primary key is used in the ordering of the changelist's results to guarantee a deterministic order, even when the model doesn't have any default ordering defined (#17198). """ superuser = self._create_superuser("superuser") for counter in range(1, 51): UnorderedObject.objects.create(id=counter, bool=True) class UnorderedObjectAdmin(admin.ModelAdmin): list_per_page = 10 def check_results_order(ascending=False): custom_site.register(UnorderedObject, UnorderedObjectAdmin) model_admin = UnorderedObjectAdmin(UnorderedObject, custom_site) counter = 0 if ascending else 51 for page in range(1, 6): request = self._mocked_authenticated_request( "/unorderedobject/?p=%s" % page, superuser ) response = model_admin.changelist_view(request) for result in response.context_data["cl"].result_list: counter += 1 if ascending else -1 self.assertEqual(result.id, counter) custom_site.unregister(UnorderedObject) # When no order is defined at all, everything is ordered by '-pk'. check_results_order() # When an order field is defined but multiple records have the same # value for that field, make sure everything gets ordered by -pk as well. UnorderedObjectAdmin.ordering = ["bool"] check_results_order() # When order fields are defined, including the pk itself, use them. UnorderedObjectAdmin.ordering = ["bool", "-pk"] check_results_order() UnorderedObjectAdmin.ordering = ["bool", "pk"] check_results_order(ascending=True) UnorderedObjectAdmin.ordering = ["-id", "bool"] check_results_order() UnorderedObjectAdmin.ordering = ["id", "bool"] check_results_order(ascending=True) def test_deterministic_order_for_model_ordered_by_its_manager(self): """ The primary key is used in the ordering of the changelist's results to guarantee a deterministic order, even when the model has a manager that defines a default ordering (#17198). """ superuser = self._create_superuser("superuser") for counter in range(1, 51): OrderedObject.objects.create(id=counter, bool=True, number=counter) class OrderedObjectAdmin(admin.ModelAdmin): list_per_page = 10 def check_results_order(ascending=False): custom_site.register(OrderedObject, OrderedObjectAdmin) model_admin = OrderedObjectAdmin(OrderedObject, custom_site) counter = 0 if ascending else 51 for page in range(1, 6): request = self._mocked_authenticated_request( "/orderedobject/?p=%s" % page, superuser ) response = model_admin.changelist_view(request) for result in response.context_data["cl"].result_list: counter += 1 if ascending else -1 self.assertEqual(result.id, counter) custom_site.unregister(OrderedObject) # When no order is defined at all, use the model's default ordering # (i.e. 'number'). check_results_order(ascending=True) # When an order field is defined but multiple records have the same # value for that field, make sure everything gets ordered by -pk as well. OrderedObjectAdmin.ordering = ["bool"] check_results_order() # When order fields are defined, including the pk itself, use them. OrderedObjectAdmin.ordering = ["bool", "-pk"] check_results_order() OrderedObjectAdmin.ordering = ["bool", "pk"] check_results_order(ascending=True) OrderedObjectAdmin.ordering = ["-id", "bool"] check_results_order() OrderedObjectAdmin.ordering = ["id", "bool"] check_results_order(ascending=True) @isolate_apps("admin_changelist") def test_total_ordering_optimization(self): class Related(models.Model): unique_field = models.BooleanField(unique=True) class Meta: ordering = ("unique_field",) class Model(models.Model): unique_field = models.BooleanField(unique=True) unique_nullable_field = models.BooleanField(unique=True, null=True) related = models.ForeignKey(Related, models.CASCADE) other_related = models.ForeignKey(Related, models.CASCADE) related_unique = models.OneToOneField(Related, models.CASCADE) field = models.BooleanField() other_field = models.BooleanField() null_field = models.BooleanField(null=True) class Meta: unique_together = { ("field", "other_field"), ("field", "null_field"), ("related", "other_related_id"), } class ModelAdmin(admin.ModelAdmin): def get_queryset(self, request): return Model.objects.none() request = self._mocked_authenticated_request("/", self.superuser) site = admin.AdminSite(name="admin") model_admin = ModelAdmin(Model, site) change_list = model_admin.get_changelist_instance(request) tests = ( ([], ["-pk"]), # Unique non-nullable field. (["unique_field"], ["unique_field"]), (["-unique_field"], ["-unique_field"]), # Unique nullable field. (["unique_nullable_field"], ["unique_nullable_field", "-pk"]), # Field. (["field"], ["field", "-pk"]), # Related field introspection is not implemented. (["related__unique_field"], ["related__unique_field", "-pk"]), # Related attname unique. (["related_unique_id"], ["related_unique_id"]), # Related ordering introspection is not implemented. (["related_unique"], ["related_unique", "-pk"]), # Composite unique. (["field", "-other_field"], ["field", "-other_field"]), # Composite unique nullable. (["-field", "null_field"], ["-field", "null_field", "-pk"]), # Composite unique and nullable. ( ["-field", "null_field", "other_field"], ["-field", "null_field", "other_field"], ), # Composite unique attnames. (["related_id", "-other_related_id"], ["related_id", "-other_related_id"]), # Composite unique names. (["related", "-other_related_id"], ["related", "-other_related_id", "-pk"]), ) # F() objects composite unique. total_ordering = [F("field"), F("other_field").desc(nulls_last=True)] # F() objects composite unique nullable. non_total_ordering = [F("field"), F("null_field").desc(nulls_last=True)] tests += ( (total_ordering, total_ordering), (non_total_ordering, non_total_ordering + ["-pk"]), ) for ordering, expected in tests: with self.subTest(ordering=ordering): self.assertEqual( change_list._get_deterministic_ordering(ordering), expected ) @isolate_apps("admin_changelist") def test_total_ordering_optimization_meta_constraints(self): class Related(models.Model): unique_field = models.BooleanField(unique=True) class Meta: ordering = ("unique_field",) class Model(models.Model): field_1 = models.BooleanField() field_2 = models.BooleanField() field_3 = models.BooleanField() field_4 = models.BooleanField() field_5 = models.BooleanField() field_6 = models.BooleanField() nullable_1 = models.BooleanField(null=True) nullable_2 = models.BooleanField(null=True) related_1 = models.ForeignKey(Related, models.CASCADE) related_2 = models.ForeignKey(Related, models.CASCADE) related_3 = models.ForeignKey(Related, models.CASCADE) related_4 = models.ForeignKey(Related, models.CASCADE) class Meta: constraints = [ *[ models.UniqueConstraint(fields=fields, name="".join(fields)) for fields in ( ["field_1"], ["nullable_1"], ["related_1"], ["related_2_id"], ["field_2", "field_3"], ["field_2", "nullable_2"], ["field_2", "related_3"], ["field_3", "related_4_id"], ) ], models.CheckConstraint(check=models.Q(id__gt=0), name="foo"), models.UniqueConstraint( fields=["field_5"], condition=models.Q(id__gt=10), name="total_ordering_1", ), models.UniqueConstraint( fields=["field_6"], condition=models.Q(), name="total_ordering", ), ] class ModelAdmin(admin.ModelAdmin): def get_queryset(self, request): return Model.objects.none() request = self._mocked_authenticated_request("/", self.superuser) site = admin.AdminSite(name="admin") model_admin = ModelAdmin(Model, site) change_list = model_admin.get_changelist_instance(request) tests = ( # Unique non-nullable field. (["field_1"], ["field_1"]), # Unique nullable field. (["nullable_1"], ["nullable_1", "-pk"]), # Related attname unique. (["related_1_id"], ["related_1_id"]), (["related_2_id"], ["related_2_id"]), # Related ordering introspection is not implemented. (["related_1"], ["related_1", "-pk"]), # Composite unique. (["-field_2", "field_3"], ["-field_2", "field_3"]), # Composite unique nullable. (["field_2", "-nullable_2"], ["field_2", "-nullable_2", "-pk"]), # Composite unique and nullable. ( ["field_2", "-nullable_2", "field_3"], ["field_2", "-nullable_2", "field_3"], ), # Composite field and related field name. (["field_2", "-related_3"], ["field_2", "-related_3", "-pk"]), (["field_3", "related_4"], ["field_3", "related_4", "-pk"]), # Composite field and related field attname. (["field_2", "related_3_id"], ["field_2", "related_3_id"]), (["field_3", "-related_4_id"], ["field_3", "-related_4_id"]), # Partial unique constraint is ignored. (["field_5"], ["field_5", "-pk"]), # Unique constraint with an empty condition. (["field_6"], ["field_6"]), ) for ordering, expected in tests: with self.subTest(ordering=ordering): self.assertEqual( change_list._get_deterministic_ordering(ordering), expected ) def test_dynamic_list_filter(self): """ Regression tests for ticket #17646: dynamic list_filter support. """ parent = Parent.objects.create(name="parent") for i in range(10): Child.objects.create(name="child %s" % i, parent=parent) user_noparents = self._create_superuser("noparents") user_parents = self._create_superuser("parents") # Test with user 'noparents' m = DynamicListFilterChildAdmin(Child, custom_site) request = self._mocked_authenticated_request("/child/", user_noparents) response = m.changelist_view(request) self.assertEqual(response.context_data["cl"].list_filter, ["name", "age"]) # Test with user 'parents' m = DynamicListFilterChildAdmin(Child, custom_site) request = self._mocked_authenticated_request("/child/", user_parents) response = m.changelist_view(request) self.assertEqual( response.context_data["cl"].list_filter, ("parent", "name", "age") ) def test_dynamic_search_fields(self): child = self._create_superuser("child") m = DynamicSearchFieldsChildAdmin(Child, custom_site) request = self._mocked_authenticated_request("/child/", child) response = m.changelist_view(request) self.assertEqual(response.context_data["cl"].search_fields, ("name", "age")) def test_pagination_page_range(self): """ Regression tests for ticket #15653: ensure the number of pages generated for changelist views are correct. """ # instantiating and setting up ChangeList object m = GroupAdmin(Group, custom_site) request = self.factory.get("/group/") request.user = self.superuser cl = m.get_changelist_instance(request) cl.list_per_page = 10 ELLIPSIS = cl.paginator.ELLIPSIS for number, pages, expected in [ (1, 1, []), (1, 2, [1, 2]), (6, 11, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]), (6, 12, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), (6, 13, [1, 2, 3, 4, 5, 6, 7, 8, 9, ELLIPSIS, 12, 13]), (7, 12, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), (7, 13, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]), (7, 14, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ELLIPSIS, 13, 14]), (8, 13, [1, 2, ELLIPSIS, 5, 6, 7, 8, 9, 10, 11, 12, 13]), (8, 14, [1, 2, ELLIPSIS, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]), (8, 15, [1, 2, ELLIPSIS, 5, 6, 7, 8, 9, 10, 11, ELLIPSIS, 14, 15]), ]: with self.subTest(number=number, pages=pages): # assuming exactly `pages * cl.list_per_page` objects Group.objects.all().delete() for i in range(pages * cl.list_per_page): Group.objects.create(name="test band") # setting page number and calculating page range cl.page_num = number cl.get_results(request) self.assertEqual(list(pagination(cl)["page_range"]), expected) def test_object_tools_displayed_no_add_permission(self): """ When ModelAdmin.has_add_permission() returns False, the object-tools block is still shown. """ superuser = self._create_superuser("superuser") m = EventAdmin(Event, custom_site) request = self._mocked_authenticated_request("/event/", superuser) self.assertFalse(m.has_add_permission(request)) response = m.changelist_view(request) self.assertIn('<ul class="object-tools">', response.rendered_content) # The "Add" button inside the object-tools shouldn't appear. self.assertNotIn("Add ", response.rendered_content) def test_search_help_text(self): superuser = self._create_superuser("superuser") m = BandAdmin(Band, custom_site) # search_fields without search_help_text. m.search_fields = ["name"] request = self._mocked_authenticated_request("/band/", superuser) response = m.changelist_view(request) self.assertIsNone(response.context_data["cl"].search_help_text) self.assertNotContains(response, '<div class="help id="searchbar_helptext">') # search_fields with search_help_text. m.search_help_text = "Search help text" request = self._mocked_authenticated_request("/band/", superuser) response = m.changelist_view(request) self.assertEqual( response.context_data["cl"].search_help_text, "Search help text" ) self.assertContains( response, '<div class="help" id="searchbar_helptext">Search help text</div>' ) self.assertContains( response, '<input type="text" size="40" name="q" value="" id="searchbar" ' 'aria-describedby="searchbar_helptext">', ) def test_search_bar_total_link_preserves_options(self): self.client.force_login(self.superuser) url = reverse("admin:auth_user_changelist") for data, href in ( ({"is_staff__exact": "0"}, "?"), ({"is_staff__exact": "0", IS_POPUP_VAR: "1"}, f"?{IS_POPUP_VAR}=1"), ({"is_staff__exact": "0", IS_FACETS_VAR: ""}, f"?{IS_FACETS_VAR}"), ( {"is_staff__exact": "0", IS_POPUP_VAR: "1", IS_FACETS_VAR: ""}, f"?{IS_POPUP_VAR}=1&{IS_FACETS_VAR}", ), ): with self.subTest(data=data): response = self.client.get(url, data=data) self.assertContains( response, f'0 results (<a href="{href}">1 total</a>)' ) class GetAdminLogTests(TestCase): def test_custom_user_pk_not_named_id(self): """ {% get_admin_log %} works if the user model's primary key isn't named 'id'. """ context = Context( { "user": CustomIdUser(), "log_entries": LogEntry.objects.all(), } ) template = Template( "{% load log %}{% get_admin_log 10 as admin_log for_user user %}" ) # This template tag just logs. self.assertEqual(template.render(context), "") def test_no_user(self): """{% get_admin_log %} works without specifying a user.""" user = User(username="jondoe", password="secret", email="[email protected]") user.save() ct = ContentType.objects.get_for_model(User) LogEntry.objects.log_action(user.pk, ct.pk, user.pk, repr(user), 1) context = Context({"log_entries": LogEntry.objects.all()}) t = Template( "{% load log %}" "{% get_admin_log 100 as admin_log %}" "{% for entry in admin_log %}" "{{ entry|safe }}" "{% endfor %}" ) self.assertEqual(t.render(context), "Added “<User: jondoe>”.") def test_missing_args(self): msg = "'get_admin_log' statements require two arguments" with self.assertRaisesMessage(TemplateSyntaxError, msg): Template("{% load log %}{% get_admin_log 10 as %}") def test_non_integer_limit(self): msg = "First argument to 'get_admin_log' must be an integer" with self.assertRaisesMessage(TemplateSyntaxError, msg): Template( '{% load log %}{% get_admin_log "10" as admin_log for_user user %}' ) def test_without_as(self): msg = "Second argument to 'get_admin_log' must be 'as'" with self.assertRaisesMessage(TemplateSyntaxError, msg): Template("{% load log %}{% get_admin_log 10 ad admin_log for_user user %}") def test_without_for_user(self): msg = "Fourth argument to 'get_admin_log' must be 'for_user'" with self.assertRaisesMessage(TemplateSyntaxError, msg): Template("{% load log %}{% get_admin_log 10 as admin_log foruser user %}") @override_settings(ROOT_URLCONF="admin_changelist.urls") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_changelist"] + AdminSeleniumTestCase.available_apps def setUp(self): User.objects.create_superuser(username="super", password="secret", email=None) def test_add_row_selection(self): """ The status line for selected rows gets updated correctly (#22038). """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get(self.live_server_url + reverse("admin:auth_user_changelist")) form_id = "#changelist-form" # Test amount of rows in the Changelist rows = self.selenium.find_elements( By.CSS_SELECTOR, "%s #result_list tbody tr" % form_id ) self.assertEqual(len(rows), 1) row = rows[0] selection_indicator = self.selenium.find_element( By.CSS_SELECTOR, "%s .action-counter" % form_id ) all_selector = self.selenium.find_element(By.ID, "action-toggle") row_selector = self.selenium.find_element( By.CSS_SELECTOR, "%s #result_list tbody tr:first-child .action-select" % form_id, ) # Test current selection self.assertEqual(selection_indicator.text, "0 of 1 selected") self.assertIs(all_selector.get_property("checked"), False) self.assertEqual(row.get_attribute("class"), "") # Select a row and check again row_selector.click() self.assertEqual(selection_indicator.text, "1 of 1 selected") self.assertIs(all_selector.get_property("checked"), True) self.assertEqual(row.get_attribute("class"), "selected") # Deselect a row and check again row_selector.click() self.assertEqual(selection_indicator.text, "0 of 1 selected") self.assertIs(all_selector.get_property("checked"), False) self.assertEqual(row.get_attribute("class"), "") def test_modifier_allows_multiple_section(self): """ Selecting a row and then selecting another row whilst holding shift should select all rows in-between. """ from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys Parent.objects.bulk_create([Parent(name="parent%d" % i) for i in range(5)]) self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_changelist_parent_changelist") ) checkboxes = self.selenium.find_elements( By.CSS_SELECTOR, "tr input.action-select" ) self.assertEqual(len(checkboxes), 5) for c in checkboxes: self.assertIs(c.get_property("checked"), False) # Check first row. Hold-shift and check next-to-last row. checkboxes[0].click() ActionChains(self.selenium).key_down(Keys.SHIFT).click(checkboxes[-2]).key_up( Keys.SHIFT ).perform() for c in checkboxes[:-2]: self.assertIs(c.get_property("checked"), True) self.assertIs(checkboxes[-1].get_property("checked"), False) def test_select_all_across_pages(self): from selenium.webdriver.common.by import By Parent.objects.bulk_create([Parent(name="parent%d" % i) for i in range(101)]) self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_changelist_parent_changelist") ) selection_indicator = self.selenium.find_element( By.CSS_SELECTOR, ".action-counter" ) select_all_indicator = self.selenium.find_element( By.CSS_SELECTOR, ".actions .all" ) question = self.selenium.find_element(By.CSS_SELECTOR, ".actions > .question") clear = self.selenium.find_element(By.CSS_SELECTOR, ".actions > .clear") select_all = self.selenium.find_element(By.ID, "action-toggle") select_across = self.selenium.find_elements(By.NAME, "select_across") self.assertIs(question.is_displayed(), False) self.assertIs(clear.is_displayed(), False) self.assertIs(select_all.get_property("checked"), False) for hidden_input in select_across: self.assertEqual(hidden_input.get_property("value"), "0") self.assertIs(selection_indicator.is_displayed(), True) self.assertEqual(selection_indicator.text, "0 of 100 selected") self.assertIs(select_all_indicator.is_displayed(), False) select_all.click() self.assertIs(question.is_displayed(), True) self.assertIs(clear.is_displayed(), False) self.assertIs(select_all.get_property("checked"), True) for hidden_input in select_across: self.assertEqual(hidden_input.get_property("value"), "0") self.assertIs(selection_indicator.is_displayed(), True) self.assertEqual(selection_indicator.text, "100 of 100 selected") self.assertIs(select_all_indicator.is_displayed(), False) question.click() self.assertIs(question.is_displayed(), False) self.assertIs(clear.is_displayed(), True) self.assertIs(select_all.get_property("checked"), True) for hidden_input in select_across: self.assertEqual(hidden_input.get_property("value"), "1") self.assertIs(selection_indicator.is_displayed(), False) self.assertIs(select_all_indicator.is_displayed(), True) clear.click() self.assertIs(question.is_displayed(), False) self.assertIs(clear.is_displayed(), False) self.assertIs(select_all.get_property("checked"), False) for hidden_input in select_across: self.assertEqual(hidden_input.get_property("value"), "0") self.assertIs(selection_indicator.is_displayed(), True) self.assertEqual(selection_indicator.text, "0 of 100 selected") self.assertIs(select_all_indicator.is_displayed(), False) def test_actions_warn_on_pending_edits(self): from selenium.webdriver.common.by import By Parent.objects.create(name="foo") self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_changelist_parent_changelist") ) name_input = self.selenium.find_element(By.ID, "id_form-0-name") name_input.clear() name_input.send_keys("bar") self.selenium.find_element(By.ID, "action-toggle").click() self.selenium.find_element(By.NAME, "index").click() # Go alert = self.selenium.switch_to.alert try: self.assertEqual( alert.text, "You have unsaved changes on individual editable fields. If you " "run an action, your unsaved changes will be lost.", ) finally: alert.dismiss() def test_save_with_changes_warns_on_pending_action(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select Parent.objects.create(name="parent") self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_changelist_parent_changelist") ) name_input = self.selenium.find_element(By.ID, "id_form-0-name") name_input.clear() name_input.send_keys("other name") Select(self.selenium.find_element(By.NAME, "action")).select_by_value( "delete_selected" ) self.selenium.find_element(By.NAME, "_save").click() alert = self.selenium.switch_to.alert try: self.assertEqual( alert.text, "You have selected an action, but you haven’t saved your " "changes to individual fields yet. Please click OK to save. " "You’ll need to re-run the action.", ) finally: alert.dismiss() def test_save_without_changes_warns_on_pending_action(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select Parent.objects.create(name="parent") self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_changelist_parent_changelist") ) Select(self.selenium.find_element(By.NAME, "action")).select_by_value( "delete_selected" ) self.selenium.find_element(By.NAME, "_save").click() alert = self.selenium.switch_to.alert try: self.assertEqual( alert.text, "You have selected an action, and you haven’t made any " "changes on individual fields. You’re probably looking for " "the Go button rather than the Save button.", ) finally: alert.dismiss() def test_collapse_filters(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get(self.live_server_url + reverse("admin:auth_user_changelist")) # The UserAdmin has 3 field filters by default: "staff status", # "superuser status", and "active". details = self.selenium.find_elements(By.CSS_SELECTOR, "details") # All filters are opened at first. for detail in details: self.assertTrue(detail.get_attribute("open")) # Collapse "staff' and "superuser" filters. for detail in details[:2]: summary = detail.find_element(By.CSS_SELECTOR, "summary") summary.click() self.assertFalse(detail.get_attribute("open")) # Filters are in the same state after refresh. self.selenium.refresh() self.assertFalse( self.selenium.find_element( By.CSS_SELECTOR, "[data-filter-title='staff status']" ).get_attribute("open") ) self.assertFalse( self.selenium.find_element( By.CSS_SELECTOR, "[data-filter-title='superuser status']" ).get_attribute("open") ) self.assertTrue( self.selenium.find_element( By.CSS_SELECTOR, "[data-filter-title='active']" ).get_attribute("open") ) # Collapse a filter on another view (Bands). self.selenium.get( self.live_server_url + reverse("admin:admin_changelist_band_changelist") ) self.selenium.find_element(By.CSS_SELECTOR, "summary").click() # Go to Users view and then, back again to Bands view. self.selenium.get(self.live_server_url + reverse("admin:auth_user_changelist")) self.selenium.get( self.live_server_url + reverse("admin:admin_changelist_band_changelist") ) # The filter remains in the same state. self.assertFalse( self.selenium.find_element( By.CSS_SELECTOR, "[data-filter-title='number of members']", ).get_attribute("open") ) def test_collapse_filter_with_unescaped_title(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") changelist_url = reverse("admin:admin_changelist_proxyuser_changelist") self.selenium.get(self.live_server_url + changelist_url) # Title is escaped. filter_title = self.selenium.find_element( By.CSS_SELECTOR, "[data-filter-title='It\\'s OK']" ) filter_title.find_element(By.CSS_SELECTOR, "summary").click() self.assertFalse(filter_title.get_attribute("open")) # Filter is in the same state after refresh. self.selenium.refresh() self.assertFalse( self.selenium.find_element( By.CSS_SELECTOR, "[data-filter-title='It\\'s OK']" ).get_attribute("open") )
c4bab9b24f6b666c7d315f9199f4f9cd3ebf94222f741791885d4928baa318b8
import functools import re from collections import defaultdict from graphlib import TopologicalSorter from itertools import chain from django.conf import settings from django.db import models from django.db.migrations import operations from django.db.migrations.migration import Migration from django.db.migrations.operations.models import AlterModelOptions from django.db.migrations.optimizer import MigrationOptimizer from django.db.migrations.questioner import MigrationQuestioner from django.db.migrations.utils import ( COMPILED_REGEX_TYPE, RegexObject, resolve_relation, ) class MigrationAutodetector: """ Take a pair of ProjectStates and compare them to see what the first would need doing to make it match the second (the second usually being the project's current state). Note that this naturally operates on entire projects at a time, as it's likely that changes interact (for example, you can't add a ForeignKey without having a migration to add the table it depends on first). A user interface may offer single-app usage if it wishes, with the caveat that it may not always be possible. """ def __init__(self, from_state, to_state, questioner=None): self.from_state = from_state self.to_state = to_state self.questioner = questioner or MigrationQuestioner() self.existing_apps = {app for app, model in from_state.models} def changes(self, graph, trim_to_apps=None, convert_apps=None, migration_name=None): """ Main entry point to produce a list of applicable changes. Take a graph to base names on and an optional set of apps to try and restrict to (restriction is not guaranteed) """ changes = self._detect_changes(convert_apps, graph) changes = self.arrange_for_graph(changes, graph, migration_name) if trim_to_apps: changes = self._trim_to_apps(changes, trim_to_apps) return changes def deep_deconstruct(self, obj): """ Recursive deconstruction for a field and its arguments. Used for full comparison for rename/alter; sometimes a single-level deconstruction will not compare correctly. """ if isinstance(obj, list): return [self.deep_deconstruct(value) for value in obj] elif isinstance(obj, tuple): return tuple(self.deep_deconstruct(value) for value in obj) elif isinstance(obj, dict): return {key: self.deep_deconstruct(value) for key, value in obj.items()} elif isinstance(obj, functools.partial): return ( obj.func, self.deep_deconstruct(obj.args), self.deep_deconstruct(obj.keywords), ) elif isinstance(obj, COMPILED_REGEX_TYPE): return RegexObject(obj) elif isinstance(obj, type): # If this is a type that implements 'deconstruct' as an instance method, # avoid treating this as being deconstructible itself - see #22951 return obj elif hasattr(obj, "deconstruct"): deconstructed = obj.deconstruct() if isinstance(obj, models.Field): # we have a field which also returns a name deconstructed = deconstructed[1:] path, args, kwargs = deconstructed return ( path, [self.deep_deconstruct(value) for value in args], {key: self.deep_deconstruct(value) for key, value in kwargs.items()}, ) else: return obj def only_relation_agnostic_fields(self, fields): """ Return a definition of the fields that ignores field names and what related fields actually relate to. Used for detecting renames (as the related fields change during renames). """ fields_def = [] for name, field in sorted(fields.items()): deconstruction = self.deep_deconstruct(field) if field.remote_field and field.remote_field.model: deconstruction[2].pop("to", None) fields_def.append(deconstruction) return fields_def def _detect_changes(self, convert_apps=None, graph=None): """ Return a dict of migration plans which will achieve the change from from_state to to_state. The dict has app labels as keys and a list of migrations as values. The resulting migrations aren't specially named, but the names do matter for dependencies inside the set. convert_apps is the list of apps to convert to use migrations (i.e. to make initial migrations for, in the usual case) graph is an optional argument that, if provided, can help improve dependency generation and avoid potential circular dependencies. """ # The first phase is generating all the operations for each app # and gathering them into a big per-app list. # Then go through that list, order it, and split into migrations to # resolve dependencies caused by M2Ms and FKs. self.generated_operations = {} self.altered_indexes = {} self.altered_constraints = {} self.renamed_fields = {} # Prepare some old/new state and model lists, separating # proxy models and ignoring unmigrated apps. self.old_model_keys = set() self.old_proxy_keys = set() self.old_unmanaged_keys = set() self.new_model_keys = set() self.new_proxy_keys = set() self.new_unmanaged_keys = set() for (app_label, model_name), model_state in self.from_state.models.items(): if not model_state.options.get("managed", True): self.old_unmanaged_keys.add((app_label, model_name)) elif app_label not in self.from_state.real_apps: if model_state.options.get("proxy"): self.old_proxy_keys.add((app_label, model_name)) else: self.old_model_keys.add((app_label, model_name)) for (app_label, model_name), model_state in self.to_state.models.items(): if not model_state.options.get("managed", True): self.new_unmanaged_keys.add((app_label, model_name)) elif app_label not in self.from_state.real_apps or ( convert_apps and app_label in convert_apps ): if model_state.options.get("proxy"): self.new_proxy_keys.add((app_label, model_name)) else: self.new_model_keys.add((app_label, model_name)) self.from_state.resolve_fields_and_relations() self.to_state.resolve_fields_and_relations() # Renames have to come first self.generate_renamed_models() # Prepare lists of fields and generate through model map self._prepare_field_lists() self._generate_through_model_map() # Generate non-rename model operations self.generate_deleted_models() self.generate_created_models() self.generate_deleted_proxies() self.generate_created_proxies() self.generate_altered_options() self.generate_altered_managers() self.generate_altered_db_table_comment() # Create the renamed fields and store them in self.renamed_fields. # They are used by create_altered_indexes(), generate_altered_fields(), # generate_removed_altered_index/unique_together(), and # generate_altered_index/unique_together(). self.create_renamed_fields() # Create the altered indexes and store them in self.altered_indexes. # This avoids the same computation in generate_removed_indexes() # and generate_added_indexes(). self.create_altered_indexes() self.create_altered_constraints() # Generate index removal operations before field is removed self.generate_removed_constraints() self.generate_removed_indexes() # Generate field renaming operations. self.generate_renamed_fields() self.generate_renamed_indexes() # Generate removal of foo together. self.generate_removed_altered_unique_together() self.generate_removed_altered_index_together() # RemovedInDjango51Warning. # Generate field operations. self.generate_removed_fields() self.generate_added_fields() self.generate_altered_fields() self.generate_altered_order_with_respect_to() self.generate_altered_unique_together() self.generate_altered_index_together() # RemovedInDjango51Warning. self.generate_added_indexes() self.generate_added_constraints() self.generate_altered_db_table() self._sort_migrations() self._build_migration_list(graph) self._optimize_migrations() return self.migrations def _prepare_field_lists(self): """ Prepare field lists and a list of the fields that used through models in the old state so dependencies can be made from the through model deletion to the field that uses it. """ self.kept_model_keys = self.old_model_keys & self.new_model_keys self.kept_proxy_keys = self.old_proxy_keys & self.new_proxy_keys self.kept_unmanaged_keys = self.old_unmanaged_keys & self.new_unmanaged_keys self.through_users = {} self.old_field_keys = { (app_label, model_name, field_name) for app_label, model_name in self.kept_model_keys for field_name in self.from_state.models[ app_label, self.renamed_models.get((app_label, model_name), model_name) ].fields } self.new_field_keys = { (app_label, model_name, field_name) for app_label, model_name in self.kept_model_keys for field_name in self.to_state.models[app_label, model_name].fields } def _generate_through_model_map(self): """Through model map generation.""" for app_label, model_name in sorted(self.old_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] for field_name, field in old_model_state.fields.items(): if hasattr(field, "remote_field") and getattr( field.remote_field, "through", None ): through_key = resolve_relation( field.remote_field.through, app_label, model_name ) self.through_users[through_key] = ( app_label, old_model_name, field_name, ) @staticmethod def _resolve_dependency(dependency): """ Return the resolved dependency and a boolean denoting whether or not it was swappable. """ if dependency[0] != "__setting__": return dependency, False resolved_app_label, resolved_object_name = getattr( settings, dependency[1] ).split(".") return (resolved_app_label, resolved_object_name.lower()) + dependency[2:], True def _build_migration_list(self, graph=None): """ Chop the lists of operations up into migrations with dependencies on each other. Do this by going through an app's list of operations until one is found that has an outgoing dependency that isn't in another app's migration yet (hasn't been chopped off its list). Then chop off the operations before it into a migration and move onto the next app. If the loops completes without doing anything, there's a circular dependency (which _should_ be impossible as the operations are all split at this point so they can't depend and be depended on). """ self.migrations = {} num_ops = sum(len(x) for x in self.generated_operations.values()) chop_mode = False while num_ops: # On every iteration, we step through all the apps and see if there # is a completed set of operations. # If we find that a subset of the operations are complete we can # try to chop it off from the rest and continue, but we only # do this if we've already been through the list once before # without any chopping and nothing has changed. for app_label in sorted(self.generated_operations): chopped = [] dependencies = set() for operation in list(self.generated_operations[app_label]): deps_satisfied = True operation_dependencies = set() for dep in operation._auto_deps: # Temporarily resolve the swappable dependency to # prevent circular references. While keeping the # dependency checks on the resolved model, add the # swappable dependencies. original_dep = dep dep, is_swappable_dep = self._resolve_dependency(dep) if dep[0] != app_label: # External app dependency. See if it's not yet # satisfied. for other_operation in self.generated_operations.get( dep[0], [] ): if self.check_dependency(other_operation, dep): deps_satisfied = False break if not deps_satisfied: break else: if is_swappable_dep: operation_dependencies.add( (original_dep[0], original_dep[1]) ) elif dep[0] in self.migrations: operation_dependencies.add( (dep[0], self.migrations[dep[0]][-1].name) ) else: # If we can't find the other app, we add a # first/last dependency, but only if we've # already been through once and checked # everything. if chop_mode: # If the app already exists, we add a # dependency on the last migration, as # we don't know which migration # contains the target field. If it's # not yet migrated or has no # migrations, we use __first__. if graph and graph.leaf_nodes(dep[0]): operation_dependencies.add( graph.leaf_nodes(dep[0])[0] ) else: operation_dependencies.add( (dep[0], "__first__") ) else: deps_satisfied = False if deps_satisfied: chopped.append(operation) dependencies.update(operation_dependencies) del self.generated_operations[app_label][0] else: break # Make a migration! Well, only if there's stuff to put in it if dependencies or chopped: if not self.generated_operations[app_label] or chop_mode: subclass = type( "Migration", (Migration,), {"operations": [], "dependencies": []}, ) instance = subclass( "auto_%i" % (len(self.migrations.get(app_label, [])) + 1), app_label, ) instance.dependencies = list(dependencies) instance.operations = chopped instance.initial = app_label not in self.existing_apps self.migrations.setdefault(app_label, []).append(instance) chop_mode = False else: self.generated_operations[app_label] = ( chopped + self.generated_operations[app_label] ) new_num_ops = sum(len(x) for x in self.generated_operations.values()) if new_num_ops == num_ops: if not chop_mode: chop_mode = True else: raise ValueError( "Cannot resolve operation dependencies: %r" % self.generated_operations ) num_ops = new_num_ops def _sort_migrations(self): """ Reorder to make things possible. Reordering may be needed so FKs work nicely inside the same app. """ for app_label, ops in sorted(self.generated_operations.items()): ts = TopologicalSorter() for op in ops: ts.add(op) for dep in op._auto_deps: # Resolve intra-app dependencies to handle circular # references involving a swappable model. dep = self._resolve_dependency(dep)[0] if dep[0] != app_label: continue ts.add(op, *(x for x in ops if self.check_dependency(x, dep))) self.generated_operations[app_label] = list(ts.static_order()) def _optimize_migrations(self): # Add in internal dependencies among the migrations for app_label, migrations in self.migrations.items(): for m1, m2 in zip(migrations, migrations[1:]): m2.dependencies.append((app_label, m1.name)) # De-dupe dependencies for migrations in self.migrations.values(): for migration in migrations: migration.dependencies = list(set(migration.dependencies)) # Optimize migrations for app_label, migrations in self.migrations.items(): for migration in migrations: migration.operations = MigrationOptimizer().optimize( migration.operations, app_label ) def check_dependency(self, operation, dependency): """ Return True if the given operation depends on the given dependency, False otherwise. """ # Created model if dependency[2] is None and dependency[3] is True: return ( isinstance(operation, operations.CreateModel) and operation.name_lower == dependency[1].lower() ) # Created field elif dependency[2] is not None and dependency[3] is True: return ( isinstance(operation, operations.CreateModel) and operation.name_lower == dependency[1].lower() and any(dependency[2] == x for x, y in operation.fields) ) or ( isinstance(operation, operations.AddField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # Removed field elif dependency[2] is not None and dependency[3] is False: return ( isinstance(operation, operations.RemoveField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # Removed model elif dependency[2] is None and dependency[3] is False: return ( isinstance(operation, operations.DeleteModel) and operation.name_lower == dependency[1].lower() ) # Field being altered elif dependency[2] is not None and dependency[3] == "alter": return ( isinstance(operation, operations.AlterField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # order_with_respect_to being unset for a field elif dependency[2] is not None and dependency[3] == "order_wrt_unset": return ( isinstance(operation, operations.AlterOrderWithRespectTo) and operation.name_lower == dependency[1].lower() and (operation.order_with_respect_to or "").lower() != dependency[2].lower() ) # Field is removed and part of an index/unique_together elif dependency[2] is not None and dependency[3] == "foo_together_change": return ( isinstance( operation, (operations.AlterUniqueTogether, operations.AlterIndexTogether), ) and operation.name_lower == dependency[1].lower() ) # Unknown dependency. Raise an error. else: raise ValueError("Can't handle dependency %r" % (dependency,)) def add_operation(self, app_label, operation, dependencies=None, beginning=False): # Dependencies are # (app_label, model_name, field_name, create/delete as True/False) operation._auto_deps = dependencies or [] if beginning: self.generated_operations.setdefault(app_label, []).insert(0, operation) else: self.generated_operations.setdefault(app_label, []).append(operation) def swappable_first_key(self, item): """ Place potential swappable models first in lists of created models (only real way to solve #22783). """ try: model_state = self.to_state.models[item] base_names = { base if isinstance(base, str) else base.__name__ for base in model_state.bases } string_version = "%s.%s" % (item[0], item[1]) if ( model_state.options.get("swappable") or "AbstractUser" in base_names or "AbstractBaseUser" in base_names or settings.AUTH_USER_MODEL.lower() == string_version.lower() ): return ("___" + item[0], "___" + item[1]) except LookupError: pass return item def generate_renamed_models(self): """ Find any renamed models, generate the operations for them, and remove the old entry from the model lists. Must be run before other model-level generation. """ self.renamed_models = {} self.renamed_models_rel = {} added_models = self.new_model_keys - self.old_model_keys for app_label, model_name in sorted(added_models): model_state = self.to_state.models[app_label, model_name] model_fields_def = self.only_relation_agnostic_fields(model_state.fields) removed_models = self.old_model_keys - self.new_model_keys for rem_app_label, rem_model_name in removed_models: if rem_app_label == app_label: rem_model_state = self.from_state.models[ rem_app_label, rem_model_name ] rem_model_fields_def = self.only_relation_agnostic_fields( rem_model_state.fields ) if model_fields_def == rem_model_fields_def: if self.questioner.ask_rename_model( rem_model_state, model_state ): dependencies = [] fields = list(model_state.fields.values()) + [ field.remote_field for relations in self.to_state.relations[ app_label, model_name ].values() for field in relations.values() ] for field in fields: if field.is_relation: dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) ) self.add_operation( app_label, operations.RenameModel( old_name=rem_model_state.name, new_name=model_state.name, ), dependencies=dependencies, ) self.renamed_models[app_label, model_name] = rem_model_name renamed_models_rel_key = "%s.%s" % ( rem_model_state.app_label, rem_model_state.name_lower, ) self.renamed_models_rel[ renamed_models_rel_key ] = "%s.%s" % ( model_state.app_label, model_state.name_lower, ) self.old_model_keys.remove((rem_app_label, rem_model_name)) self.old_model_keys.add((app_label, model_name)) break def generate_created_models(self): """ Find all new models (both managed and unmanaged) and make create operations for them as well as separate operations to create any foreign key or M2M relationships (these are optimized later, if possible). Defer any model options that refer to collections of fields that might be deferred (e.g. unique_together, index_together). """ old_keys = self.old_model_keys | self.old_unmanaged_keys added_models = self.new_model_keys - old_keys added_unmanaged_models = self.new_unmanaged_keys - old_keys all_added_models = chain( sorted(added_models, key=self.swappable_first_key, reverse=True), sorted(added_unmanaged_models, key=self.swappable_first_key, reverse=True), ) for app_label, model_name in all_added_models: model_state = self.to_state.models[app_label, model_name] # Gather related fields related_fields = {} primary_key_rel = None for field_name, field in model_state.fields.items(): if field.remote_field: if field.remote_field.model: if field.primary_key: primary_key_rel = field.remote_field.model elif not field.remote_field.parent_link: related_fields[field_name] = field if getattr(field.remote_field, "through", None): related_fields[field_name] = field # Are there indexes/unique|index_together to defer? indexes = model_state.options.pop("indexes") constraints = model_state.options.pop("constraints") unique_together = model_state.options.pop("unique_together", None) # RemovedInDjango51Warning. index_together = model_state.options.pop("index_together", None) order_with_respect_to = model_state.options.pop( "order_with_respect_to", None ) # Depend on the deletion of any possible proxy version of us dependencies = [ (app_label, model_name, None, False), ] # Depend on all bases for base in model_state.bases: if isinstance(base, str) and "." in base: base_app_label, base_name = base.split(".", 1) dependencies.append((base_app_label, base_name, None, True)) # Depend on the removal of base fields if the new model has # a field with the same name. old_base_model_state = self.from_state.models.get( (base_app_label, base_name) ) new_base_model_state = self.to_state.models.get( (base_app_label, base_name) ) if old_base_model_state and new_base_model_state: removed_base_fields = ( set(old_base_model_state.fields) .difference( new_base_model_state.fields, ) .intersection(model_state.fields) ) for removed_base_field in removed_base_fields: dependencies.append( (base_app_label, base_name, removed_base_field, False) ) # Depend on the other end of the primary key if it's a relation if primary_key_rel: dependencies.append( resolve_relation( primary_key_rel, app_label, model_name, ) + (None, True) ) # Generate creation operation self.add_operation( app_label, operations.CreateModel( name=model_state.name, fields=[ d for d in model_state.fields.items() if d[0] not in related_fields ], options=model_state.options, bases=model_state.bases, managers=model_state.managers, ), dependencies=dependencies, beginning=True, ) # Don't add operations which modify the database for unmanaged models if not model_state.options.get("managed", True): continue # Generate operations for each related field for name, field in sorted(related_fields.items()): dependencies = self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) # Depend on our own model being created dependencies.append((app_label, model_name, None, True)) # Make operation self.add_operation( app_label, operations.AddField( model_name=model_name, name=name, field=field, ), dependencies=list(set(dependencies)), ) # Generate other opns if order_with_respect_to: self.add_operation( app_label, operations.AlterOrderWithRespectTo( name=model_name, order_with_respect_to=order_with_respect_to, ), dependencies=[ (app_label, model_name, order_with_respect_to, True), (app_label, model_name, None, True), ], ) related_dependencies = [ (app_label, model_name, name, True) for name in sorted(related_fields) ] related_dependencies.append((app_label, model_name, None, True)) for index in indexes: self.add_operation( app_label, operations.AddIndex( model_name=model_name, index=index, ), dependencies=related_dependencies, ) for constraint in constraints: self.add_operation( app_label, operations.AddConstraint( model_name=model_name, constraint=constraint, ), dependencies=related_dependencies, ) if unique_together: self.add_operation( app_label, operations.AlterUniqueTogether( name=model_name, unique_together=unique_together, ), dependencies=related_dependencies, ) # RemovedInDjango51Warning. if index_together: self.add_operation( app_label, operations.AlterIndexTogether( name=model_name, index_together=index_together, ), dependencies=related_dependencies, ) # Fix relationships if the model changed from a proxy model to a # concrete model. relations = self.to_state.relations if (app_label, model_name) in self.old_proxy_keys: for related_model_key, related_fields in relations[ app_label, model_name ].items(): related_model_state = self.to_state.models[related_model_key] for related_field_name, related_field in related_fields.items(): self.add_operation( related_model_state.app_label, operations.AlterField( model_name=related_model_state.name, name=related_field_name, field=related_field, ), dependencies=[(app_label, model_name, None, True)], ) def generate_created_proxies(self): """ Make CreateModel statements for proxy models. Use the same statements as that way there's less code duplication, but for proxy models it's safe to skip all the pointless field stuff and chuck out an operation. """ added = self.new_proxy_keys - self.old_proxy_keys for app_label, model_name in sorted(added): model_state = self.to_state.models[app_label, model_name] assert model_state.options.get("proxy") # Depend on the deletion of any possible non-proxy version of us dependencies = [ (app_label, model_name, None, False), ] # Depend on all bases for base in model_state.bases: if isinstance(base, str) and "." in base: base_app_label, base_name = base.split(".", 1) dependencies.append((base_app_label, base_name, None, True)) # Generate creation operation self.add_operation( app_label, operations.CreateModel( name=model_state.name, fields=[], options=model_state.options, bases=model_state.bases, managers=model_state.managers, ), # Depend on the deletion of any possible non-proxy version of us dependencies=dependencies, ) def generate_deleted_models(self): """ Find all deleted models (managed and unmanaged) and make delete operations for them as well as separate operations to delete any foreign key or M2M relationships (these are optimized later, if possible). Also bring forward removal of any model options that refer to collections of fields - the inverse of generate_created_models(). """ new_keys = self.new_model_keys | self.new_unmanaged_keys deleted_models = self.old_model_keys - new_keys deleted_unmanaged_models = self.old_unmanaged_keys - new_keys all_deleted_models = chain( sorted(deleted_models), sorted(deleted_unmanaged_models) ) for app_label, model_name in all_deleted_models: model_state = self.from_state.models[app_label, model_name] # Gather related fields related_fields = {} for field_name, field in model_state.fields.items(): if field.remote_field: if field.remote_field.model: related_fields[field_name] = field if getattr(field.remote_field, "through", None): related_fields[field_name] = field # Generate option removal first unique_together = model_state.options.pop("unique_together", None) # RemovedInDjango51Warning. index_together = model_state.options.pop("index_together", None) if unique_together: self.add_operation( app_label, operations.AlterUniqueTogether( name=model_name, unique_together=None, ), ) # RemovedInDjango51Warning. if index_together: self.add_operation( app_label, operations.AlterIndexTogether( name=model_name, index_together=None, ), ) # Then remove each related field for name in sorted(related_fields): self.add_operation( app_label, operations.RemoveField( model_name=model_name, name=name, ), ) # Finally, remove the model. # This depends on both the removal/alteration of all incoming fields # and the removal of all its own related fields, and if it's # a through model the field that references it. dependencies = [] relations = self.from_state.relations for ( related_object_app_label, object_name, ), relation_related_fields in relations[app_label, model_name].items(): for field_name, field in relation_related_fields.items(): dependencies.append( (related_object_app_label, object_name, field_name, False), ) if not field.many_to_many: dependencies.append( ( related_object_app_label, object_name, field_name, "alter", ), ) for name in sorted(related_fields): dependencies.append((app_label, model_name, name, False)) # We're referenced in another field's through= through_user = self.through_users.get((app_label, model_state.name_lower)) if through_user: dependencies.append( (through_user[0], through_user[1], through_user[2], False) ) # Finally, make the operation, deduping any dependencies self.add_operation( app_label, operations.DeleteModel( name=model_state.name, ), dependencies=list(set(dependencies)), ) def generate_deleted_proxies(self): """Make DeleteModel options for proxy models.""" deleted = self.old_proxy_keys - self.new_proxy_keys for app_label, model_name in sorted(deleted): model_state = self.from_state.models[app_label, model_name] assert model_state.options.get("proxy") self.add_operation( app_label, operations.DeleteModel( name=model_state.name, ), ) def create_renamed_fields(self): """Work out renamed fields.""" self.renamed_operations = [] old_field_keys = self.old_field_keys.copy() for app_label, model_name, field_name in sorted( self.new_field_keys - old_field_keys ): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] field = new_model_state.get_field(field_name) # Scan to see if this is actually a rename! field_dec = self.deep_deconstruct(field) for rem_app_label, rem_model_name, rem_field_name in sorted( old_field_keys - self.new_field_keys ): if rem_app_label == app_label and rem_model_name == model_name: old_field = old_model_state.get_field(rem_field_name) old_field_dec = self.deep_deconstruct(old_field) if ( field.remote_field and field.remote_field.model and "to" in old_field_dec[2] ): old_rel_to = old_field_dec[2]["to"] if old_rel_to in self.renamed_models_rel: old_field_dec[2]["to"] = self.renamed_models_rel[old_rel_to] old_field.set_attributes_from_name(rem_field_name) old_db_column = old_field.get_attname_column()[1] if old_field_dec == field_dec or ( # Was the field renamed and db_column equal to the # old field's column added? old_field_dec[0:2] == field_dec[0:2] and dict(old_field_dec[2], db_column=old_db_column) == field_dec[2] ): if self.questioner.ask_rename( model_name, rem_field_name, field_name, field ): self.renamed_operations.append( ( rem_app_label, rem_model_name, old_field.db_column, rem_field_name, app_label, model_name, field, field_name, ) ) old_field_keys.remove( (rem_app_label, rem_model_name, rem_field_name) ) old_field_keys.add((app_label, model_name, field_name)) self.renamed_fields[ app_label, model_name, field_name ] = rem_field_name break def generate_renamed_fields(self): """Generate RenameField operations.""" for ( rem_app_label, rem_model_name, rem_db_column, rem_field_name, app_label, model_name, field, field_name, ) in self.renamed_operations: # A db_column mismatch requires a prior noop AlterField for the # subsequent RenameField to be a noop on attempts at preserving the # old name. if rem_db_column != field.db_column: altered_field = field.clone() altered_field.name = rem_field_name self.add_operation( app_label, operations.AlterField( model_name=model_name, name=rem_field_name, field=altered_field, ), ) self.add_operation( app_label, operations.RenameField( model_name=model_name, old_name=rem_field_name, new_name=field_name, ), ) self.old_field_keys.remove((rem_app_label, rem_model_name, rem_field_name)) self.old_field_keys.add((app_label, model_name, field_name)) def generate_added_fields(self): """Make AddField operations.""" for app_label, model_name, field_name in sorted( self.new_field_keys - self.old_field_keys ): self._generate_added_field(app_label, model_name, field_name) def _generate_added_field(self, app_label, model_name, field_name): field = self.to_state.models[app_label, model_name].get_field(field_name) # Adding a field always depends at least on its removal. dependencies = [(app_label, model_name, field_name, False)] # Fields that are foreignkeys/m2ms depend on stuff. if field.remote_field and field.remote_field.model: dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) ) # You can't just add NOT NULL fields with no default or fields # which don't allow empty strings as default. time_fields = (models.DateField, models.DateTimeField, models.TimeField) preserve_default = ( field.null or field.has_default() or field.many_to_many or (field.blank and field.empty_strings_allowed) or (isinstance(field, time_fields) and field.auto_now) ) if not preserve_default: field = field.clone() if isinstance(field, time_fields) and field.auto_now_add: field.default = self.questioner.ask_auto_now_add_addition( field_name, model_name ) else: field.default = self.questioner.ask_not_null_addition( field_name, model_name ) if ( field.unique and field.default is not models.NOT_PROVIDED and callable(field.default) ): self.questioner.ask_unique_callable_default_addition(field_name, model_name) self.add_operation( app_label, operations.AddField( model_name=model_name, name=field_name, field=field, preserve_default=preserve_default, ), dependencies=dependencies, ) def generate_removed_fields(self): """Make RemoveField operations.""" for app_label, model_name, field_name in sorted( self.old_field_keys - self.new_field_keys ): self._generate_removed_field(app_label, model_name, field_name) def _generate_removed_field(self, app_label, model_name, field_name): self.add_operation( app_label, operations.RemoveField( model_name=model_name, name=field_name, ), # We might need to depend on the removal of an # order_with_respect_to or index/unique_together operation; # this is safely ignored if there isn't one dependencies=[ (app_label, model_name, field_name, "order_wrt_unset"), (app_label, model_name, field_name, "foo_together_change"), ], ) def generate_altered_fields(self): """ Make AlterField operations, or possibly RemovedField/AddField if alter isn't possible. """ for app_label, model_name, field_name in sorted( self.old_field_keys & self.new_field_keys ): # Did the field change? old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_field_name = self.renamed_fields.get( (app_label, model_name, field_name), field_name ) old_field = self.from_state.models[app_label, old_model_name].get_field( old_field_name ) new_field = self.to_state.models[app_label, model_name].get_field( field_name ) dependencies = [] # Implement any model renames on relations; these are handled by RenameModel # so we need to exclude them from the comparison if hasattr(new_field, "remote_field") and getattr( new_field.remote_field, "model", None ): rename_key = resolve_relation( new_field.remote_field.model, app_label, model_name ) if rename_key in self.renamed_models: new_field.remote_field.model = old_field.remote_field.model # Handle ForeignKey which can only have a single to_field. remote_field_name = getattr(new_field.remote_field, "field_name", None) 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) if from_fields: from_rename_key = (app_label, model_name) new_field.from_fields = tuple( [ self.renamed_fields.get( from_rename_key + (from_field,), from_field ) for from_field in from_fields ] ) new_field.to_fields = tuple( [ self.renamed_fields.get(rename_key + (to_field,), to_field) for to_field in new_field.to_fields ] ) dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, new_field, self.to_state, ) ) if hasattr(new_field, "remote_field") and getattr( new_field.remote_field, "through", None ): rename_key = resolve_relation( new_field.remote_field.through, app_label, model_name ) if rename_key in self.renamed_models: new_field.remote_field.through = old_field.remote_field.through old_field_dec = self.deep_deconstruct(old_field) new_field_dec = self.deep_deconstruct(new_field) # If the field was confirmed to be renamed it means that only # db_column was allowed to change which generate_renamed_fields() # already accounts for by adding an AlterField operation. if old_field_dec != new_field_dec and old_field_name == field_name: both_m2m = old_field.many_to_many and new_field.many_to_many neither_m2m = not old_field.many_to_many and not new_field.many_to_many if both_m2m or neither_m2m: # Either both fields are m2m or neither is preserve_default = True if ( old_field.null and not new_field.null and not new_field.has_default() and not new_field.many_to_many ): field = new_field.clone() new_default = self.questioner.ask_not_null_alteration( field_name, model_name ) if new_default is not models.NOT_PROVIDED: field.default = new_default preserve_default = False else: field = new_field self.add_operation( app_label, operations.AlterField( model_name=model_name, name=field_name, field=field, preserve_default=preserve_default, ), dependencies=dependencies, ) else: # We cannot alter between m2m and concrete fields self._generate_removed_field(app_label, model_name, field_name) self._generate_added_field(app_label, model_name, field_name) def create_altered_indexes(self): option_name = operations.AddIndex.option_name self.renamed_index_together_values = defaultdict(list) for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_indexes = old_model_state.options[option_name] new_indexes = new_model_state.options[option_name] added_indexes = [idx for idx in new_indexes if idx not in old_indexes] removed_indexes = [idx for idx in old_indexes if idx not in new_indexes] renamed_indexes = [] # Find renamed indexes. remove_from_added = [] remove_from_removed = [] for new_index in added_indexes: new_index_dec = new_index.deconstruct() new_index_name = new_index_dec[2].pop("name") for old_index in removed_indexes: old_index_dec = old_index.deconstruct() old_index_name = old_index_dec[2].pop("name") # Indexes are the same except for the names. if ( new_index_dec == old_index_dec and new_index_name != old_index_name ): renamed_indexes.append((old_index_name, new_index_name, None)) remove_from_added.append(new_index) remove_from_removed.append(old_index) # Find index_together changed to indexes. for ( old_value, new_value, index_together_app_label, index_together_model_name, dependencies, ) in self._get_altered_foo_together_operations( operations.AlterIndexTogether.option_name ): if ( app_label != index_together_app_label or model_name != index_together_model_name ): continue removed_values = old_value.difference(new_value) for removed_index_together in removed_values: renamed_index_together_indexes = [] for new_index in added_indexes: _, args, kwargs = new_index.deconstruct() # Ensure only 'fields' are defined in the Index. if ( not args and new_index.fields == list(removed_index_together) and set(kwargs) == {"name", "fields"} ): renamed_index_together_indexes.append(new_index) if len(renamed_index_together_indexes) == 1: renamed_index = renamed_index_together_indexes[0] remove_from_added.append(renamed_index) renamed_indexes.append( (None, renamed_index.name, removed_index_together) ) self.renamed_index_together_values[ index_together_app_label, index_together_model_name ].append(removed_index_together) # Remove renamed indexes from the lists of added and removed # indexes. added_indexes = [ idx for idx in added_indexes if idx not in remove_from_added ] removed_indexes = [ idx for idx in removed_indexes if idx not in remove_from_removed ] self.altered_indexes.update( { (app_label, model_name): { "added_indexes": added_indexes, "removed_indexes": removed_indexes, "renamed_indexes": renamed_indexes, } } ) def generate_added_indexes(self): for (app_label, model_name), alt_indexes in self.altered_indexes.items(): dependencies = self._get_dependencies_for_model(app_label, model_name) for index in alt_indexes["added_indexes"]: self.add_operation( app_label, operations.AddIndex( model_name=model_name, index=index, ), dependencies=dependencies, ) def generate_removed_indexes(self): for (app_label, model_name), alt_indexes in self.altered_indexes.items(): for index in alt_indexes["removed_indexes"]: self.add_operation( app_label, operations.RemoveIndex( model_name=model_name, name=index.name, ), ) def generate_renamed_indexes(self): for (app_label, model_name), alt_indexes in self.altered_indexes.items(): for old_index_name, new_index_name, old_fields in alt_indexes[ "renamed_indexes" ]: self.add_operation( app_label, operations.RenameIndex( model_name=model_name, new_name=new_index_name, old_name=old_index_name, old_fields=old_fields, ), ) def create_altered_constraints(self): option_name = operations.AddConstraint.option_name for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_constraints = old_model_state.options[option_name] new_constraints = new_model_state.options[option_name] add_constraints = [c for c in new_constraints if c not in old_constraints] rem_constraints = [c for c in old_constraints if c not in new_constraints] self.altered_constraints.update( { (app_label, model_name): { "added_constraints": add_constraints, "removed_constraints": rem_constraints, } } ) def generate_added_constraints(self): for ( app_label, model_name, ), alt_constraints in self.altered_constraints.items(): dependencies = self._get_dependencies_for_model(app_label, model_name) for constraint in alt_constraints["added_constraints"]: self.add_operation( app_label, operations.AddConstraint( model_name=model_name, constraint=constraint, ), dependencies=dependencies, ) def generate_removed_constraints(self): for ( app_label, model_name, ), alt_constraints in self.altered_constraints.items(): for constraint in alt_constraints["removed_constraints"]: self.add_operation( app_label, operations.RemoveConstraint( model_name=model_name, name=constraint.name, ), ) @staticmethod def _get_dependencies_for_foreign_key(app_label, model_name, field, project_state): remote_field_model = None if hasattr(field.remote_field, "model"): remote_field_model = field.remote_field.model else: relations = project_state.relations[app_label, model_name] for (remote_app_label, remote_model_name), fields in relations.items(): if any( field == related_field.remote_field for related_field in fields.values() ): remote_field_model = f"{remote_app_label}.{remote_model_name}" break # Account for FKs to swappable models swappable_setting = getattr(field, "swappable_setting", None) if swappable_setting is not None: dep_app_label = "__setting__" dep_object_name = swappable_setting else: dep_app_label, dep_object_name = resolve_relation( remote_field_model, app_label, model_name, ) dependencies = [(dep_app_label, dep_object_name, None, True)] if getattr(field.remote_field, "through", None): through_app_label, through_object_name = resolve_relation( field.remote_field.through, app_label, model_name, ) dependencies.append((through_app_label, through_object_name, None, True)) return dependencies def _get_dependencies_for_model(self, app_label, model_name): """Return foreign key dependencies of the given model.""" dependencies = [] model_state = self.to_state.models[app_label, model_name] for field in model_state.fields.values(): if field.is_relation: dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) ) return dependencies def _get_altered_foo_together_operations(self, option_name): for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] # We run the old version through the field renames to account for those old_value = old_model_state.options.get(option_name) old_value = ( { tuple( self.renamed_fields.get((app_label, model_name, n), n) for n in unique ) for unique in old_value } if old_value else set() ) new_value = new_model_state.options.get(option_name) new_value = set(new_value) if new_value else set() if old_value != new_value: dependencies = [] for foo_togethers in new_value: for field_name in foo_togethers: field = new_model_state.get_field(field_name) if field.remote_field and field.remote_field.model: dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) ) yield ( old_value, new_value, app_label, model_name, dependencies, ) def _generate_removed_altered_foo_together(self, operation): for ( old_value, new_value, app_label, model_name, dependencies, ) in self._get_altered_foo_together_operations(operation.option_name): if operation == operations.AlterIndexTogether: old_value = { value for value in old_value if value not in self.renamed_index_together_values[app_label, model_name] } removal_value = new_value.intersection(old_value) if removal_value or old_value: self.add_operation( app_label, operation( name=model_name, **{operation.option_name: removal_value} ), dependencies=dependencies, ) def generate_removed_altered_unique_together(self): self._generate_removed_altered_foo_together(operations.AlterUniqueTogether) # RemovedInDjango51Warning. def generate_removed_altered_index_together(self): self._generate_removed_altered_foo_together(operations.AlterIndexTogether) def _generate_altered_foo_together(self, operation): for ( old_value, new_value, app_label, model_name, dependencies, ) in self._get_altered_foo_together_operations(operation.option_name): removal_value = new_value.intersection(old_value) if new_value != removal_value: self.add_operation( app_label, operation(name=model_name, **{operation.option_name: new_value}), dependencies=dependencies, ) def generate_altered_unique_together(self): self._generate_altered_foo_together(operations.AlterUniqueTogether) # RemovedInDjango51Warning. def generate_altered_index_together(self): self._generate_altered_foo_together(operations.AlterIndexTogether) def generate_altered_db_table(self): models_to_check = self.kept_model_keys.union( self.kept_proxy_keys, self.kept_unmanaged_keys ) for app_label, model_name in sorted(models_to_check): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_db_table_name = old_model_state.options.get("db_table") new_db_table_name = new_model_state.options.get("db_table") if old_db_table_name != new_db_table_name: self.add_operation( app_label, operations.AlterModelTable( name=model_name, table=new_db_table_name, ), ) def generate_altered_db_table_comment(self): models_to_check = self.kept_model_keys.union( self.kept_proxy_keys, self.kept_unmanaged_keys ) for app_label, model_name in sorted(models_to_check): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_db_table_comment = old_model_state.options.get("db_table_comment") new_db_table_comment = new_model_state.options.get("db_table_comment") if old_db_table_comment != new_db_table_comment: self.add_operation( app_label, operations.AlterModelTableComment( name=model_name, table_comment=new_db_table_comment, ), ) def generate_altered_options(self): """ Work out if any non-schema-affecting options have changed and make an operation to represent them in state changes (in case Python code in migrations needs them). """ models_to_check = self.kept_model_keys.union( self.kept_proxy_keys, self.kept_unmanaged_keys, # unmanaged converted to managed self.old_unmanaged_keys & self.new_model_keys, # managed converted to unmanaged self.old_model_keys & self.new_unmanaged_keys, ) for app_label, model_name in sorted(models_to_check): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_options = { key: value for key, value in old_model_state.options.items() if key in AlterModelOptions.ALTER_OPTION_KEYS } new_options = { key: value for key, value in new_model_state.options.items() if key in AlterModelOptions.ALTER_OPTION_KEYS } if old_options != new_options: self.add_operation( app_label, operations.AlterModelOptions( name=model_name, options=new_options, ), ) def generate_altered_order_with_respect_to(self): for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] if old_model_state.options.get( "order_with_respect_to" ) != new_model_state.options.get("order_with_respect_to"): # Make sure it comes second if we're adding # (removal dependency is part of RemoveField) dependencies = [] if new_model_state.options.get("order_with_respect_to"): dependencies.append( ( app_label, model_name, new_model_state.options["order_with_respect_to"], True, ) ) # Actually generate the operation self.add_operation( app_label, operations.AlterOrderWithRespectTo( name=model_name, order_with_respect_to=new_model_state.options.get( "order_with_respect_to" ), ), dependencies=dependencies, ) def generate_altered_managers(self): for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] if old_model_state.managers != new_model_state.managers: self.add_operation( app_label, operations.AlterModelManagers( name=model_name, managers=new_model_state.managers, ), ) def arrange_for_graph(self, changes, graph, migration_name=None): """ Take a result from changes() and a MigrationGraph, and fix the names and dependencies of the changes so they extend the graph from the leaf nodes for each app. """ leaves = graph.leaf_nodes() name_map = {} for app_label, migrations in list(changes.items()): if not migrations: continue # Find the app label's current leaf node app_leaf = None for leaf in leaves: if leaf[0] == app_label: app_leaf = leaf break # Do they want an initial migration for this app? if app_leaf is None and not self.questioner.ask_initial(app_label): # They don't. for migration in migrations: name_map[(app_label, migration.name)] = (app_label, "__first__") del changes[app_label] continue # Work out the next number in the sequence if app_leaf is None: next_number = 1 else: next_number = (self.parse_number(app_leaf[1]) or 0) + 1 # Name each migration for i, migration in enumerate(migrations): if i == 0 and app_leaf: migration.dependencies.append(app_leaf) new_name_parts = ["%04i" % next_number] if migration_name: new_name_parts.append(migration_name) elif i == 0 and not app_leaf: new_name_parts.append("initial") else: new_name_parts.append(migration.suggest_name()[:100]) new_name = "_".join(new_name_parts) name_map[(app_label, migration.name)] = (app_label, new_name) next_number += 1 migration.name = new_name # Now fix dependencies for migrations in changes.values(): for migration in migrations: migration.dependencies = [ name_map.get(d, d) for d in migration.dependencies ] return changes def _trim_to_apps(self, changes, app_labels): """ Take changes from arrange_for_graph() and set of app labels, and return a modified set of changes which trims out as many migrations that are not in app_labels as possible. Note that some other migrations may still be present as they may be required dependencies. """ # Gather other app dependencies in a first pass app_dependencies = {} for app_label, migrations in changes.items(): for migration in migrations: for dep_app_label, name in migration.dependencies: app_dependencies.setdefault(app_label, set()).add(dep_app_label) required_apps = set(app_labels) # Keep resolving till there's no change old_required_apps = None while old_required_apps != required_apps: old_required_apps = set(required_apps) required_apps.update( *[app_dependencies.get(app_label, ()) for app_label in required_apps] ) # Remove all migrations that aren't needed for app_label in list(changes): if app_label not in required_apps: del changes[app_label] return changes @classmethod def parse_number(cls, name): """ Given a migration name, try to extract a number from the beginning of it. For a squashed migration such as '0001_squashed_0004…', return the second number. If no number is found, return None. """ if squashed_match := re.search(r".*_squashed_(\d+)", name): return int(squashed_match[1]) match = re.match(r"^\d+", name) if match: return int(match[0]) return None
57131e06f927b58dc58b292d8996e347deca09a2848e24dc721e746d742f3d9c
import itertools import math from django.core.exceptions import EmptyResultSet, FullResultSet from django.db.models.expressions import Case, Expression, Func, Value, When from django.db.models.fields import ( BooleanField, CharField, DateTimeField, Field, IntegerField, UUIDField, ) from django.db.models.query_utils import RegisterLookupMixin from django.utils.datastructures import OrderedSet from django.utils.functional import cached_property from django.utils.hashable import make_hashable class Lookup(Expression): lookup_name = None prepare_rhs = True can_use_none_as_rhs = False def __init__(self, lhs, rhs): self.lhs, self.rhs = lhs, rhs self.rhs = self.get_prep_lookup() self.lhs = self.get_prep_lhs() if hasattr(self.lhs, "get_bilateral_transforms"): bilateral_transforms = self.lhs.get_bilateral_transforms() else: bilateral_transforms = [] if bilateral_transforms: # Warn the user as soon as possible if they are trying to apply # a bilateral transformation on a nested QuerySet: that won't work. from django.db.models.sql.query import Query # avoid circular import if isinstance(rhs, Query): raise NotImplementedError( "Bilateral transformations on nested querysets are not implemented." ) self.bilateral_transforms = bilateral_transforms def apply_bilateral_transforms(self, value): for transform in self.bilateral_transforms: value = transform(value) return value def __repr__(self): return f"{self.__class__.__name__}({self.lhs!r}, {self.rhs!r})" def batch_process_rhs(self, compiler, connection, rhs=None): if rhs is None: rhs = self.rhs if self.bilateral_transforms: sqls, sqls_params = [], [] for p in rhs: value = Value(p, output_field=self.lhs.output_field) value = self.apply_bilateral_transforms(value) value = value.resolve_expression(compiler.query) sql, sql_params = compiler.compile(value) sqls.append(sql) sqls_params.extend(sql_params) else: _, params = self.get_db_prep_lookup(rhs, connection) sqls, sqls_params = ["%s"] * len(params), params return sqls, sqls_params def get_source_expressions(self): if self.rhs_is_direct_value(): return [self.lhs] return [self.lhs, self.rhs] def set_source_expressions(self, new_exprs): if len(new_exprs) == 1: self.lhs = new_exprs[0] else: self.lhs, self.rhs = new_exprs def get_prep_lookup(self): if not self.prepare_rhs or hasattr(self.rhs, "resolve_expression"): return self.rhs if hasattr(self.lhs, "output_field"): if hasattr(self.lhs.output_field, "get_prep_value"): return self.lhs.output_field.get_prep_value(self.rhs) elif self.rhs_is_direct_value(): return Value(self.rhs) return self.rhs def get_prep_lhs(self): if hasattr(self.lhs, "resolve_expression"): return self.lhs return Value(self.lhs) def get_db_prep_lookup(self, value, connection): return ("%s", [value]) def process_lhs(self, compiler, connection, lhs=None): lhs = lhs or self.lhs if hasattr(lhs, "resolve_expression"): lhs = lhs.resolve_expression(compiler.query) sql, params = compiler.compile(lhs) if isinstance(lhs, Lookup): # Wrapped in parentheses to respect operator precedence. sql = f"({sql})" return sql, params def process_rhs(self, compiler, connection): value = self.rhs if self.bilateral_transforms: if self.rhs_is_direct_value(): # Do not call get_db_prep_lookup here as the value will be # transformed before being used for lookup value = Value(value, output_field=self.lhs.output_field) value = self.apply_bilateral_transforms(value) value = value.resolve_expression(compiler.query) if hasattr(value, "as_sql"): sql, params = compiler.compile(value) # Ensure expression is wrapped in parentheses to respect operator # precedence but avoid double wrapping as it can be misinterpreted # on some backends (e.g. subqueries on SQLite). if sql and sql[0] != "(": sql = "(%s)" % sql return sql, params else: return self.get_db_prep_lookup(value, connection) def rhs_is_direct_value(self): return not hasattr(self.rhs, "as_sql") def get_group_by_cols(self): cols = [] for source in self.get_source_expressions(): cols.extend(source.get_group_by_cols()) return cols def as_oracle(self, compiler, connection): # Oracle doesn't allow EXISTS() and filters to be compared to another # expression unless they're wrapped in a CASE WHEN. wrapped = False exprs = [] for expr in (self.lhs, self.rhs): if connection.ops.conditional_expression_supported_in_where_clause(expr): expr = Case(When(expr, then=True), default=False) wrapped = True exprs.append(expr) lookup = type(self)(*exprs) if wrapped else self return lookup.as_sql(compiler, connection) @cached_property def output_field(self): return BooleanField() @property def identity(self): return self.__class__, self.lhs, self.rhs def __eq__(self, other): if not isinstance(other, Lookup): return NotImplemented return self.identity == other.identity def __hash__(self): return hash(make_hashable(self.identity)) def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = self.copy() c.is_summary = summarize c.lhs = self.lhs.resolve_expression( query, allow_joins, reuse, summarize, for_save ) if hasattr(self.rhs, "resolve_expression"): c.rhs = self.rhs.resolve_expression( query, allow_joins, reuse, summarize, for_save ) return c def select_format(self, compiler, sql, params): # Wrap filters with a CASE WHEN expression if a database backend # (e.g. Oracle) doesn't support boolean expression in SELECT or GROUP # BY list. if not compiler.connection.features.supports_boolean_expr_in_select_clause: sql = f"CASE WHEN {sql} THEN 1 ELSE 0 END" return sql, params class Transform(RegisterLookupMixin, Func): """ RegisterLookupMixin() is first so that get_lookup() and get_transform() first examine self and then check output_field. """ bilateral = False arity = 1 @property def lhs(self): return self.get_source_expressions()[0] def get_bilateral_transforms(self): if hasattr(self.lhs, "get_bilateral_transforms"): bilateral_transforms = self.lhs.get_bilateral_transforms() else: bilateral_transforms = [] if self.bilateral: bilateral_transforms.append(self.__class__) return bilateral_transforms class BuiltinLookup(Lookup): def process_lhs(self, compiler, connection, lhs=None): lhs_sql, params = super().process_lhs(compiler, connection, lhs) field_internal_type = self.lhs.output_field.get_internal_type() db_type = self.lhs.output_field.db_type(connection=connection) lhs_sql = connection.ops.field_cast_sql(db_type, field_internal_type) % lhs_sql lhs_sql = ( connection.ops.lookup_cast(self.lookup_name, field_internal_type) % lhs_sql ) return lhs_sql, list(params) def as_sql(self, compiler, connection): lhs_sql, params = self.process_lhs(compiler, connection) rhs_sql, rhs_params = self.process_rhs(compiler, connection) params.extend(rhs_params) rhs_sql = self.get_rhs_op(connection, rhs_sql) return "%s %s" % (lhs_sql, rhs_sql), params def get_rhs_op(self, connection, rhs): return connection.operators[self.lookup_name] % rhs class FieldGetDbPrepValueMixin: """ Some lookups require Field.get_db_prep_value() to be called on their inputs. """ get_db_prep_lookup_value_is_iterable = False def get_db_prep_lookup(self, value, connection): # For relational fields, use the 'target_field' attribute of the # output_field. field = getattr(self.lhs.output_field, "target_field", None) get_db_prep_value = ( getattr(field, "get_db_prep_value", None) or self.lhs.output_field.get_db_prep_value ) return ( "%s", [get_db_prep_value(v, connection, prepared=True) for v in value] if self.get_db_prep_lookup_value_is_iterable else [get_db_prep_value(value, connection, prepared=True)], ) class FieldGetDbPrepValueIterableMixin(FieldGetDbPrepValueMixin): """ Some lookups require Field.get_db_prep_value() to be called on each value in an iterable. """ get_db_prep_lookup_value_is_iterable = True def get_prep_lookup(self): if hasattr(self.rhs, "resolve_expression"): return self.rhs prepared_values = [] for rhs_value in self.rhs: if hasattr(rhs_value, "resolve_expression"): # An expression will be handled by the database but can coexist # alongside real values. pass elif self.prepare_rhs and hasattr(self.lhs.output_field, "get_prep_value"): rhs_value = self.lhs.output_field.get_prep_value(rhs_value) prepared_values.append(rhs_value) return prepared_values def process_rhs(self, compiler, connection): if self.rhs_is_direct_value(): # rhs should be an iterable of values. Use batch_process_rhs() # to prepare/transform those values. return self.batch_process_rhs(compiler, connection) else: return super().process_rhs(compiler, connection) def resolve_expression_parameter(self, compiler, connection, sql, param): params = [param] if hasattr(param, "resolve_expression"): param = param.resolve_expression(compiler.query) if hasattr(param, "as_sql"): sql, params = compiler.compile(param) return sql, params def batch_process_rhs(self, compiler, connection, rhs=None): pre_processed = super().batch_process_rhs(compiler, connection, rhs) # The params list may contain expressions which compile to a # sql/param pair. Zip them to get sql and param pairs that refer to the # same argument and attempt to replace them with the result of # compiling the param step. sql, params = zip( *( self.resolve_expression_parameter(compiler, connection, sql, param) for sql, param in zip(*pre_processed) ) ) params = itertools.chain.from_iterable(params) return sql, tuple(params) class PostgresOperatorLookup(Lookup): """Lookup defined by operators on PostgreSQL.""" postgres_operator = None def as_postgresql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = tuple(lhs_params) + tuple(rhs_params) return "%s %s %s" % (lhs, self.postgres_operator, rhs), params @Field.register_lookup class Exact(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "exact" def get_prep_lookup(self): from django.db.models.sql.query import Query # avoid circular import if isinstance(self.rhs, Query): if self.rhs.has_limit_one(): 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 " "one result using slicing." ) return super().get_prep_lookup() def as_sql(self, compiler, connection): # Avoid comparison against direct rhs if lhs is a boolean value. That # turns "boolfield__exact=True" into "WHERE boolean_field" instead of # "WHERE boolean_field = True" when allowed. if ( isinstance(self.rhs, bool) and getattr(self.lhs, "conditional", False) and connection.ops.conditional_expression_supported_in_where_clause( self.lhs ) ): lhs_sql, params = self.process_lhs(compiler, connection) template = "%s" if self.rhs else "NOT %s" return template % lhs_sql, params return super().as_sql(compiler, connection) @Field.register_lookup class IExact(BuiltinLookup): lookup_name = "iexact" prepare_rhs = False def process_rhs(self, qn, connection): rhs, params = super().process_rhs(qn, connection) if params: params[0] = connection.ops.prep_for_iexact_query(params[0]) return rhs, params @Field.register_lookup class GreaterThan(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "gt" @Field.register_lookup class GreaterThanOrEqual(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "gte" @Field.register_lookup class LessThan(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "lt" @Field.register_lookup class LessThanOrEqual(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "lte" class IntegerFieldOverflow: underflow_exception = EmptyResultSet overflow_exception = EmptyResultSet def process_rhs(self, compiler, connection): rhs = self.rhs if isinstance(rhs, int): field_internal_type = self.lhs.output_field.get_internal_type() min_value, max_value = connection.ops.integer_field_range( field_internal_type ) if min_value is not None and rhs < min_value: raise self.underflow_exception if max_value is not None and rhs > max_value: raise self.overflow_exception return super().process_rhs(compiler, connection) class IntegerFieldFloatRounding: """ Allow floats to work as query values for IntegerField. Without this, the decimal portion of the float would always be discarded. """ def get_prep_lookup(self): if isinstance(self.rhs, float): self.rhs = math.ceil(self.rhs) return super().get_prep_lookup() @IntegerField.register_lookup class IntegerFieldExact(IntegerFieldOverflow, Exact): pass @IntegerField.register_lookup class IntegerGreaterThan(IntegerFieldOverflow, GreaterThan): underflow_exception = FullResultSet @IntegerField.register_lookup class IntegerGreaterThanOrEqual( IntegerFieldOverflow, IntegerFieldFloatRounding, GreaterThanOrEqual ): underflow_exception = FullResultSet @IntegerField.register_lookup class IntegerLessThan(IntegerFieldOverflow, IntegerFieldFloatRounding, LessThan): overflow_exception = FullResultSet @IntegerField.register_lookup class IntegerLessThanOrEqual(IntegerFieldOverflow, LessThanOrEqual): overflow_exception = FullResultSet @Field.register_lookup class In(FieldGetDbPrepValueIterableMixin, BuiltinLookup): lookup_name = "in" def get_prep_lookup(self): from django.db.models.sql.query import Query # avoid circular import if isinstance(self.rhs, Query): self.rhs.clear_ordering(clear_default=True) if not self.rhs.has_select_fields: self.rhs.clear_select_clause() self.rhs.add_fields(["pk"]) return super().get_prep_lookup() def process_rhs(self, compiler, connection): db_rhs = getattr(self.rhs, "_db", None) if db_rhs is not None and db_rhs != connection.alias: raise ValueError( "Subqueries aren't allowed across different databases. Force " "the inner query to be evaluated using `list(inner_query)`." ) if self.rhs_is_direct_value(): # Remove None from the list as NULL is never equal to anything. try: rhs = OrderedSet(self.rhs) rhs.discard(None) except TypeError: # Unhashable items in self.rhs rhs = [r for r in self.rhs if r is not None] if not rhs: raise EmptyResultSet # rhs should be an iterable; use batch_process_rhs() to # prepare/transform those values. sqls, sqls_params = self.batch_process_rhs(compiler, connection, rhs) placeholder = "(" + ", ".join(sqls) + ")" return (placeholder, sqls_params) return super().process_rhs(compiler, connection) def get_rhs_op(self, connection, rhs): return "IN %s" % rhs def as_sql(self, compiler, connection): max_in_list_size = connection.ops.max_in_list_size() if ( self.rhs_is_direct_value() and max_in_list_size and len(self.rhs) > max_in_list_size ): return self.split_parameter_list_as_sql(compiler, connection) return super().as_sql(compiler, connection) def split_parameter_list_as_sql(self, compiler, connection): # This is a special case for databases which limit the number of # elements which can appear in an 'IN' clause. max_in_list_size = connection.ops.max_in_list_size() lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.batch_process_rhs(compiler, connection) in_clause_elements = ["("] params = [] for offset in range(0, len(rhs_params), max_in_list_size): if offset > 0: in_clause_elements.append(" OR ") in_clause_elements.append("%s IN (" % lhs) params.extend(lhs_params) sqls = rhs[offset : offset + max_in_list_size] sqls_params = rhs_params[offset : offset + max_in_list_size] param_group = ", ".join(sqls) in_clause_elements.append(param_group) in_clause_elements.append(")") params.extend(sqls_params) in_clause_elements.append(")") return "".join(in_clause_elements), params class PatternLookup(BuiltinLookup): param_pattern = "%%%s%%" prepare_rhs = False def get_rhs_op(self, connection, rhs): # Assume we are in startswith. We need to produce SQL like: # col LIKE %s, ['thevalue%'] # For python values we can (and should) do that directly in Python, # but if the value is for example reference to other column, then # we need to add the % pattern match to the lookup by something like # col LIKE othercol || '%%' # So, for Python values we don't need any special pattern, but for # SQL reference values or SQL transformations we need the correct # pattern added. if hasattr(self.rhs, "as_sql") or self.bilateral_transforms: pattern = connection.pattern_ops[self.lookup_name].format( connection.pattern_esc ) return pattern.format(rhs) else: return super().get_rhs_op(connection, rhs) def process_rhs(self, qn, connection): rhs, params = super().process_rhs(qn, connection) if self.rhs_is_direct_value() and params and not self.bilateral_transforms: params[0] = self.param_pattern % connection.ops.prep_for_like_query( params[0] ) return rhs, params @Field.register_lookup class Contains(PatternLookup): lookup_name = "contains" @Field.register_lookup class IContains(Contains): lookup_name = "icontains" @Field.register_lookup class StartsWith(PatternLookup): lookup_name = "startswith" param_pattern = "%s%%" @Field.register_lookup class IStartsWith(StartsWith): lookup_name = "istartswith" @Field.register_lookup class EndsWith(PatternLookup): lookup_name = "endswith" param_pattern = "%%%s" @Field.register_lookup class IEndsWith(EndsWith): lookup_name = "iendswith" @Field.register_lookup class Range(FieldGetDbPrepValueIterableMixin, BuiltinLookup): lookup_name = "range" def get_rhs_op(self, connection, rhs): return "BETWEEN %s AND %s" % (rhs[0], rhs[1]) @Field.register_lookup class IsNull(BuiltinLookup): lookup_name = "isnull" 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 = self.process_lhs(compiler, connection) if self.rhs: return "%s IS NULL" % sql, params else: return "%s IS NOT NULL" % sql, params @Field.register_lookup class Regex(BuiltinLookup): lookup_name = "regex" prepare_rhs = False def as_sql(self, compiler, connection): if self.lookup_name in connection.operators: return super().as_sql(compiler, connection) else: lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) sql_template = connection.ops.regex_lookup(self.lookup_name) return sql_template % (lhs, rhs), lhs_params + rhs_params @Field.register_lookup class IRegex(Regex): lookup_name = "iregex" class YearLookup(Lookup): def year_lookup_bounds(self, connection, year): from django.db.models.functions import ExtractIsoYear iso_year = isinstance(self.lhs, ExtractIsoYear) output_field = self.lhs.lhs.output_field if isinstance(output_field, DateTimeField): bounds = connection.ops.year_lookup_bounds_for_datetime_field( year, iso_year=iso_year, ) else: bounds = connection.ops.year_lookup_bounds_for_date_field( year, iso_year=iso_year, ) return bounds def as_sql(self, compiler, connection): # Avoid the extract operation if the rhs is a direct value to allow # indexes to be used. if self.rhs_is_direct_value(): # Skip the extract part by directly using the originating field, # that is self.lhs.lhs. lhs_sql, params = self.process_lhs(compiler, connection, self.lhs.lhs) rhs_sql, _ = self.process_rhs(compiler, connection) rhs_sql = self.get_direct_rhs_sql(connection, rhs_sql) start, finish = self.year_lookup_bounds(connection, self.rhs) params.extend(self.get_bound_params(start, finish)) return "%s %s" % (lhs_sql, rhs_sql), params return super().as_sql(compiler, connection) def get_direct_rhs_sql(self, connection, rhs): return connection.operators[self.lookup_name] % rhs def get_bound_params(self, start, finish): raise NotImplementedError( "subclasses of YearLookup must provide a get_bound_params() method" ) class YearExact(YearLookup, Exact): def get_direct_rhs_sql(self, connection, rhs): return "BETWEEN %s AND %s" def get_bound_params(self, start, finish): return (start, finish) class YearGt(YearLookup, GreaterThan): def get_bound_params(self, start, finish): return (finish,) class YearGte(YearLookup, GreaterThanOrEqual): def get_bound_params(self, start, finish): return (start,) class YearLt(YearLookup, LessThan): def get_bound_params(self, start, finish): return (start,) class YearLte(YearLookup, LessThanOrEqual): def get_bound_params(self, start, finish): return (finish,) class UUIDTextMixin: """ Strip hyphens from a value when filtering a UUIDField on backends without a native datatype for UUID. """ def process_rhs(self, qn, connection): if not connection.features.has_native_uuid_field: from django.db.models.functions import Replace if self.rhs_is_direct_value(): self.rhs = Value(self.rhs) self.rhs = Replace( self.rhs, Value("-"), Value(""), output_field=CharField() ) rhs, params = super().process_rhs(qn, connection) return rhs, params @UUIDField.register_lookup class UUIDIExact(UUIDTextMixin, IExact): pass @UUIDField.register_lookup class UUIDContains(UUIDTextMixin, Contains): pass @UUIDField.register_lookup class UUIDIContains(UUIDTextMixin, IContains): pass @UUIDField.register_lookup class UUIDStartsWith(UUIDTextMixin, StartsWith): pass @UUIDField.register_lookup class UUIDIStartsWith(UUIDTextMixin, IStartsWith): pass @UUIDField.register_lookup class UUIDEndsWith(UUIDTextMixin, EndsWith): pass @UUIDField.register_lookup class UUIDIEndsWith(UUIDTextMixin, IEndsWith): pass
654b31079a94a4368a52d5556d706150802235fc69ad00dde5c13fc11d125e82
import datetime import decimal import uuid from functools import lru_cache from itertools import chain from django.conf import settings from django.core.exceptions import FieldError from django.db import DatabaseError, NotSupportedError, models from django.db.backends.base.operations import BaseDatabaseOperations from django.db.models.constants import OnConflict from django.db.models.expressions import Col from django.utils import timezone from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.functional import cached_property class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = "text" cast_data_types = { "DateField": "TEXT", "DateTimeField": "TEXT", } explain_prefix = "EXPLAIN QUERY PLAN" # List of datatypes to that cannot be extracted with JSON_EXTRACT() on # SQLite. Use JSON_TYPE() instead. jsonfield_datatype_values = frozenset(["null", "false", "true"]) def bulk_batch_size(self, fields, objs): """ SQLite has a compile-time default (SQLITE_LIMIT_VARIABLE_NUMBER) of 999 variables per query. If there's only a single field to insert, the limit is 500 (SQLITE_MAX_COMPOUND_SELECT). """ if len(fields) == 1: return 500 elif len(fields) > 1: return self.connection.features.max_query_params // len(fields) else: return len(objs) def check_expression_support(self, expression): bad_fields = (models.DateField, models.DateTimeField, models.TimeField) bad_aggregates = (models.Sum, models.Avg, models.Variance, models.StdDev) if isinstance(expression, bad_aggregates): for expr in expression.get_source_expressions(): try: output_field = expr.output_field except (AttributeError, FieldError): # Not every subexpression has an output_field which is fine # to ignore. pass else: if isinstance(output_field, bad_fields): raise NotSupportedError( "You cannot use Sum, Avg, StdDev, and Variance " "aggregations on date/time fields in sqlite3 " "since date/time is saved as text." ) if ( isinstance(expression, models.Aggregate) and expression.distinct and len(expression.source_expressions) > 1 ): raise NotSupportedError( "SQLite doesn't support DISTINCT on aggregate functions " "accepting multiple arguments." ) def date_extract_sql(self, lookup_type, sql, params): """ Support EXTRACT with a user-defined function django_date_extract() that's registered in connect(). Use single quotes because this is a string and could otherwise cause a collision with a field name. """ return f"django_date_extract(%s, {sql})", (lookup_type.lower(), *params) def fetch_returned_insert_rows(self, cursor): """ Given a cursor object that has just performed an INSERT...RETURNING statement into a table, return the list of returned data. """ return cursor.fetchall() def format_for_duration_arithmetic(self, sql): """Do nothing since formatting is handled in the custom function.""" return sql def date_trunc_sql(self, lookup_type, sql, params, tzname=None): return f"django_date_trunc(%s, {sql}, %s, %s)", ( lookup_type.lower(), *params, *self._convert_tznames_to_sql(tzname), ) def time_trunc_sql(self, lookup_type, sql, params, tzname=None): return f"django_time_trunc(%s, {sql}, %s, %s)", ( lookup_type.lower(), *params, *self._convert_tznames_to_sql(tzname), ) def _convert_tznames_to_sql(self, tzname): if tzname and settings.USE_TZ: return tzname, self.connection.timezone_name return None, None def datetime_cast_date_sql(self, sql, params, tzname): return f"django_datetime_cast_date({sql}, %s, %s)", ( *params, *self._convert_tznames_to_sql(tzname), ) def datetime_cast_time_sql(self, sql, params, tzname): return f"django_datetime_cast_time({sql}, %s, %s)", ( *params, *self._convert_tznames_to_sql(tzname), ) def datetime_extract_sql(self, lookup_type, sql, params, tzname): return f"django_datetime_extract(%s, {sql}, %s, %s)", ( lookup_type.lower(), *params, *self._convert_tznames_to_sql(tzname), ) def datetime_trunc_sql(self, lookup_type, sql, params, tzname): return f"django_datetime_trunc(%s, {sql}, %s, %s)", ( lookup_type.lower(), *params, *self._convert_tznames_to_sql(tzname), ) def time_extract_sql(self, lookup_type, sql, params): return f"django_time_extract(%s, {sql})", (lookup_type.lower(), *params) def pk_default_value(self): return "NULL" def _quote_params_for_last_executed_query(self, params): """ Only for last_executed_query! Don't use this to execute SQL queries! """ # This function is limited both by SQLITE_LIMIT_VARIABLE_NUMBER (the # number of parameters, default = 999) and SQLITE_MAX_COLUMN (the # number of return values, default = 2000). Since Python's sqlite3 # module doesn't expose the get_limit() C API, assume the default # limits are in effect and split the work in batches if needed. BATCH_SIZE = 999 if len(params) > BATCH_SIZE: results = () for index in range(0, len(params), BATCH_SIZE): chunk = params[index : index + BATCH_SIZE] results += self._quote_params_for_last_executed_query(chunk) return results sql = "SELECT " + ", ".join(["QUOTE(?)"] * len(params)) # Bypass Django's wrappers and use the underlying sqlite3 connection # to avoid logging this query - it would trigger infinite recursion. cursor = self.connection.connection.cursor() # Native sqlite3 cursors cannot be used as context managers. try: return cursor.execute(sql, params).fetchone() finally: cursor.close() def last_executed_query(self, cursor, sql, params): # Python substitutes parameters in Modules/_sqlite/cursor.c with: # bind_parameters(state, self->statement, parameters); # Unfortunately there is no way to reach self->statement from Python, # so we quote and substitute parameters manually. if params: if isinstance(params, (list, tuple)): params = self._quote_params_for_last_executed_query(params) else: values = tuple(params.values()) values = self._quote_params_for_last_executed_query(values) params = dict(zip(params, values)) return sql % params # For consistency with SQLiteCursorWrapper.execute(), just return sql # when there are no parameters. See #13648 and #17158. else: return sql def quote_name(self, name): if name.startswith('"') and name.endswith('"'): return name # Quoting once is enough. return '"%s"' % name def no_limit_value(self): return -1 def __references_graph(self, table_name): query = """ WITH tables AS ( SELECT %s name UNION SELECT sqlite_master.name FROM sqlite_master JOIN tables ON (sql REGEXP %s || tables.name || %s) ) SELECT name FROM tables; """ params = ( table_name, r'(?i)\s+references\s+("|\')?', r'("|\')?\s*\(', ) with self.connection.cursor() as cursor: results = cursor.execute(query, params) return [row[0] for row in results.fetchall()] @cached_property def _references_graph(self): # 512 is large enough to fit the ~330 tables (as of this writing) in # Django's test suite. return lru_cache(maxsize=512)(self.__references_graph) def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False): if tables and allow_cascade: # Simulate TRUNCATE CASCADE by recursively collecting the tables # referencing the tables to be flushed. tables = set( chain.from_iterable(self._references_graph(table) for table in tables) ) sql = [ "%s %s %s;" % ( style.SQL_KEYWORD("DELETE"), style.SQL_KEYWORD("FROM"), style.SQL_FIELD(self.quote_name(table)), ) for table in tables ] if reset_sequences: sequences = [{"table": table} for table in tables] sql.extend(self.sequence_reset_by_name_sql(style, sequences)) return sql def sequence_reset_by_name_sql(self, style, sequences): if not sequences: return [] return [ "%s %s %s %s = 0 %s %s %s (%s);" % ( style.SQL_KEYWORD("UPDATE"), style.SQL_TABLE(self.quote_name("sqlite_sequence")), style.SQL_KEYWORD("SET"), style.SQL_FIELD(self.quote_name("seq")), style.SQL_KEYWORD("WHERE"), style.SQL_FIELD(self.quote_name("name")), style.SQL_KEYWORD("IN"), ", ".join( ["'%s'" % sequence_info["table"] for sequence_info in sequences] ), ), ] def adapt_datetimefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value # SQLite doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError( "SQLite backend does not support timezone-aware datetimes when " "USE_TZ is False." ) return str(value) def adapt_timefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value # SQLite doesn't support tz-aware datetimes if timezone.is_aware(value): raise ValueError("SQLite backend does not support timezone-aware times.") return str(value) def get_db_converters(self, expression): converters = super().get_db_converters(expression) internal_type = expression.output_field.get_internal_type() if internal_type == "DateTimeField": converters.append(self.convert_datetimefield_value) elif internal_type == "DateField": converters.append(self.convert_datefield_value) elif internal_type == "TimeField": converters.append(self.convert_timefield_value) elif internal_type == "DecimalField": converters.append(self.get_decimalfield_converter(expression)) elif internal_type == "UUIDField": converters.append(self.convert_uuidfield_value) elif internal_type == "BooleanField": converters.append(self.convert_booleanfield_value) return converters def convert_datetimefield_value(self, value, expression, connection): if value is not None: if not isinstance(value, datetime.datetime): value = parse_datetime(value) if settings.USE_TZ and not timezone.is_aware(value): value = timezone.make_aware(value, self.connection.timezone) return value def convert_datefield_value(self, value, expression, connection): if value is not None: if not isinstance(value, datetime.date): value = parse_date(value) return value def convert_timefield_value(self, value, expression, connection): if value is not None: if not isinstance(value, datetime.time): value = parse_time(value) return value def get_decimalfield_converter(self, expression): # SQLite stores only 15 significant digits. Digits coming from # float inaccuracy must be removed. create_decimal = decimal.Context(prec=15).create_decimal_from_float if isinstance(expression, Col): quantize_value = decimal.Decimal(1).scaleb( -expression.output_field.decimal_places ) def converter(value, expression, connection): if value is not None: return create_decimal(value).quantize( quantize_value, context=expression.output_field.context ) else: def converter(value, expression, connection): if value is not None: return create_decimal(value) return converter def convert_uuidfield_value(self, value, expression, connection): if value is not None: value = uuid.UUID(value) return value def convert_booleanfield_value(self, value, expression, connection): return bool(value) if value in (1, 0) else value def bulk_insert_sql(self, fields, placeholder_rows): placeholder_rows_sql = (", ".join(row) for row in placeholder_rows) values_sql = ", ".join(f"({sql})" for sql in placeholder_rows_sql) return f"VALUES {values_sql}" def combine_expression(self, connector, sub_expressions): # SQLite doesn't have a ^ operator, so use the user-defined POWER # function that's registered in connect(). if connector == "^": return "POWER(%s)" % ",".join(sub_expressions) elif connector == "#": return "BITXOR(%s)" % ",".join(sub_expressions) return super().combine_expression(connector, sub_expressions) def combine_duration_expression(self, connector, sub_expressions): if connector not in ["+", "-", "*", "/"]: raise DatabaseError("Invalid connector for timedelta: %s." % connector) fn_params = ["'%s'" % connector] + sub_expressions if len(fn_params) > 3: raise ValueError("Too many params for timedelta operations.") return "django_format_dtdelta(%s)" % ", ".join(fn_params) def integer_field_range(self, internal_type): # SQLite doesn't enforce any integer constraints, but sqlite3 supports # integers up to 64 bits. if internal_type in [ "PositiveBigIntegerField", "PositiveIntegerField", "PositiveSmallIntegerField", ]: return (0, 9223372036854775807) return (-9223372036854775808, 9223372036854775807) def subtract_temporals(self, internal_type, lhs, rhs): lhs_sql, lhs_params = lhs rhs_sql, rhs_params = rhs params = (*lhs_params, *rhs_params) if internal_type == "TimeField": return "django_time_diff(%s, %s)" % (lhs_sql, rhs_sql), params return "django_timestamp_diff(%s, %s)" % (lhs_sql, rhs_sql), params def insert_statement(self, on_conflict=None): if on_conflict == OnConflict.IGNORE: return "INSERT OR IGNORE INTO" return super().insert_statement(on_conflict=on_conflict) def return_insert_columns(self, fields): # SQLite < 3.35 doesn't support an INSERT...RETURNING statement. if not fields: return "", () columns = [ "%s.%s" % ( self.quote_name(field.model._meta.db_table), self.quote_name(field.column), ) for field in fields ] return "RETURNING %s" % ", ".join(columns), () def on_conflict_suffix_sql(self, fields, on_conflict, update_fields, unique_fields): if ( on_conflict == OnConflict.UPDATE and self.connection.features.supports_update_conflicts_with_target ): return "ON CONFLICT(%s) DO UPDATE SET %s" % ( ", ".join(map(self.quote_name, unique_fields)), ", ".join( [ f"{field} = EXCLUDED.{field}" for field in map(self.quote_name, update_fields) ] ), ) return super().on_conflict_suffix_sql( fields, on_conflict, update_fields, unique_fields, )
2b9cd51466e1ab53e1c7397e10b62c45360080d12d4715c43eff764e2d90303e
import inspect import re from django.apps import apps as django_apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured, PermissionDenied from django.middleware.csrf import rotate_token from django.utils.crypto import constant_time_compare from django.utils.module_loading import import_string from django.views.decorators.debug import sensitive_variables from .signals import user_logged_in, user_logged_out, user_login_failed SESSION_KEY = "_auth_user_id" BACKEND_SESSION_KEY = "_auth_user_backend" HASH_SESSION_KEY = "_auth_user_hash" REDIRECT_FIELD_NAME = "next" def load_backend(path): return import_string(path)() def _get_backends(return_tuples=False): backends = [] for backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) backends.append((backend, backend_path) if return_tuples else backend) if not backends: raise ImproperlyConfigured( "No authentication backends have been defined. Does " "AUTHENTICATION_BACKENDS contain anything?" ) return backends def get_backends(): return _get_backends(return_tuples=False) @sensitive_variables("credentials") def _clean_credentials(credentials): """ Clean a dictionary of credentials of potentially sensitive info before sending to less secure functions. Not comprehensive - intended for user_login_failed signal """ SENSITIVE_CREDENTIALS = re.compile("api|token|key|secret|password|signature", re.I) CLEANSED_SUBSTITUTE = "********************" for key in credentials: if SENSITIVE_CREDENTIALS.search(key): credentials[key] = CLEANSED_SUBSTITUTE return credentials def _get_user_session_key(request): # This value in the session is always serialized to a string, so we need # to convert it back to Python whenever we access it. return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY]) @sensitive_variables("credentials") def authenticate(request=None, **credentials): """ If the given credentials are valid, return a User object. """ for backend, backend_path in _get_backends(return_tuples=True): backend_signature = inspect.signature(backend.authenticate) try: backend_signature.bind(request, **credentials) except TypeError: # This backend doesn't accept these credentials as arguments. Try # the next one. continue try: user = backend.authenticate(request, **credentials) except PermissionDenied: # This backend says to stop in our tracks - this user should not be # allowed in at all. break if user is None: continue # Annotate the user object with the path of the backend. user.backend = backend_path return user # The credentials supplied are invalid to all backends, fire signal user_login_failed.send( sender=__name__, credentials=_clean_credentials(credentials), request=request ) def login(request, user, backend=None): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ session_auth_hash = "" if user is None: user = request.user if hasattr(user, "get_session_auth_hash"): session_auth_hash = user.get_session_auth_hash() if SESSION_KEY in request.session: if _get_user_session_key(request) != user.pk or ( session_auth_hash and not constant_time_compare( request.session.get(HASH_SESSION_KEY, ""), session_auth_hash ) ): # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. request.session.flush() else: request.session.cycle_key() try: backend = backend or user.backend except AttributeError: backends = _get_backends(return_tuples=True) if len(backends) == 1: _, backend = backends[0] else: raise ValueError( "You have multiple authentication backends configured and " "therefore must provide the `backend` argument or set the " "`backend` attribute on the user." ) else: if not isinstance(backend, str): raise TypeError( "backend must be a dotted import path string (got %r)." % backend ) request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) request.session[BACKEND_SESSION_KEY] = backend request.session[HASH_SESSION_KEY] = session_auth_hash if hasattr(request, "user"): request.user = user rotate_token(request) user_logged_in.send(sender=user.__class__, request=request, user=user) def logout(request): """ Remove the authenticated user's ID from the request and flush their session data. """ # Dispatch the signal before the user is logged out so the receivers have a # chance to find out *who* logged out. user = getattr(request, "user", None) if not getattr(user, "is_authenticated", True): user = None user_logged_out.send(sender=user.__class__, request=request, user=user) request.session.flush() if hasattr(request, "user"): from django.contrib.auth.models import AnonymousUser request.user = AnonymousUser() def get_user_model(): """ Return the User model that is active in this project. """ try: return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) except ValueError: raise ImproperlyConfigured( "AUTH_USER_MODEL must be of the form 'app_label.model_name'" ) except LookupError: raise ImproperlyConfigured( "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL ) def get_user(request): """ Return the user model instance associated with the given request session. If no user is retrieved, return an instance of `AnonymousUser`. """ from .models import AnonymousUser user = None try: user_id = _get_user_session_key(request) backend_path = request.session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) # Verify the session if hasattr(user, "get_session_auth_hash"): session_hash = request.session.get(HASH_SESSION_KEY) if not session_hash: session_hash_verified = False else: session_auth_hash = user.get_session_auth_hash() session_hash_verified = constant_time_compare( session_hash, session_auth_hash ) if not session_hash_verified: # If the current secret does not verify the session, try # with the fallback secrets and stop when a matching one is # found. if session_hash and any( constant_time_compare(session_hash, fallback_auth_hash) for fallback_auth_hash in user.get_session_auth_fallback_hash() ): request.session.cycle_key() request.session[HASH_SESSION_KEY] = session_auth_hash else: request.session.flush() user = None return user or AnonymousUser() def get_permission_codename(action, opts): """ Return the codename of the permission for the specified action. """ return "%s_%s" % (action, opts.model_name) def update_session_auth_hash(request, user): """ Updating a user's password logs out all sessions for the user. Take the current request and the updated user object from which the new session hash will be derived and update the session hash appropriately to prevent a password change from logging out the session from which the password was changed. """ request.session.cycle_key() if hasattr(user, "get_session_auth_hash") and request.user == user: request.session[HASH_SESSION_KEY] = user.get_session_auth_hash()
93ba486fbce9a7c499b310642f4a0ec303fa8d5515943ed744e5dbdb13f3c329
""" This module allows importing AbstractBaseUser even when django.contrib.auth is not in INSTALLED_APPS. """ import unicodedata import warnings from django.conf import settings from django.contrib.auth import password_validation from django.contrib.auth.hashers import ( check_password, is_password_usable, make_password, ) from django.db import models from django.utils.crypto import get_random_string, salted_hmac from django.utils.deprecation import RemovedInDjango51Warning from django.utils.translation import gettext_lazy as _ class BaseUserManager(models.Manager): @classmethod def normalize_email(cls, email): """ Normalize the email address by lowercasing the domain part of it. """ email = email or "" try: email_name, domain_part = email.strip().rsplit("@", 1) except ValueError: pass else: email = email_name + "@" + domain_part.lower() return email def make_random_password( self, length=10, allowed_chars="abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789", ): """ Generate a random password with the given length and given allowed_chars. The default value of allowed_chars does not have "I" or "O" or letters and digits that look similar -- just to avoid confusion. """ warnings.warn( "BaseUserManager.make_random_password() is deprecated.", category=RemovedInDjango51Warning, stacklevel=2, ) return get_random_string(length, allowed_chars) def get_by_natural_key(self, username): return self.get(**{self.model.USERNAME_FIELD: username}) class AbstractBaseUser(models.Model): password = models.CharField(_("password"), max_length=128) last_login = models.DateTimeField(_("last login"), blank=True, null=True) is_active = True REQUIRED_FIELDS = [] # Stores the raw password if set_password() is called so that it can # be passed to password_changed() after the model is saved. _password = None class Meta: abstract = True def __str__(self): return self.get_username() def save(self, *args, **kwargs): super().save(*args, **kwargs) if self._password is not None: password_validation.password_changed(self._password, self) self._password = None def get_username(self): """Return the username for this User.""" return getattr(self, self.USERNAME_FIELD) def clean(self): setattr(self, self.USERNAME_FIELD, self.normalize_username(self.get_username())) def natural_key(self): return (self.get_username(),) @property def is_anonymous(self): """ Always return False. This is a way of comparing User objects to anonymous users. """ return False @property def is_authenticated(self): """ Always return True. This is a way to tell if the user has been authenticated in templates. """ return True def set_password(self, raw_password): self.password = make_password(raw_password) self._password = raw_password def check_password(self, raw_password): """ Return a boolean of whether the raw_password was correct. Handles hashing formats behind the scenes. """ def setter(raw_password): self.set_password(raw_password) # Password hash upgrades shouldn't be considered password changes. self._password = None self.save(update_fields=["password"]) return check_password(raw_password, self.password, setter) def set_unusable_password(self): # Set a value that will never be a valid hash self.password = make_password(None) def has_usable_password(self): """ Return False if set_unusable_password() has been called for this user. """ return is_password_usable(self.password) def get_session_auth_hash(self): """ Return an HMAC of the password field. """ return self._get_session_auth_hash() def get_session_auth_fallback_hash(self): for fallback_secret in settings.SECRET_KEY_FALLBACKS: yield self._get_session_auth_hash(secret=fallback_secret) def _get_session_auth_hash(self, secret=None): key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash" return salted_hmac( key_salt, self.password, secret=secret, algorithm="sha256", ).hexdigest() @classmethod def get_email_field_name(cls): try: return cls.EMAIL_FIELD except AttributeError: return "email" @classmethod def normalize_username(cls, username): return ( unicodedata.normalize("NFKC", username) if isinstance(username, str) else username )
07e7a5bceb7e9cff068faccf5dacc9be190547d2b5da7afaa8d449c802a26fde
import json import os import posixpath import re from hashlib import md5 from urllib.parse import unquote, urldefrag, urlsplit, urlunsplit from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles.utils import check_settings, matches_patterns from django.core.exceptions import ImproperlyConfigured from django.core.files.base import ContentFile from django.core.files.storage import FileSystemStorage, storages from django.utils.functional import LazyObject class StaticFilesStorage(FileSystemStorage): """ Standard file system storage for static files. The defaults for ``location`` and ``base_url`` are ``STATIC_ROOT`` and ``STATIC_URL``. """ def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = settings.STATIC_ROOT if base_url is None: base_url = settings.STATIC_URL check_settings(base_url) super().__init__(location, base_url, *args, **kwargs) # FileSystemStorage fallbacks to MEDIA_ROOT when location # is empty, so we restore the empty value. if not location: self.base_location = None self.location = None def path(self, name): if not self.location: raise ImproperlyConfigured( "You're using the staticfiles app " "without having set the STATIC_ROOT " "setting to a filesystem path." ) return super().path(name) class HashedFilesMixin: default_template = """url("%(url)s")""" max_post_process_passes = 5 patterns = ( ( "*.css", ( r"""(?P<matched>url\(['"]{0,1}\s*(?P<url>.*?)["']{0,1}\))""", ( r"""(?P<matched>@import\s*["']\s*(?P<url>.*?)["'])""", """@import url("%(url)s")""", ), ( ( r"(?m)(?P<matched>)^(/\*#[ \t]" r"(?-i:sourceMappingURL)=(?P<url>.*)[ \t]*\*/)$" ), "/*# sourceMappingURL=%(url)s */", ), ), ), ( "*.js", ( ( r"(?m)(?P<matched>)^(//# (?-i:sourceMappingURL)=(?P<url>.*))$", "//# sourceMappingURL=%(url)s", ), ( ( r"""(?P<matched>import(?s:(?P<import>[\s\{].*?))""" r"""\s*from\s*['"](?P<url>[\.\/].*?)["']\s*;)""" ), """import%(import)s from "%(url)s";""", ), ( ( r"""(?P<matched>export(?s:(?P<exports>[\s\{].*?))""" r"""\s*from\s*["'](?P<url>[\.\/].*?)["']\s*;)""" ), """export%(exports)s from "%(url)s";""", ), ( r"""(?P<matched>import\s*['"](?P<url>[\.\/].*?)["']\s*;)""", """import"%(url)s";""", ), ( r"""(?P<matched>import\(["'](?P<url>.*?)["']\))""", """import("%(url)s")""", ), ), ), ) keep_intermediate_files = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._patterns = {} self.hashed_files = {} for extension, patterns in self.patterns: for pattern in patterns: if isinstance(pattern, (tuple, list)): pattern, template = pattern else: template = self.default_template compiled = re.compile(pattern, re.IGNORECASE) self._patterns.setdefault(extension, []).append((compiled, template)) def file_hash(self, name, content=None): """ Return a hash of the file with the given name and optional content. """ if content is None: return None hasher = md5(usedforsecurity=False) for chunk in content.chunks(): hasher.update(chunk) return hasher.hexdigest()[:12] def hashed_name(self, name, content=None, filename=None): # `filename` is the name of file to hash if `content` isn't given. # `name` is the base name to construct the new hashed filename from. parsed_name = urlsplit(unquote(name)) clean_name = parsed_name.path.strip() filename = (filename and urlsplit(unquote(filename)).path.strip()) or clean_name opened = content is None if opened: if not self.exists(filename): raise ValueError( "The file '%s' could not be found with %r." % (filename, self) ) try: content = self.open(filename) except OSError: # Handle directory paths and fragments return name try: file_hash = self.file_hash(clean_name, content) finally: if opened: content.close() path, filename = os.path.split(clean_name) root, ext = os.path.splitext(filename) file_hash = (".%s" % file_hash) if file_hash else "" hashed_name = os.path.join(path, "%s%s%s" % (root, file_hash, ext)) unparsed_name = list(parsed_name) unparsed_name[2] = hashed_name # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax if "?#" in name and not unparsed_name[3]: unparsed_name[2] += "?" return urlunsplit(unparsed_name) def _url(self, hashed_name_func, name, force=False, hashed_files=None): """ Return the non-hashed URL in DEBUG mode. """ if settings.DEBUG and not force: hashed_name, fragment = name, "" else: clean_name, fragment = urldefrag(name) if urlsplit(clean_name).path.endswith("/"): # don't hash paths hashed_name = name else: args = (clean_name,) if hashed_files is not None: args += (hashed_files,) hashed_name = hashed_name_func(*args) final_url = super().url(hashed_name) # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax query_fragment = "?#" in name # [sic!] if fragment or query_fragment: urlparts = list(urlsplit(final_url)) if fragment and not urlparts[4]: urlparts[4] = fragment if query_fragment and not urlparts[3]: urlparts[2] += "?" final_url = urlunsplit(urlparts) return unquote(final_url) def url(self, name, force=False): """ Return the non-hashed URL in DEBUG mode. """ return self._url(self.stored_name, name, force) def url_converter(self, name, hashed_files, template=None): """ Return the custom URL converter for the given file name. """ if template is None: template = self.default_template def converter(matchobj): """ Convert the matched URL to a normalized and hashed URL. This requires figuring out which files the matched URL resolves to and calling the url() method of the storage. """ matches = matchobj.groupdict() matched = matches["matched"] url = matches["url"] # Ignore absolute/protocol-relative and data-uri URLs. if re.match(r"^[a-z]+:", url): return matched # Ignore absolute URLs that don't point to a static file (dynamic # CSS / JS?). Note that STATIC_URL cannot be empty. if url.startswith("/") and not url.startswith(settings.STATIC_URL): return matched # Strip off the fragment so a path-like fragment won't interfere. url_path, fragment = urldefrag(url) # Ignore URLs without a path if not url_path: return matched if url_path.startswith("/"): # Otherwise the condition above would have returned prematurely. assert url_path.startswith(settings.STATIC_URL) target_name = url_path.removeprefix(settings.STATIC_URL) else: # We're using the posixpath module to mix paths and URLs conveniently. source_name = name if os.sep == "/" else name.replace(os.sep, "/") target_name = posixpath.join(posixpath.dirname(source_name), url_path) # Determine the hashed name of the target file with the storage backend. hashed_url = self._url( self._stored_name, unquote(target_name), force=True, hashed_files=hashed_files, ) transformed_url = "/".join( url_path.split("/")[:-1] + hashed_url.split("/")[-1:] ) # Restore the fragment that was stripped off earlier. if fragment: transformed_url += ("?#" if "?#" in url else "#") + fragment # Return the hashed version to the file matches["url"] = unquote(transformed_url) return template % matches return converter def post_process(self, paths, dry_run=False, **options): """ Post process the given dictionary of files (called from collectstatic). Processing is actually two separate operations: 1. renaming files to include a hash of their content for cache-busting, and copying those files to the target storage. 2. adjusting files which contain references to other files so they refer to the cache-busting filenames. If either of these are performed on a file, then that file is considered post-processed. """ # don't even dare to process the files if we're in dry run mode if dry_run: return # where to store the new paths hashed_files = {} # build a list of adjustable files adjustable_paths = [ path for path in paths if matches_patterns(path, self._patterns) ] # Adjustable files to yield at end, keyed by the original path. processed_adjustable_paths = {} # Do a single pass first. Post-process all files once, yielding not # adjustable files and exceptions, and collecting adjustable files. for name, hashed_name, processed, _ in self._post_process( paths, adjustable_paths, hashed_files ): if name not in adjustable_paths or isinstance(processed, Exception): yield name, hashed_name, processed else: processed_adjustable_paths[name] = (name, hashed_name, processed) paths = {path: paths[path] for path in adjustable_paths} substitutions = False for i in range(self.max_post_process_passes): substitutions = False for name, hashed_name, processed, subst in self._post_process( paths, adjustable_paths, hashed_files ): # Overwrite since hashed_name may be newer. processed_adjustable_paths[name] = (name, hashed_name, processed) substitutions = substitutions or subst if not substitutions: break if substitutions: yield "All", None, RuntimeError("Max post-process passes exceeded.") # Store the processed paths self.hashed_files.update(hashed_files) # Yield adjustable files with final, hashed name. yield from processed_adjustable_paths.values() def _post_process(self, paths, adjustable_paths, hashed_files): # Sort the files by directory level def path_level(name): return len(name.split(os.sep)) for name in sorted(paths, key=path_level, reverse=True): substitutions = True # use the original, local file, not the copied-but-unprocessed # file, which might be somewhere far away, like S3 storage, path = paths[name] with storage.open(path) as original_file: cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) # generate the hash with the original content, even for # adjustable files. if hash_key not in hashed_files: hashed_name = self.hashed_name(name, original_file) else: hashed_name = hashed_files[hash_key] # then get the original's file content.. if hasattr(original_file, "seek"): original_file.seek(0) hashed_file_exists = self.exists(hashed_name) processed = False # ..to apply each replacement pattern to the content if name in adjustable_paths: old_hashed_name = hashed_name try: content = original_file.read().decode("utf-8") except UnicodeDecodeError as exc: yield name, None, exc, False for extension, patterns in self._patterns.items(): if matches_patterns(path, (extension,)): for pattern, template in patterns: converter = self.url_converter( name, hashed_files, template ) try: content = pattern.sub(converter, content) except ValueError as exc: yield name, None, exc, False if hashed_file_exists: self.delete(hashed_name) # then save the processed result content_file = ContentFile(content.encode()) if self.keep_intermediate_files: # Save intermediate file for reference self._save(hashed_name, content_file) hashed_name = self.hashed_name(name, content_file) if self.exists(hashed_name): self.delete(hashed_name) saved_name = self._save(hashed_name, content_file) hashed_name = self.clean_name(saved_name) # If the file hash stayed the same, this file didn't change if old_hashed_name == hashed_name: substitutions = False processed = True if not processed: # or handle the case in which neither processing nor # a change to the original file happened if not hashed_file_exists: processed = True saved_name = self._save(hashed_name, original_file) hashed_name = self.clean_name(saved_name) # and then set the cache accordingly hashed_files[hash_key] = hashed_name yield name, hashed_name, processed, substitutions def clean_name(self, name): return name.replace("\\", "/") def hash_key(self, name): return name def _stored_name(self, name, hashed_files): # Normalize the path to avoid multiple names for the same file like # ../foo/bar.css and ../foo/../foo/bar.css which normalize to the same # path. name = posixpath.normpath(name) cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) cache_name = hashed_files.get(hash_key) if cache_name is None: cache_name = self.clean_name(self.hashed_name(name)) return cache_name def stored_name(self, name): cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) cache_name = self.hashed_files.get(hash_key) if cache_name: return cache_name # No cached name found, recalculate it from the files. intermediate_name = name for i in range(self.max_post_process_passes + 1): cache_name = self.clean_name( self.hashed_name(name, content=None, filename=intermediate_name) ) if intermediate_name == cache_name: # Store the hashed name if there was a miss. self.hashed_files[hash_key] = cache_name return cache_name else: # Move on to the next intermediate file. intermediate_name = cache_name # If the cache name can't be determined after the max number of passes, # the intermediate files on disk may be corrupt; avoid an infinite loop. raise ValueError("The name '%s' could not be hashed with %r." % (name, self)) class ManifestFilesMixin(HashedFilesMixin): manifest_version = "1.1" # the manifest format standard manifest_name = "staticfiles.json" manifest_strict = True keep_intermediate_files = False def __init__(self, *args, manifest_storage=None, **kwargs): super().__init__(*args, **kwargs) if manifest_storage is None: manifest_storage = self self.manifest_storage = manifest_storage self.hashed_files, self.manifest_hash = self.load_manifest() def read_manifest(self): try: with self.manifest_storage.open(self.manifest_name) as manifest: return manifest.read().decode() except FileNotFoundError: return None def load_manifest(self): content = self.read_manifest() if content is None: return {}, "" try: stored = json.loads(content) except json.JSONDecodeError: pass else: version = stored.get("version") if version in ("1.0", "1.1"): return stored.get("paths", {}), stored.get("hash", "") raise ValueError( "Couldn't load manifest '%s' (version %s)" % (self.manifest_name, self.manifest_version) ) def post_process(self, *args, **kwargs): self.hashed_files = {} yield from super().post_process(*args, **kwargs) if not kwargs.get("dry_run"): self.save_manifest() def save_manifest(self): self.manifest_hash = self.file_hash( None, ContentFile(json.dumps(sorted(self.hashed_files.items())).encode()) ) payload = { "paths": self.hashed_files, "version": self.manifest_version, "hash": self.manifest_hash, } if self.manifest_storage.exists(self.manifest_name): self.manifest_storage.delete(self.manifest_name) contents = json.dumps(payload).encode() self.manifest_storage._save(self.manifest_name, ContentFile(contents)) def stored_name(self, name): parsed_name = urlsplit(unquote(name)) clean_name = parsed_name.path.strip() hash_key = self.hash_key(clean_name) cache_name = self.hashed_files.get(hash_key) if cache_name is None: if self.manifest_strict: raise ValueError( "Missing staticfiles manifest entry for '%s'" % clean_name ) cache_name = self.clean_name(self.hashed_name(name)) unparsed_name = list(parsed_name) unparsed_name[2] = cache_name # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax if "?#" in name and not unparsed_name[3]: unparsed_name[2] += "?" return urlunsplit(unparsed_name) class ManifestStaticFilesStorage(ManifestFilesMixin, StaticFilesStorage): """ A static file system storage backend which also saves hashed copies of the files it saves. """ pass class ConfiguredStorage(LazyObject): def _setup(self): self._wrapped = storages[STATICFILES_STORAGE_ALIAS] staticfiles_storage = ConfiguredStorage()
8c02d63a92569c6fe201c8e1d2a31f3d239ec20025b376fd28b59e99a0465e93
from collections import defaultdict from django.apps import apps from django.db import models from django.db.models import Q from django.utils.translation import gettext_lazy as _ class ContentTypeManager(models.Manager): use_in_migrations = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Cache shared by all the get_for_* methods to speed up # ContentType retrieval. self._cache = {} def get_by_natural_key(self, app_label, model): try: ct = self._cache[self.db][(app_label, model)] except KeyError: ct = self.get(app_label=app_label, model=model) self._add_to_cache(self.db, ct) return ct def _get_opts(self, model, for_concrete_model): if for_concrete_model: model = model._meta.concrete_model return model._meta def _get_from_cache(self, opts): key = (opts.app_label, opts.model_name) return self._cache[self.db][key] def get_for_model(self, model, for_concrete_model=True): """ Return the ContentType object for a given model, creating the ContentType if necessary. Lookups are cached so that subsequent lookups for the same model don't hit the database. """ opts = self._get_opts(model, for_concrete_model) try: return self._get_from_cache(opts) except KeyError: pass # The ContentType entry was not found in the cache, therefore we # proceed to load or create it. try: # Start with get() and not get_or_create() in order to use # the db_for_read (see #20401). ct = self.get(app_label=opts.app_label, model=opts.model_name) except self.model.DoesNotExist: # Not found in the database; we proceed to create it. This time # use get_or_create to take care of any race conditions. ct, created = self.get_or_create( app_label=opts.app_label, model=opts.model_name, ) self._add_to_cache(self.db, ct) return ct def get_for_models(self, *models, for_concrete_models=True): """ Given *models, return a dictionary mapping {model: content_type}. """ results = {} # Models that aren't already in the cache grouped by app labels. needed_models = defaultdict(set) # Mapping of opts to the list of models requiring it. needed_opts = defaultdict(list) for model in models: opts = self._get_opts(model, for_concrete_models) try: ct = self._get_from_cache(opts) except KeyError: needed_models[opts.app_label].add(opts.model_name) needed_opts[opts].append(model) else: results[model] = ct if needed_opts: # Lookup required content types from the DB. condition = Q( *( Q(("app_label", app_label), ("model__in", models)) for app_label, models in needed_models.items() ), _connector=Q.OR, ) cts = self.filter(condition) for ct in cts: opts_models = needed_opts.pop( ct._meta.apps.get_model(ct.app_label, ct.model)._meta, [] ) for model in opts_models: results[model] = ct self._add_to_cache(self.db, ct) # Create content types that weren't in the cache or DB. for opts, opts_models in needed_opts.items(): ct = self.create( app_label=opts.app_label, model=opts.model_name, ) self._add_to_cache(self.db, ct) for model in opts_models: results[model] = ct return results def get_for_id(self, id): """ Lookup a ContentType by ID. Use the same shared cache as get_for_model (though ContentTypes are not created on-the-fly by get_by_id). """ try: ct = self._cache[self.db][id] except KeyError: # This could raise a DoesNotExist; that's correct behavior and will # make sure that only correct ctypes get stored in the cache dict. ct = self.get(pk=id) self._add_to_cache(self.db, ct) return ct def clear_cache(self): """ Clear out the content-type cache. """ self._cache.clear() def _add_to_cache(self, using, ct): """Insert a ContentType into the cache.""" # Note it's possible for ContentType objects to be stale; model_class() # will return None. Hence, there is no reliance on # model._meta.app_label here, just using the model fields instead. key = (ct.app_label, ct.model) self._cache.setdefault(using, {})[key] = ct self._cache.setdefault(using, {})[ct.id] = ct class ContentType(models.Model): app_label = models.CharField(max_length=100) model = models.CharField(_("python model class name"), max_length=100) objects = ContentTypeManager() class Meta: verbose_name = _("content type") verbose_name_plural = _("content types") db_table = "django_content_type" unique_together = [["app_label", "model"]] def __str__(self): return self.app_labeled_name @property def name(self): model = self.model_class() if not model: return self.model return str(model._meta.verbose_name) @property def app_labeled_name(self): model = self.model_class() if not model: return self.model return "%s | %s" % ( model._meta.app_config.verbose_name, model._meta.verbose_name, ) def model_class(self): """Return the model class for this type of content.""" try: return apps.get_model(self.app_label, self.model) except LookupError: return None def get_object_for_this_type(self, **kwargs): """ Return an object of this type for the keyword arguments given. Basically, this is a proxy around this object_type's get_object() model method. The ObjectNotExist exception, if thrown, will not be caught, so code that calls this method should catch it. """ return self.model_class()._base_manager.using(self._state.db).get(**kwargs) def get_all_objects_for_this_type(self, **kwargs): """ Return all objects of this type for the keyword arguments given. """ return self.model_class()._base_manager.using(self._state.db).filter(**kwargs) def natural_key(self): return (self.app_label, self.model)
c25c889e3c460b79345bc278f82256dcab976acc768cca93ec55dac648935c71
import functools import re from unittest import mock from django.apps import apps from django.conf import settings from django.contrib.auth.models import AbstractBaseUser from django.core.validators import RegexValidator, validate_slug from django.db import connection, migrations, models from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.graph import MigrationGraph from django.db.migrations.loader import MigrationLoader from django.db.migrations.questioner import MigrationQuestioner from django.db.migrations.state import ModelState, ProjectState from django.test import SimpleTestCase, TestCase, ignore_warnings, override_settings from django.test.utils import isolate_lru_cache from django.utils.deprecation import RemovedInDjango51Warning from .models import FoodManager, FoodQuerySet class DeconstructibleObject: """ A custom deconstructible object. """ def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def deconstruct(self): return (self.__module__ + "." + self.__class__.__name__, self.args, self.kwargs) class BaseAutodetectorTests(TestCase): def repr_changes(self, changes, include_dependencies=False): output = "" for app_label, migrations_ in sorted(changes.items()): output += " %s:\n" % app_label for migration in migrations_: output += " %s\n" % migration.name for operation in migration.operations: output += " %s\n" % operation if include_dependencies: output += " Dependencies:\n" if migration.dependencies: for dep in migration.dependencies: output += " %s\n" % (dep,) else: output += " None\n" return output def assertNumberMigrations(self, changes, app_label, number): if len(changes.get(app_label, [])) != number: self.fail( "Incorrect number of migrations (%s) for %s (expected %s)\n%s" % ( len(changes.get(app_label, [])), app_label, number, self.repr_changes(changes), ) ) def assertMigrationDependencies(self, changes, app_label, position, dependencies): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] if set(migration.dependencies) != set(dependencies): self.fail( "Migration dependencies mismatch for %s.%s (expected %s):\n%s" % ( app_label, migration.name, dependencies, self.repr_changes(changes, include_dependencies=True), ) ) def assertOperationTypes(self, changes, app_label, position, types): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] real_types = [ operation.__class__.__name__ for operation in migration.operations ] if types != real_types: self.fail( "Operation type mismatch for %s.%s (expected %s):\n%s" % ( app_label, migration.name, types, self.repr_changes(changes), ) ) def assertOperationAttributes( self, changes, app_label, position, operation_position, **attrs ): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] if len(changes[app_label]) < position + 1: self.fail( "No operation at index %s for %s.%s\n%s" % ( operation_position, app_label, migration.name, self.repr_changes(changes), ) ) operation = migration.operations[operation_position] for attr, value in attrs.items(): if getattr(operation, attr, None) != value: self.fail( "Attribute mismatch for %s.%s op #%s, %s (expected %r, got %r):\n%s" % ( app_label, migration.name, operation_position, attr, value, getattr(operation, attr, None), self.repr_changes(changes), ) ) def assertOperationFieldAttributes( self, changes, app_label, position, operation_position, **attrs ): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] if len(changes[app_label]) < position + 1: self.fail( "No operation at index %s for %s.%s\n%s" % ( operation_position, app_label, migration.name, self.repr_changes(changes), ) ) operation = migration.operations[operation_position] if not hasattr(operation, "field"): self.fail( "No field attribute for %s.%s op #%s." % ( app_label, migration.name, operation_position, ) ) field = operation.field for attr, value in attrs.items(): if getattr(field, attr, None) != value: self.fail( "Field attribute mismatch for %s.%s op #%s, field.%s (expected %r, " "got %r):\n%s" % ( app_label, migration.name, operation_position, attr, value, getattr(field, attr, None), self.repr_changes(changes), ) ) def make_project_state(self, model_states): "Shortcut to make ProjectStates from lists of predefined models" project_state = ProjectState() for model_state in model_states: project_state.add_model(model_state.clone()) return project_state def get_changes(self, before_states, after_states, questioner=None): if not isinstance(before_states, ProjectState): before_states = self.make_project_state(before_states) if not isinstance(after_states, ProjectState): after_states = self.make_project_state(after_states) return MigrationAutodetector( before_states, after_states, questioner, )._detect_changes() class AutodetectorTests(BaseAutodetectorTests): """ Tests the migration autodetector. """ author_empty = ModelState( "testapp", "Author", [("id", models.AutoField(primary_key=True))] ) author_name = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], ) author_name_null = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, null=True)), ], ) author_name_longer = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=400)), ], ) author_name_renamed = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("names", models.CharField(max_length=200)), ], ) author_name_default = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default="Ada Lovelace")), ], ) author_name_check_constraint = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], { "constraints": [ models.CheckConstraint( check=models.Q(name__contains="Bob"), name="name_contains_bob" ) ] }, ) author_dates_of_birth_auto_now = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("date_of_birth", models.DateField(auto_now=True)), ("date_time_of_birth", models.DateTimeField(auto_now=True)), ("time_of_birth", models.TimeField(auto_now=True)), ], ) author_dates_of_birth_auto_now_add = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("date_of_birth", models.DateField(auto_now_add=True)), ("date_time_of_birth", models.DateTimeField(auto_now_add=True)), ("time_of_birth", models.TimeField(auto_now_add=True)), ], ) author_name_deconstructible_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject())), ], ) author_name_deconstructible_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject())), ], ) author_name_deconstructible_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=models.IntegerField())), ], ) author_name_deconstructible_4 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=models.IntegerField())), ], ) author_name_deconstructible_list_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=[DeconstructibleObject(), 123] ), ), ], ) author_name_deconstructible_list_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=[DeconstructibleObject(), 123] ), ), ], ) author_name_deconstructible_list_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=[DeconstructibleObject(), 999] ), ), ], ) author_name_deconstructible_tuple_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=(DeconstructibleObject(), 123) ), ), ], ) author_name_deconstructible_tuple_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=(DeconstructibleObject(), 123) ), ), ], ) author_name_deconstructible_tuple_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=(DeconstructibleObject(), 999) ), ), ], ) author_name_deconstructible_dict_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default={"item": DeconstructibleObject(), "otheritem": 123}, ), ), ], ) author_name_deconstructible_dict_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default={"item": DeconstructibleObject(), "otheritem": 123}, ), ), ], ) author_name_deconstructible_dict_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default={"item": DeconstructibleObject(), "otheritem": 999}, ), ), ], ) author_name_nested_deconstructible_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_changed_arg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2-changed"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_extra_arg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), None, a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_changed_kwarg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c-changed")), ), ), ), ], ) author_name_nested_deconstructible_extra_kwarg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), c=None, ), ), ), ], ) author_custom_pk = ModelState( "testapp", "Author", [("pk_field", models.IntegerField(primary_key=True))] ) author_with_biography_non_blank = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField()), ("biography", models.TextField()), ], ) author_with_biography_blank = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(blank=True)), ("biography", models.TextField(blank=True)), ], ) author_with_book = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], ) author_with_book_order_wrt = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={"order_with_respect_to": "book"}, ) author_renamed_with_book = ModelState( "testapp", "Writer", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], ) author_with_publisher_string = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("publisher_name", models.CharField(max_length=200)), ], ) author_with_publisher = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ], ) author_with_user = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("user", models.ForeignKey("auth.User", models.CASCADE)), ], ) author_with_custom_user = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("user", models.ForeignKey("thirdapp.CustomUser", models.CASCADE)), ], ) author_proxy = ModelState( "testapp", "AuthorProxy", [], {"proxy": True}, ("testapp.author",) ) author_proxy_options = ModelState( "testapp", "AuthorProxy", [], { "proxy": True, "verbose_name": "Super Author", }, ("testapp.author",), ) author_proxy_notproxy = ModelState( "testapp", "AuthorProxy", [], {}, ("testapp.author",) ) author_proxy_third = ModelState( "thirdapp", "AuthorProxy", [], {"proxy": True}, ("testapp.author",) ) author_proxy_third_notproxy = ModelState( "thirdapp", "AuthorProxy", [], {}, ("testapp.author",) ) author_proxy_proxy = ModelState( "testapp", "AAuthorProxyProxy", [], {"proxy": True}, ("testapp.authorproxy",) ) author_unmanaged = ModelState( "testapp", "AuthorUnmanaged", [], {"managed": False}, ("testapp.author",) ) author_unmanaged_managed = ModelState( "testapp", "AuthorUnmanaged", [], {}, ("testapp.author",) ) author_unmanaged_default_pk = ModelState( "testapp", "Author", [("id", models.AutoField(primary_key=True))] ) author_unmanaged_custom_pk = ModelState( "testapp", "Author", [ ("pk_field", models.IntegerField(primary_key=True)), ], ) author_with_m2m = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher")), ], ) author_with_m2m_blank = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher", blank=True)), ], ) author_with_m2m_through = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "publishers", models.ManyToManyField("testapp.Publisher", through="testapp.Contract"), ), ], ) author_with_renamed_m2m_through = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "publishers", models.ManyToManyField("testapp.Publisher", through="testapp.Deal"), ), ], ) author_with_former_m2m = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.CharField(max_length=100)), ], ) author_with_options = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], { "permissions": [("can_hire", "Can hire")], "verbose_name": "Authi", }, ) author_with_db_table_comment = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table_comment": "Table comment"}, ) author_with_db_table_options = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_one"}, ) author_with_new_db_table_options = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_two"}, ) author_renamed_with_db_table_options = ModelState( "testapp", "NewAuthor", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_one"}, ) author_renamed_with_new_db_table_options = ModelState( "testapp", "NewAuthor", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_three"}, ) contract = ModelState( "testapp", "Contract", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ], ) contract_renamed = ModelState( "testapp", "Deal", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ], ) publisher = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ], ) publisher_with_author = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("name", models.CharField(max_length=100)), ], ) publisher_with_aardvark_author = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Aardvark", models.CASCADE)), ("name", models.CharField(max_length=100)), ], ) publisher_with_book = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("otherapp.Book", models.CASCADE)), ("name", models.CharField(max_length=100)), ], ) other_pony = ModelState( "otherapp", "Pony", [ ("id", models.AutoField(primary_key=True)), ], ) other_pony_food = ModelState( "otherapp", "Pony", [ ("id", models.AutoField(primary_key=True)), ], managers=[ ("food_qs", FoodQuerySet.as_manager()), ("food_mgr", FoodManager("a", "b")), ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)), ], ) other_stable = ModelState( "otherapp", "Stable", [("id", models.AutoField(primary_key=True))] ) third_thing = ModelState( "thirdapp", "Thing", [("id", models.AutoField(primary_key=True))] ) book = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_proxy_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("thirdapp.AuthorProxy", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_proxy_proxy_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.AAuthorProxyProxy", models.CASCADE)), ], ) book_migrations_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("migrations.UnmigratedModel", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_with_no_author_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.IntegerField()), ("title", models.CharField(max_length=200)), ], ) book_with_no_author = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=200)), ], ) book_with_author_renamed = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Writer", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_with_field_and_author_renamed = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("writer", models.ForeignKey("testapp.Writer", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_with_multiple_authors = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("authors", models.ManyToManyField("testapp.Author")), ("title", models.CharField(max_length=200)), ], ) book_with_multiple_authors_through_attribution = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ( "authors", models.ManyToManyField( "testapp.Author", through="otherapp.Attribution" ), ), ("title", models.CharField(max_length=200)), ], ) book_indexes = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [ models.Index(fields=["author", "title"], name="book_title_author_idx") ], }, ) book_unordered_indexes = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [ models.Index(fields=["title", "author"], name="book_author_title_idx") ], }, ) book_unique_together = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "unique_together": {("author", "title")}, }, ) book_unique_together_2 = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "unique_together": {("title", "author")}, }, ) book_unique_together_3 = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "unique_together": {("title", "newfield")}, }, ) book_unique_together_4 = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield2", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "unique_together": {("title", "newfield2")}, }, ) attribution = ModelState( "otherapp", "Attribution", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], ) edition = ModelState( "thirdapp", "Edition", [ ("id", models.AutoField(primary_key=True)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], ) custom_user = ModelState( "thirdapp", "CustomUser", [ ("id", models.AutoField(primary_key=True)), ("username", models.CharField(max_length=255)), ], bases=(AbstractBaseUser,), ) custom_user_no_inherit = ModelState( "thirdapp", "CustomUser", [ ("id", models.AutoField(primary_key=True)), ("username", models.CharField(max_length=255)), ], ) aardvark = ModelState( "thirdapp", "Aardvark", [("id", models.AutoField(primary_key=True))] ) aardvark_testapp = ModelState( "testapp", "Aardvark", [("id", models.AutoField(primary_key=True))] ) aardvark_based_on_author = ModelState( "testapp", "Aardvark", [], bases=("testapp.Author",) ) aardvark_pk_fk_author = ModelState( "testapp", "Aardvark", [ ( "id", models.OneToOneField( "testapp.Author", models.CASCADE, primary_key=True ), ), ], ) knight = ModelState("eggs", "Knight", [("id", models.AutoField(primary_key=True))]) rabbit = ModelState( "eggs", "Rabbit", [ ("id", models.AutoField(primary_key=True)), ("knight", models.ForeignKey("eggs.Knight", models.CASCADE)), ("parent", models.ForeignKey("eggs.Rabbit", models.CASCADE)), ], { "unique_together": {("parent", "knight")}, "indexes": [ models.Index( fields=["parent", "knight"], name="rabbit_circular_fk_index" ) ], }, ) def test_arrange_for_graph(self): """Tests auto-naming of migrations for graph matching.""" # Make a fake graph graph = MigrationGraph() graph.add_node(("testapp", "0001_initial"), None) graph.add_node(("testapp", "0002_foobar"), None) graph.add_node(("otherapp", "0001_initial"), None) graph.add_dependency( "testapp.0002_foobar", ("testapp", "0002_foobar"), ("testapp", "0001_initial"), ) graph.add_dependency( "testapp.0002_foobar", ("testapp", "0002_foobar"), ("otherapp", "0001_initial"), ) # Use project state to make a new migration change set before = self.make_project_state([self.publisher, self.other_pony]) after = self.make_project_state( [ self.author_empty, self.publisher, self.other_pony, self.other_stable, ] ) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Run through arrange_for_graph changes = autodetector.arrange_for_graph(changes, graph) # Make sure there's a new name, deps match, etc. self.assertEqual(changes["testapp"][0].name, "0003_author") self.assertEqual( changes["testapp"][0].dependencies, [("testapp", "0002_foobar")] ) self.assertEqual(changes["otherapp"][0].name, "0002_stable") self.assertEqual( changes["otherapp"][0].dependencies, [("otherapp", "0001_initial")] ) def test_arrange_for_graph_with_multiple_initial(self): # Make a fake graph. graph = MigrationGraph() # Use project state to make a new migration change set. before = self.make_project_state([]) after = self.make_project_state( [self.author_with_book, self.book, self.attribution] ) autodetector = MigrationAutodetector( before, after, MigrationQuestioner({"ask_initial": True}) ) changes = autodetector._detect_changes() changes = autodetector.arrange_for_graph(changes, graph) self.assertEqual(changes["otherapp"][0].name, "0001_initial") self.assertEqual(changes["otherapp"][0].dependencies, []) self.assertEqual(changes["otherapp"][1].name, "0002_initial") self.assertCountEqual( changes["otherapp"][1].dependencies, [("testapp", "0001_initial"), ("otherapp", "0001_initial")], ) self.assertEqual(changes["testapp"][0].name, "0001_initial") self.assertEqual( changes["testapp"][0].dependencies, [("otherapp", "0001_initial")] ) def test_trim_apps(self): """ Trim does not remove dependencies but does remove unwanted apps. """ # Use project state to make a new migration change set before = self.make_project_state([]) after = self.make_project_state( [self.author_empty, self.other_pony, self.other_stable, self.third_thing] ) autodetector = MigrationAutodetector( before, after, MigrationQuestioner({"ask_initial": True}) ) changes = autodetector._detect_changes() # Run through arrange_for_graph graph = MigrationGraph() changes = autodetector.arrange_for_graph(changes, graph) changes["testapp"][0].dependencies.append(("otherapp", "0001_initial")) changes = autodetector._trim_to_apps(changes, {"testapp"}) # Make sure there's the right set of migrations self.assertEqual(changes["testapp"][0].name, "0001_initial") self.assertEqual(changes["otherapp"][0].name, "0001_initial") self.assertNotIn("thirdapp", changes) def test_custom_migration_name(self): """Tests custom naming of migrations for graph matching.""" # Make a fake graph graph = MigrationGraph() graph.add_node(("testapp", "0001_initial"), None) graph.add_node(("testapp", "0002_foobar"), None) graph.add_node(("otherapp", "0001_initial"), None) graph.add_dependency( "testapp.0002_foobar", ("testapp", "0002_foobar"), ("testapp", "0001_initial"), ) # Use project state to make a new migration change set before = self.make_project_state([]) after = self.make_project_state( [self.author_empty, self.other_pony, self.other_stable] ) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Run through arrange_for_graph migration_name = "custom_name" changes = autodetector.arrange_for_graph(changes, graph, migration_name) # Make sure there's a new name, deps match, etc. self.assertEqual(changes["testapp"][0].name, "0003_%s" % migration_name) self.assertEqual( changes["testapp"][0].dependencies, [("testapp", "0002_foobar")] ) self.assertEqual(changes["otherapp"][0].name, "0002_%s" % migration_name) self.assertEqual( changes["otherapp"][0].dependencies, [("otherapp", "0001_initial")] ) def test_new_model(self): """Tests autodetection of new models.""" changes = self.get_changes([], [self.other_pony_food]) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Pony") self.assertEqual( [name for name, mgr in changes["otherapp"][0].operations[0].managers], ["food_qs", "food_mgr", "food_mgr_kwargs"], ) def test_old_model(self): """Tests deletion of old models.""" changes = self.get_changes([self.author_empty], []) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["DeleteModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") def test_add_field(self): """Tests autodetection of new fields.""" changes = self.get_changes([self.author_empty], [self.author_name]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name") @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition", side_effect=AssertionError("Should not have prompted for not null addition"), ) def test_add_date_fields_with_auto_now_not_asking_for_default( self, mocked_ask_method ): changes = self.get_changes( [self.author_empty], [self.author_dates_of_birth_auto_now] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AddField", "AddField", "AddField"] ) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, auto_now=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 1, auto_now=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, auto_now=True) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition", side_effect=AssertionError("Should not have prompted for not null addition"), ) def test_add_date_fields_with_auto_now_add_not_asking_for_null_addition( self, mocked_ask_method ): changes = self.get_changes( [self.author_empty], [self.author_dates_of_birth_auto_now_add] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AddField", "AddField", "AddField"] ) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 1, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, auto_now_add=True) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_auto_now_add_addition" ) def test_add_date_fields_with_auto_now_add_asking_for_default( self, mocked_ask_method ): changes = self.get_changes( [self.author_empty], [self.author_dates_of_birth_auto_now_add] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AddField", "AddField", "AddField"] ) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 1, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, auto_now_add=True) self.assertEqual(mocked_ask_method.call_count, 3) def test_remove_field(self): """Tests autodetection of removed fields.""" changes = self.get_changes([self.author_name], [self.author_empty]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RemoveField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name") def test_alter_field(self): """Tests autodetection of new fields.""" changes = self.get_changes([self.author_name], [self.author_name_longer]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="name", preserve_default=True ) def test_supports_functools_partial(self): def _content_file_name(instance, filename, key, **kwargs): return "{}/{}".format(instance, filename) def content_file_name(key, **kwargs): return functools.partial(_content_file_name, key, **kwargs) # An unchanged partial reference. before = [ ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "file", models.FileField( max_length=200, upload_to=content_file_name("file") ), ), ], ) ] after = [ ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "file", models.FileField( max_length=200, upload_to=content_file_name("file") ), ), ], ) ] changes = self.get_changes(before, after) self.assertNumberMigrations(changes, "testapp", 0) # A changed partial reference. args_changed = [ ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "file", models.FileField( max_length=200, upload_to=content_file_name("other-file") ), ), ], ) ] changes = self.get_changes(before, args_changed) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) # Can't use assertOperationFieldAttributes because we need the # deconstructed version, i.e., the exploded func/args/keywords rather # than the partial: we don't care if it's not the same instance of the # partial, only if it's the same source function, args, and keywords. value = changes["testapp"][0].operations[0].field.upload_to self.assertEqual( (_content_file_name, ("other-file",), {}), (value.func, value.args, value.keywords), ) kwargs_changed = [ ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "file", models.FileField( max_length=200, upload_to=content_file_name("file", spam="eggs"), ), ), ], ) ] changes = self.get_changes(before, kwargs_changed) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) value = changes["testapp"][0].operations[0].field.upload_to self.assertEqual( (_content_file_name, ("file",), {"spam": "eggs"}), (value.func, value.args, value.keywords), ) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration", side_effect=AssertionError("Should not have prompted for not null addition"), ) def test_alter_field_to_not_null_with_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ changes = self.get_changes([self.author_name_null], [self.author_name_default]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="name", preserve_default=True ) self.assertOperationFieldAttributes( changes, "testapp", 0, 0, default="Ada Lovelace" ) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration", return_value=models.NOT_PROVIDED, ) def test_alter_field_to_not_null_without_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ changes = self.get_changes([self.author_name_null], [self.author_name]) self.assertEqual(mocked_ask_method.call_count, 1) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="name", preserve_default=True ) self.assertOperationFieldAttributes( changes, "testapp", 0, 0, default=models.NOT_PROVIDED ) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration", return_value="Some Name", ) def test_alter_field_to_not_null_oneoff_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ changes = self.get_changes([self.author_name_null], [self.author_name]) self.assertEqual(mocked_ask_method.call_count, 1) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="name", preserve_default=False ) self.assertOperationFieldAttributes( changes, "testapp", 0, 0, default="Some Name" ) def test_rename_field(self): """Tests autodetection of renamed fields.""" changes = self.get_changes( [self.author_name], [self.author_name_renamed], MigrationQuestioner({"ask_rename": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="name", new_name="names" ) def test_rename_field_foreign_key_to_field(self): before = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField(unique=True)), ], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ( "foo", models.ForeignKey("app.Foo", models.CASCADE, to_field="field"), ), ], ), ] after = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("renamed_field", models.IntegerField(unique=True)), ], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ( "foo", models.ForeignKey( "app.Foo", models.CASCADE, to_field="renamed_field" ), ), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) # Right number/type of migrations? self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["RenameField"]) self.assertOperationAttributes( changes, "app", 0, 0, old_name="field", new_name="renamed_field" ) def test_rename_foreign_object_fields(self): fields = ("first", "second") renamed_fields = ("first_renamed", "second_renamed") before = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("first", models.IntegerField()), ("second", models.IntegerField()), ], options={"unique_together": {fields}}, ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("first", models.IntegerField()), ("second", models.IntegerField()), ( "foo", models.ForeignObject( "app.Foo", models.CASCADE, from_fields=fields, to_fields=fields, ), ), ], ), ] # Case 1: to_fields renames. after = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("first_renamed", models.IntegerField()), ("second_renamed", models.IntegerField()), ], options={"unique_together": {renamed_fields}}, ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("first", models.IntegerField()), ("second", models.IntegerField()), ( "foo", models.ForeignObject( "app.Foo", models.CASCADE, from_fields=fields, to_fields=renamed_fields, ), ), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes( changes, "app", 0, ["RenameField", "RenameField", "AlterUniqueTogether"] ) self.assertOperationAttributes( changes, "app", 0, 0, model_name="foo", old_name="first", new_name="first_renamed", ) self.assertOperationAttributes( changes, "app", 0, 1, model_name="foo", old_name="second", new_name="second_renamed", ) # Case 2: from_fields renames. after = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("first", models.IntegerField()), ("second", models.IntegerField()), ], options={"unique_together": {fields}}, ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("first_renamed", models.IntegerField()), ("second_renamed", models.IntegerField()), ( "foo", models.ForeignObject( "app.Foo", models.CASCADE, from_fields=renamed_fields, to_fields=fields, ), ), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["RenameField", "RenameField"]) self.assertOperationAttributes( changes, "app", 0, 0, model_name="bar", old_name="first", new_name="first_renamed", ) self.assertOperationAttributes( 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 old field's column is added. """ before = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField()), ], ), ] after = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("renamed_field", models.IntegerField(db_column="field")), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["AlterField", "RenameField"]) self.assertOperationAttributes( changes, "app", 0, 0, model_name="foo", name="field", ) self.assertEqual( changes["app"][0].operations[0].field.deconstruct(), ( "field", "django.db.models.IntegerField", [], {"db_column": "field"}, ), ) self.assertOperationAttributes( changes, "app", 0, 1, model_name="foo", old_name="field", new_name="renamed_field", ) def test_rename_related_field_preserved_db_column(self): before = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("foo", models.ForeignKey("app.Foo", models.CASCADE)), ], ), ] after = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ( "renamed_foo", models.ForeignKey( "app.Foo", models.CASCADE, db_column="foo_id" ), ), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["AlterField", "RenameField"]) self.assertOperationAttributes( changes, "app", 0, 0, model_name="bar", name="foo", ) self.assertEqual( changes["app"][0].operations[0].field.deconstruct(), ( "foo", "django.db.models.ForeignKey", [], {"to": "app.foo", "on_delete": models.CASCADE, "db_column": "foo_id"}, ), ) self.assertOperationAttributes( changes, "app", 0, 1, model_name="bar", old_name="foo", new_name="renamed_foo", ) def test_rename_field_with_renamed_model(self): changes = self.get_changes( [self.author_name], [ ModelState( "testapp", "RenamedAuthor", [ ("id", models.AutoField(primary_key=True)), ("renamed_name", models.CharField(max_length=200)), ], ), ], MigrationQuestioner({"ask_rename_model": True, "ask_rename": True}), ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel", "RenameField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Author", new_name="RenamedAuthor", ) self.assertOperationAttributes( changes, "testapp", 0, 1, old_name="name", new_name="renamed_name", ) def test_rename_model(self): """Tests autodetection of renamed models.""" changes = self.get_changes( [self.author_with_book, self.book], [self.author_renamed_with_book, self.book_with_author_renamed], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Author", new_name="Writer" ) # Now that RenameModel handles related fields too, there should be # no AlterField for the related field. self.assertNumberMigrations(changes, "otherapp", 0) def test_rename_model_case(self): """ Model name is case-insensitive. Changing case doesn't lead to any autodetected operations. """ author_renamed = ModelState( "testapp", "author", [ ("id", models.AutoField(primary_key=True)), ], ) changes = self.get_changes( [self.author_empty, self.book], [author_renamed, self.book], questioner=MigrationQuestioner({"ask_rename_model": True}), ) self.assertNumberMigrations(changes, "testapp", 0) self.assertNumberMigrations(changes, "otherapp", 0) def test_renamed_referenced_m2m_model_case(self): publisher_renamed = ModelState( "testapp", "publisher", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ], ) changes = self.get_changes( [self.publisher, self.author_with_m2m], [publisher_renamed, self.author_with_m2m], questioner=MigrationQuestioner({"ask_rename_model": True}), ) self.assertNumberMigrations(changes, "testapp", 0) self.assertNumberMigrations(changes, "otherapp", 0) def test_rename_m2m_through_model(self): """ Tests autodetection of renamed models that are used in M2M relations as through models. """ changes = self.get_changes( [self.author_with_m2m_through, self.publisher, self.contract], [ self.author_with_renamed_m2m_through, self.publisher, self.contract_renamed, ], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Contract", new_name="Deal" ) def test_rename_model_with_renamed_rel_field(self): """ Tests autodetection of renamed models while simultaneously renaming one of the fields that relate to the renamed model. """ changes = self.get_changes( [self.author_with_book, self.book], [self.author_renamed_with_book, self.book_with_field_and_author_renamed], MigrationQuestioner({"ask_rename": True, "ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Author", new_name="Writer" ) # Right number/type of migrations for related field rename? # Alter is already taken care of. self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RenameField"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, old_name="author", new_name="writer" ) def test_rename_model_with_fks_in_different_position(self): """ #24537 - The order of fields in a model does not influence the RenameModel detection. """ before = [ ModelState( "testapp", "EntityA", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "testapp", "EntityB", [ ("id", models.AutoField(primary_key=True)), ("some_label", models.CharField(max_length=255)), ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)), ], ), ] after = [ ModelState( "testapp", "EntityA", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "testapp", "RenamedEntityB", [ ("id", models.AutoField(primary_key=True)), ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)), ("some_label", models.CharField(max_length=255)), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename_model": True}) ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="EntityB", new_name="RenamedEntityB" ) def test_rename_model_reverse_relation_dependencies(self): """ The migration to rename a model pointed to by a foreign key in another app must run after the other app's migration that adds the foreign key with model's original name. Therefore, the renaming migration has a dependency on that other migration. """ before = [ ModelState( "testapp", "EntityA", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "otherapp", "EntityB", [ ("id", models.AutoField(primary_key=True)), ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)), ], ), ] after = [ ModelState( "testapp", "RenamedEntityA", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "otherapp", "EntityB", [ ("id", models.AutoField(primary_key=True)), ( "entity_a", models.ForeignKey("testapp.RenamedEntityA", models.CASCADE), ), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename_model": True}) ) self.assertNumberMigrations(changes, "testapp", 1) self.assertMigrationDependencies( changes, "testapp", 0, [("otherapp", "__first__")] ) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="EntityA", new_name="RenamedEntityA" ) def test_fk_dependency(self): """Having a ForeignKey automatically adds a dependency.""" # Note that testapp (author) has no dependencies, # otherapp (book) depends on testapp (author), # thirdapp (edition) depends on otherapp (book) changes = self.get_changes([], [self.author_name, self.book, self.edition]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertMigrationDependencies(changes, "testapp", 0, []) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Book") self.assertMigrationDependencies( changes, "otherapp", 0, [("testapp", "auto_1")] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "thirdapp", 1) self.assertOperationTypes(changes, "thirdapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "thirdapp", 0, 0, name="Edition") self.assertMigrationDependencies( changes, "thirdapp", 0, [("otherapp", "auto_1")] ) def test_proxy_fk_dependency(self): """FK dependencies still work on proxy models.""" # Note that testapp (author) has no dependencies, # otherapp (book) depends on testapp (authorproxy) changes = self.get_changes( [], [self.author_empty, self.author_proxy_third, self.book_proxy_fk] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertMigrationDependencies(changes, "testapp", 0, []) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Book") self.assertMigrationDependencies( changes, "otherapp", 0, [("thirdapp", "auto_1")] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "thirdapp", 1) self.assertOperationTypes(changes, "thirdapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "thirdapp", 0, 0, name="AuthorProxy") self.assertMigrationDependencies( changes, "thirdapp", 0, [("testapp", "auto_1")] ) def test_same_app_no_fk_dependency(self): """ A migration with a FK between two models of the same app does not have a dependency to itself. """ changes = self.get_changes([], [self.author_with_publisher, self.publisher]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Author") self.assertMigrationDependencies(changes, "testapp", 0, []) def test_circular_fk_dependency(self): """ Having a circular ForeignKey dependency automatically resolves the situation into 2 migrations on one side and 1 on the other. """ changes = self.get_changes( [], [self.author_with_book, self.book, self.publisher_with_book] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertMigrationDependencies( changes, "testapp", 0, [("otherapp", "auto_1")] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 2) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationTypes(changes, "otherapp", 1, ["AddField"]) self.assertMigrationDependencies(changes, "otherapp", 0, []) self.assertMigrationDependencies( changes, "otherapp", 1, [("otherapp", "auto_1"), ("testapp", "auto_1")] ) # both split migrations should be `initial` self.assertTrue(changes["otherapp"][0].initial) self.assertTrue(changes["otherapp"][1].initial) def test_same_app_circular_fk_dependency(self): """ A migration with a FK between two models of the same app does not have a dependency to itself. """ changes = self.get_changes( [], [self.author_with_publisher, self.publisher_with_author] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["CreateModel", "CreateModel", "AddField"] ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 2, name="publisher") self.assertMigrationDependencies(changes, "testapp", 0, []) def test_same_app_circular_fk_dependency_with_unique_together_and_indexes(self): """ #22275 - A migration with circular FK dependency does not try to create unique together constraint and indexes before creating all required fields first. """ changes = self.get_changes([], [self.knight, self.rabbit]) # Right number/type of migrations? self.assertNumberMigrations(changes, "eggs", 1) self.assertOperationTypes( changes, "eggs", 0, ["CreateModel", "CreateModel", "AddIndex", "AlterUniqueTogether"], ) self.assertNotIn("unique_together", changes["eggs"][0].operations[0].options) self.assertNotIn("unique_together", changes["eggs"][0].operations[1].options) self.assertMigrationDependencies(changes, "eggs", 0, []) def test_alter_db_table_add(self): """Tests detection for adding db_table in model's options.""" changes = self.get_changes( [self.author_empty], [self.author_with_db_table_options] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelTable"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", table="author_one" ) def test_alter_db_table_change(self): """Tests detection for changing db_table in model's options'.""" changes = self.get_changes( [self.author_with_db_table_options], [self.author_with_new_db_table_options] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelTable"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", table="author_two" ) def test_alter_db_table_remove(self): """Tests detection for removing db_table in model's options.""" changes = self.get_changes( [self.author_with_db_table_options], [self.author_empty] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelTable"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", table=None ) def test_alter_db_table_no_changes(self): """ Alter_db_table doesn't generate a migration if no changes have been made. """ changes = self.get_changes( [self.author_with_db_table_options], [self.author_with_db_table_options] ) # Right number of migrations? self.assertEqual(len(changes), 0) def test_keep_db_table_with_model_change(self): """ Tests when model changes but db_table stays as-is, autodetector must not create more than one operation. """ changes = self.get_changes( [self.author_with_db_table_options], [self.author_renamed_with_db_table_options], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Author", new_name="NewAuthor" ) def test_alter_db_table_with_model_change(self): """ Tests when model and db_table changes, autodetector must create two operations. """ changes = self.get_changes( [self.author_with_db_table_options], [self.author_renamed_with_new_db_table_options], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["RenameModel", "AlterModelTable"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Author", new_name="NewAuthor" ) self.assertOperationAttributes( changes, "testapp", 0, 1, name="newauthor", table="author_three" ) def test_alter_db_table_comment_add(self): changes = self.get_changes( [self.author_empty], [self.author_with_db_table_comment] ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelTableComment"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", table_comment="Table comment" ) def test_alter_db_table_comment_change(self): author_with_new_db_table_comment = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table_comment": "New table comment"}, ) changes = self.get_changes( [self.author_with_db_table_comment], [author_with_new_db_table_comment], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelTableComment"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", table_comment="New table comment", ) def test_alter_db_table_comment_remove(self): changes = self.get_changes( [self.author_with_db_table_comment], [self.author_empty], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelTableComment"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", db_table_comment=None ) def test_alter_db_table_comment_no_changes(self): changes = self.get_changes( [self.author_with_db_table_comment], [self.author_with_db_table_comment], ) self.assertNumberMigrations(changes, "testapp", 0) def test_identical_regex_doesnt_alter(self): from_state = ModelState( "testapp", "model", [ ( "id", models.AutoField( primary_key=True, validators=[ RegexValidator( re.compile("^[-a-zA-Z0-9_]+\\Z"), "Enter a valid “slug” consisting of letters, numbers, " "underscores or hyphens.", "invalid", ) ], ), ) ], ) to_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))], ) changes = self.get_changes([from_state], [to_state]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 0) def test_different_regex_does_alter(self): from_state = ModelState( "testapp", "model", [ ( "id", models.AutoField( primary_key=True, validators=[ RegexValidator( re.compile("^[a-z]+\\Z", 32), "Enter a valid “slug” consisting of letters, numbers, " "underscores or hyphens.", "invalid", ) ], ), ) ], ) to_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))], ) changes = self.get_changes([from_state], [to_state]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) def test_alter_regex_string_to_compiled_regex(self): regex_string = "^[a-z]+$" from_state = ModelState( "testapp", "model", [ ( "id", models.AutoField( primary_key=True, validators=[RegexValidator(regex_string)] ), ) ], ) to_state = ModelState( "testapp", "model", [ ( "id", models.AutoField( primary_key=True, validators=[RegexValidator(re.compile(regex_string))], ), ) ], ) changes = self.get_changes([from_state], [to_state]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) def test_empty_unique_together(self): """Empty unique_together shouldn't generate a migration.""" # Explicitly testing for not specified, since this is the case after # a CreateModel operation w/o any definition on the original model model_state_not_specified = ModelState( "a", "model", [("id", models.AutoField(primary_key=True))] ) # Explicitly testing for None, since this was the issue in #23452 after # an AlterUniqueTogether operation with e.g. () as value model_state_none = ModelState( "a", "model", [("id", models.AutoField(primary_key=True))], { "unique_together": None, }, ) # Explicitly testing for the empty set, since we now always have sets. # During removal (('col1', 'col2'),) --> () this becomes set([]) model_state_empty = ModelState( "a", "model", [("id", models.AutoField(primary_key=True))], { "unique_together": set(), }, ) def test(from_state, to_state, msg): changes = self.get_changes([from_state], [to_state]) if changes: ops = ", ".join( o.__class__.__name__ for o in changes["a"][0].operations ) self.fail("Created operation(s) %s from %s" % (ops, msg)) tests = ( ( model_state_not_specified, model_state_not_specified, '"not specified" to "not specified"', ), (model_state_not_specified, model_state_none, '"not specified" to "None"'), ( model_state_not_specified, model_state_empty, '"not specified" to "empty"', ), (model_state_none, model_state_not_specified, '"None" to "not specified"'), (model_state_none, model_state_none, '"None" to "None"'), (model_state_none, model_state_empty, '"None" to "empty"'), ( model_state_empty, model_state_not_specified, '"empty" to "not specified"', ), (model_state_empty, model_state_none, '"empty" to "None"'), (model_state_empty, model_state_empty, '"empty" to "empty"'), ) for t in tests: test(*t) def test_create_model_with_indexes(self): """Test creation of new model with indexes already defined.""" author = ModelState( "otherapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], { "indexes": [ models.Index(fields=["name"], name="create_model_with_indexes_idx") ] }, ) changes = self.get_changes([], [author]) added_index = models.Index( fields=["name"], name="create_model_with_indexes_idx" ) # Right number of migrations? self.assertEqual(len(changes["otherapp"]), 1) # Right number of actions? migration = changes["otherapp"][0] self.assertEqual(len(migration.operations), 2) # Right actions order? self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel", "AddIndex"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Author") self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="author", index=added_index ) def test_add_indexes(self): """Test change detection of new indexes.""" changes = self.get_changes( [self.author_empty, self.book], [self.author_empty, self.book_indexes] ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AddIndex"]) added_index = models.Index( fields=["author", "title"], name="book_title_author_idx" ) self.assertOperationAttributes( changes, "otherapp", 0, 0, model_name="book", index=added_index ) def test_remove_indexes(self): """Test change detection of removed indexes.""" changes = self.get_changes( [self.author_empty, self.book_indexes], [self.author_empty, self.book] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RemoveIndex"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, model_name="book", name="book_title_author_idx" ) def test_rename_indexes(self): book_renamed_indexes = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [ models.Index( fields=["author", "title"], name="renamed_book_title_author_idx" ) ], }, ) changes = self.get_changes( [self.author_empty, self.book_indexes], [self.author_empty, book_renamed_indexes], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RenameIndex"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, model_name="book", new_name="renamed_book_title_author_idx", old_name="book_title_author_idx", ) def test_order_fields_indexes(self): """Test change detection of reordering of fields in indexes.""" changes = self.get_changes( [self.author_empty, self.book_indexes], [self.author_empty, self.book_unordered_indexes], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RemoveIndex", "AddIndex"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, model_name="book", name="book_title_author_idx" ) added_index = models.Index( fields=["title", "author"], name="book_author_title_idx" ) self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="book", index=added_index ) def test_create_model_with_check_constraint(self): """Test creation of new model with constraints already defined.""" author = ModelState( "otherapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], { "constraints": [ models.CheckConstraint( check=models.Q(name__contains="Bob"), name="name_contains_bob" ) ] }, ) changes = self.get_changes([], [author]) added_constraint = models.CheckConstraint( check=models.Q(name__contains="Bob"), name="name_contains_bob" ) # Right number of migrations? self.assertEqual(len(changes["otherapp"]), 1) # Right number of actions? migration = changes["otherapp"][0] self.assertEqual(len(migration.operations), 2) # Right actions order? self.assertOperationTypes( changes, "otherapp", 0, ["CreateModel", "AddConstraint"] ) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Author") self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="author", constraint=added_constraint ) def test_add_constraints(self): """Test change detection of new constraints.""" changes = self.get_changes( [self.author_name], [self.author_name_check_constraint] ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddConstraint"]) added_constraint = models.CheckConstraint( check=models.Q(name__contains="Bob"), name="name_contains_bob" ) self.assertOperationAttributes( changes, "testapp", 0, 0, model_name="author", constraint=added_constraint ) def test_add_constraints_with_new_model(self): book_with_unique_title_and_pony = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=200)), ("pony", models.ForeignKey("otherapp.Pony", models.CASCADE)), ], { "constraints": [ models.UniqueConstraint( fields=["title", "pony"], name="unique_title_pony", ) ] }, ) changes = self.get_changes( [self.book_with_no_author], [book_with_unique_title_and_pony, self.other_pony], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["CreateModel", "AddField", "AddConstraint"], ) def test_add_index_with_new_model(self): book_with_index_title_and_pony = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=200)), ("pony", models.ForeignKey("otherapp.Pony", models.CASCADE)), ], { "indexes": [ models.Index(fields=["title", "pony"], name="index_title_pony"), ] }, ) changes = self.get_changes( [self.book_with_no_author], [book_with_index_title_and_pony, self.other_pony], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["CreateModel", "AddField", "AddIndex"], ) def test_remove_constraints(self): """Test change detection of removed constraints.""" changes = self.get_changes( [self.author_name_check_constraint], [self.author_name] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RemoveConstraint"]) self.assertOperationAttributes( changes, "testapp", 0, 0, model_name="author", name="name_contains_bob" ) def test_add_unique_together(self): """Tests unique_together detection.""" changes = self.get_changes( [self.author_empty, self.book], [self.author_empty, self.book_unique_together], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterUniqueTogether"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together={("author", "title")}, ) def test_remove_unique_together(self): """Tests unique_together detection.""" changes = self.get_changes( [self.author_empty, self.book_unique_together], [self.author_empty, self.book], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterUniqueTogether"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together=set() ) def test_unique_together_remove_fk(self): """Tests unique_together and field removal detection & ordering""" changes = self.get_changes( [self.author_empty, self.book_unique_together], [self.author_empty, self.book_with_no_author], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterUniqueTogether", "RemoveField"], ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together=set() ) self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="book", name="author" ) def test_unique_together_no_changes(self): """ unique_together doesn't generate a migration if no changes have been made. """ changes = self.get_changes( [self.author_empty, self.book_unique_together], [self.author_empty, self.book_unique_together], ) # Right number of migrations? self.assertEqual(len(changes), 0) def test_unique_together_ordering(self): """ unique_together also triggers on ordering changes. """ changes = self.get_changes( [self.author_empty, self.book_unique_together], [self.author_empty, self.book_unique_together_2], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterUniqueTogether"], ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together={("title", "author")}, ) def test_add_field_and_unique_together(self): """ Added fields will be created before using them in unique_together. """ changes = self.get_changes( [self.author_empty, self.book], [self.author_empty, self.book_unique_together_3], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AddField", "AlterUniqueTogether"], ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", unique_together={("title", "newfield")}, ) def test_create_model_and_unique_together(self): author = ModelState( "otherapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], ) book_with_author = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("otherapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "unique_together": {("title", "author")}, }, ) changes = self.get_changes( [self.book_with_no_author], [author, book_with_author] ) # Right number of migrations? self.assertEqual(len(changes["otherapp"]), 1) # Right number of actions? migration = changes["otherapp"][0] self.assertEqual(len(migration.operations), 3) # Right actions order? self.assertOperationTypes( changes, "otherapp", 0, ["CreateModel", "AddField", "AlterUniqueTogether"], ) def test_remove_field_and_unique_together(self): """ Removed fields will be removed after updating unique_together. """ changes = self.get_changes( [self.author_empty, self.book_unique_together_3], [self.author_empty, self.book_unique_together], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterUniqueTogether", "RemoveField"], ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together={("author", "title")}, ) self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="book", name="newfield", ) def test_alter_field_and_unique_together(self): """Fields are altered after deleting some unique_together.""" initial_author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField(db_index=True)), ], { "unique_together": {("name",)}, }, ) author_reversed_constraints = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, unique=True)), ("age", models.IntegerField()), ], { "unique_together": {("age",)}, }, ) changes = self.get_changes([initial_author], [author_reversed_constraints]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, [ "AlterUniqueTogether", "AlterField", "AlterField", "AlterUniqueTogether", ], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", unique_together=set(), ) self.assertOperationAttributes( changes, "testapp", 0, 1, model_name="author", name="age", ) self.assertOperationAttributes( changes, "testapp", 0, 2, model_name="author", name="name", ) self.assertOperationAttributes( changes, "testapp", 0, 3, name="author", unique_together={("age",)}, ) def test_partly_alter_unique_together_increase(self): initial_author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "unique_together": {("name",)}, }, ) author_new_constraints = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "unique_together": {("name",), ("age",)}, }, ) changes = self.get_changes([initial_author], [author_new_constraints]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AlterUniqueTogether"], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", unique_together={("name",), ("age",)}, ) def test_partly_alter_unique_together_decrease(self): initial_author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "unique_together": {("name",), ("age",)}, }, ) author_new_constraints = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "unique_together": {("name",)}, }, ) changes = self.get_changes([initial_author], [author_new_constraints]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AlterUniqueTogether"], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", unique_together={("name",)}, ) def test_rename_field_and_unique_together(self): """Fields are renamed before updating unique_together.""" changes = self.get_changes( [self.author_empty, self.book_unique_together_3], [self.author_empty, self.book_unique_together_4], MigrationQuestioner({"ask_rename": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["RenameField", "AlterUniqueTogether"], ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", unique_together={("title", "newfield2")}, ) def test_proxy(self): """The autodetector correctly deals with proxy models.""" # First, we test adding a proxy model changes = self.get_changes( [self.author_empty], [self.author_empty, self.author_proxy] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="AuthorProxy", options={"proxy": True, "indexes": [], "constraints": []}, ) # Now, we test turning a proxy model into a non-proxy model # It should delete the proxy then make the real one changes = self.get_changes( [self.author_empty, self.author_proxy], [self.author_empty, self.author_proxy_notproxy], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["DeleteModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="AuthorProxy") self.assertOperationAttributes( changes, "testapp", 0, 1, name="AuthorProxy", options={} ) def test_proxy_non_model_parent(self): class Mixin: pass author_proxy_non_model_parent = ModelState( "testapp", "AuthorProxy", [], {"proxy": True}, (Mixin, "testapp.author"), ) changes = self.get_changes( [self.author_empty], [self.author_empty, author_proxy_non_model_parent], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="AuthorProxy", options={"proxy": True, "indexes": [], "constraints": []}, bases=(Mixin, "testapp.author"), ) def test_proxy_custom_pk(self): """ #23415 - The autodetector must correctly deal with custom FK on proxy models. """ # First, we test the default pk field name changes = self.get_changes( [], [self.author_empty, self.author_proxy_third, self.book_proxy_fk] ) # The model the FK is pointing from and to. self.assertEqual( changes["otherapp"][0].operations[0].fields[2][1].remote_field.model, "thirdapp.AuthorProxy", ) # Now, we test the custom pk field name changes = self.get_changes( [], [self.author_custom_pk, self.author_proxy_third, self.book_proxy_fk] ) # The model the FK is pointing from and to. self.assertEqual( changes["otherapp"][0].operations[0].fields[2][1].remote_field.model, "thirdapp.AuthorProxy", ) def test_proxy_to_mti_with_fk_to_proxy(self): # First, test the pk table and field name. to_state = self.make_project_state( [self.author_empty, self.author_proxy_third, self.book_proxy_fk], ) changes = self.get_changes([], to_state) fk_field = changes["otherapp"][0].operations[0].fields[2][1] self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ("testapp", "author"), ) self.assertEqual(fk_field.remote_field.model, "thirdapp.AuthorProxy") # Change AuthorProxy to use MTI. from_state = to_state.clone() to_state = self.make_project_state( [self.author_empty, self.author_proxy_third_notproxy, self.book_proxy_fk], ) changes = self.get_changes(from_state, to_state) # Right number/type of migrations for the AuthorProxy model? self.assertNumberMigrations(changes, "thirdapp", 1) self.assertOperationTypes( changes, "thirdapp", 0, ["DeleteModel", "CreateModel"] ) # Right number/type of migrations for the Book model with a FK to # AuthorProxy? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterField"]) # otherapp should depend on thirdapp. self.assertMigrationDependencies( changes, "otherapp", 0, [("thirdapp", "auto_1")] ) # Now, test the pk table and field name. fk_field = changes["otherapp"][0].operations[0].field self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ("thirdapp", "authorproxy"), ) self.assertEqual(fk_field.remote_field.model, "thirdapp.AuthorProxy") def test_proxy_to_mti_with_fk_to_proxy_proxy(self): # First, test the pk table and field name. to_state = self.make_project_state( [ self.author_empty, self.author_proxy, self.author_proxy_proxy, self.book_proxy_proxy_fk, ] ) changes = self.get_changes([], to_state) fk_field = changes["otherapp"][0].operations[0].fields[1][1] self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ("testapp", "author"), ) self.assertEqual(fk_field.remote_field.model, "testapp.AAuthorProxyProxy") # Change AuthorProxy to use MTI. FK still points to AAuthorProxyProxy, # a proxy of AuthorProxy. from_state = to_state.clone() to_state = self.make_project_state( [ self.author_empty, self.author_proxy_notproxy, self.author_proxy_proxy, self.book_proxy_proxy_fk, ] ) changes = self.get_changes(from_state, to_state) # Right number/type of migrations for the AuthorProxy model? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["DeleteModel", "CreateModel"]) # Right number/type of migrations for the Book model with a FK to # AAuthorProxyProxy? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterField"]) # otherapp should depend on testapp. self.assertMigrationDependencies( changes, "otherapp", 0, [("testapp", "auto_1")] ) # Now, test the pk table and field name. fk_field = changes["otherapp"][0].operations[0].field self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ("testapp", "authorproxy"), ) self.assertEqual(fk_field.remote_field.model, "testapp.AAuthorProxyProxy") def test_unmanaged_create(self): """The autodetector correctly deals with managed models.""" # First, we test adding an unmanaged model changes = self.get_changes( [self.author_empty], [self.author_empty, self.author_unmanaged] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="AuthorUnmanaged", options={"managed": False} ) def test_unmanaged_delete(self): changes = self.get_changes( [self.author_empty, self.author_unmanaged], [self.author_empty] ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["DeleteModel"]) def test_unmanaged_to_managed(self): # Now, we test turning an unmanaged model into a managed model changes = self.get_changes( [self.author_empty, self.author_unmanaged], [self.author_empty, self.author_unmanaged_managed], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="authorunmanaged", options={} ) def test_managed_to_unmanaged(self): # Now, we turn managed to unmanaged. changes = self.get_changes( [self.author_empty, self.author_unmanaged_managed], [self.author_empty, self.author_unmanaged], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="authorunmanaged", options={"managed": False} ) def test_unmanaged_custom_pk(self): """ #23415 - The autodetector must correctly deal with custom FK on unmanaged models. """ # First, we test the default pk field name changes = self.get_changes([], [self.author_unmanaged_default_pk, self.book]) # The model the FK on the book model points to. fk_field = changes["otherapp"][0].operations[0].fields[2][1] self.assertEqual(fk_field.remote_field.model, "testapp.Author") # Now, we test the custom pk field name changes = self.get_changes([], [self.author_unmanaged_custom_pk, self.book]) # The model the FK on the book model points to. fk_field = changes["otherapp"][0].operations[0].fields[2][1] self.assertEqual(fk_field.remote_field.model, "testapp.Author") @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") def test_swappable(self): with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes( [self.custom_user], [self.custom_user, self.author_with_custom_user] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertMigrationDependencies( changes, "testapp", 0, [("__setting__", "AUTH_USER_MODEL")] ) def test_swappable_lowercase(self): model_state = ModelState( "testapp", "Document", [ ("id", models.AutoField(primary_key=True)), ( "owner", models.ForeignKey( settings.AUTH_USER_MODEL.lower(), models.CASCADE, ), ), ], ) with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes([], [model_state]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Document") self.assertMigrationDependencies( changes, "testapp", 0, [("__setting__", "AUTH_USER_MODEL")], ) @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") def test_swappable_many_to_many_model_case(self): document_lowercase = ModelState( "testapp", "Document", [ ("id", models.AutoField(primary_key=True)), ("owners", models.ManyToManyField(settings.AUTH_USER_MODEL.lower())), ], ) document = ModelState( "testapp", "Document", [ ("id", models.AutoField(primary_key=True)), ("owners", models.ManyToManyField(settings.AUTH_USER_MODEL)), ], ) with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes( [self.custom_user, document_lowercase], [self.custom_user, document], ) self.assertEqual(len(changes), 0) def test_swappable_changed(self): with isolate_lru_cache(apps.get_swappable_settings_name): before = self.make_project_state([self.custom_user, self.author_with_user]) with override_settings(AUTH_USER_MODEL="thirdapp.CustomUser"): after = self.make_project_state( [self.custom_user, self.author_with_custom_user] ) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, model_name="author", name="user" ) fk_field = changes["testapp"][0].operations[0].field self.assertEqual(fk_field.remote_field.model, "thirdapp.CustomUser") def test_add_field_with_default(self): """#22030 - Adding a field with a default should work.""" changes = self.get_changes([self.author_empty], [self.author_name_default]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name") def test_custom_deconstructible(self): """ Two instances which deconstruct to the same value aren't considered a change. """ changes = self.get_changes( [self.author_name_deconstructible_1], [self.author_name_deconstructible_2] ) # Right number of migrations? self.assertEqual(len(changes), 0) def test_deconstruct_field_kwarg(self): """Field instances are handled correctly by nested deconstruction.""" changes = self.get_changes( [self.author_name_deconstructible_3], [self.author_name_deconstructible_4] ) self.assertEqual(changes, {}) def test_deconstructible_list(self): """Nested deconstruction descends into lists.""" # When lists contain items that deconstruct to identical values, those lists # should be considered equal for the purpose of detecting state changes # (even if the original items are unequal). changes = self.get_changes( [self.author_name_deconstructible_list_1], [self.author_name_deconstructible_list_2], ) self.assertEqual(changes, {}) # Legitimate differences within the deconstructed lists should be reported # as a change changes = self.get_changes( [self.author_name_deconstructible_list_1], [self.author_name_deconstructible_list_3], ) self.assertEqual(len(changes), 1) def test_deconstructible_tuple(self): """Nested deconstruction descends into tuples.""" # When tuples contain items that deconstruct to identical values, those tuples # should be considered equal for the purpose of detecting state changes # (even if the original items are unequal). changes = self.get_changes( [self.author_name_deconstructible_tuple_1], [self.author_name_deconstructible_tuple_2], ) self.assertEqual(changes, {}) # Legitimate differences within the deconstructed tuples should be reported # as a change changes = self.get_changes( [self.author_name_deconstructible_tuple_1], [self.author_name_deconstructible_tuple_3], ) self.assertEqual(len(changes), 1) def test_deconstructible_dict(self): """Nested deconstruction descends into dict values.""" # When dicts contain items whose values deconstruct to identical values, # those dicts should be considered equal for the purpose of detecting # state changes (even if the original values are unequal). changes = self.get_changes( [self.author_name_deconstructible_dict_1], [self.author_name_deconstructible_dict_2], ) self.assertEqual(changes, {}) # Legitimate differences within the deconstructed dicts should be reported # as a change changes = self.get_changes( [self.author_name_deconstructible_dict_1], [self.author_name_deconstructible_dict_3], ) self.assertEqual(len(changes), 1) def test_nested_deconstructible_objects(self): """ Nested deconstruction is applied recursively to the args/kwargs of deconstructed objects. """ # If the items within a deconstructed object's args/kwargs have the same # deconstructed values - whether or not the items themselves are different # instances - then the object as a whole is regarded as unchanged. changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_2], ) self.assertEqual(changes, {}) # Differences that exist solely within the args list of a deconstructed object # should be reported as changes changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_changed_arg], ) self.assertEqual(len(changes), 1) # Additional args should also be reported as a change changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_extra_arg], ) self.assertEqual(len(changes), 1) # Differences that exist solely within the kwargs dict of a deconstructed object # should be reported as changes changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_changed_kwarg], ) self.assertEqual(len(changes), 1) # Additional kwargs should also be reported as a change changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_extra_kwarg], ) self.assertEqual(len(changes), 1) def test_deconstruct_type(self): """ #22951 -- Uninstantiated classes with deconstruct are correctly returned by deep_deconstruct during serialization. """ author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, # IntegerField intentionally not instantiated. default=models.IntegerField, ), ), ], ) changes = self.get_changes([], [author]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) def test_replace_string_with_foreignkey(self): """ #22300 - Adding an FK in the same "spot" as a deleted CharField should work. """ changes = self.get_changes( [self.author_with_publisher_string], [self.author_with_publisher, self.publisher], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["CreateModel", "RemoveField", "AddField"] ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 1, name="publisher_name") self.assertOperationAttributes(changes, "testapp", 0, 2, name="publisher") def test_foreign_key_removed_before_target_model(self): """ Removing an FK and the model it targets in the same change must remove the FK field before the model to maintain consistency. """ changes = self.get_changes( [self.author_with_publisher, self.publisher], [self.author_name] ) # removes both the model and FK # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RemoveField", "DeleteModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="publisher") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition", side_effect=AssertionError("Should not have prompted for not null addition"), ) def test_add_many_to_many(self, mocked_ask_method): """#22435 - Adding a ManyToManyField should not prompt for a default.""" changes = self.get_changes( [self.author_empty, self.publisher], [self.author_with_m2m, self.publisher] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="publishers") def test_alter_many_to_many(self): changes = self.get_changes( [self.author_with_m2m, self.publisher], [self.author_with_m2m_blank, self.publisher], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="publishers") def test_create_with_through_model(self): """ Adding a m2m with a through model and the models that use it should be ordered correctly. """ changes = self.get_changes( [], [self.author_with_m2m_through, self.publisher, self.contract] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, [ "CreateModel", "CreateModel", "CreateModel", "AddField", ], ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 2, name="Contract") self.assertOperationAttributes( changes, "testapp", 0, 3, model_name="author", name="publishers" ) def test_create_with_through_model_separate_apps(self): author_with_m2m_through = ModelState( "authors", "Author", [ ("id", models.AutoField(primary_key=True)), ( "publishers", models.ManyToManyField( "testapp.Publisher", through="contract.Contract" ), ), ], ) contract = ModelState( "contract", "Contract", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("authors.Author", models.CASCADE)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ], ) changes = self.get_changes( [], [author_with_m2m_through, self.publisher, contract] ) self.assertNumberMigrations(changes, "testapp", 1) self.assertNumberMigrations(changes, "contract", 1) self.assertNumberMigrations(changes, "authors", 2) self.assertMigrationDependencies( changes, "authors", 1, {("authors", "auto_1"), ("contract", "auto_1"), ("testapp", "auto_1")}, ) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Publisher") self.assertOperationTypes(changes, "contract", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "contract", 0, 0, name="Contract") self.assertOperationTypes(changes, "authors", 0, ["CreateModel"]) self.assertOperationTypes(changes, "authors", 1, ["AddField"]) self.assertOperationAttributes(changes, "authors", 0, 0, name="Author") self.assertOperationAttributes( changes, "authors", 1, 0, model_name="author", name="publishers" ) def test_many_to_many_removed_before_through_model(self): """ Removing a ManyToManyField and the "through" model in the same change must remove the field before the model to maintain consistency. """ changes = self.get_changes( [ self.book_with_multiple_authors_through_attribution, self.author_name, self.attribution, ], [self.book_with_no_author, self.author_name], ) # Remove both the through model and ManyToMany # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["RemoveField", "DeleteModel"] ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="authors", model_name="book" ) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="Attribution") def test_many_to_many_removed_before_through_model_2(self): """ Removing a model that contains a ManyToManyField and the "through" model in the same change must remove the field before the model to maintain consistency. """ changes = self.get_changes( [ self.book_with_multiple_authors_through_attribution, self.author_name, self.attribution, ], [self.author_name], ) # Remove both the through model and ManyToMany # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["RemoveField", "DeleteModel", "DeleteModel"] ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="authors", model_name="book" ) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="Attribution") self.assertOperationAttributes(changes, "otherapp", 0, 2, name="Book") def test_m2m_w_through_multistep_remove(self): """ A model with a m2m field that specifies a "through" model cannot be removed in the same migration as that through model as the schema will pass through an inconsistent state. The autodetector should produce two migrations to avoid this issue. """ changes = self.get_changes( [self.author_with_m2m_through, self.publisher, self.contract], [self.publisher], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["RemoveField", "RemoveField", "DeleteModel", "DeleteModel"], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", model_name="contract" ) self.assertOperationAttributes( changes, "testapp", 0, 1, name="publisher", model_name="contract" ) self.assertOperationAttributes(changes, "testapp", 0, 2, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 3, name="Contract") def test_concrete_field_changed_to_many_to_many(self): """ #23938 - Changing a concrete field into a ManyToManyField first removes the concrete field and then adds the m2m field. """ changes = self.get_changes( [self.author_with_former_m2m], [self.author_with_m2m, self.publisher] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["CreateModel", "RemoveField", "AddField"] ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Publisher") self.assertOperationAttributes( changes, "testapp", 0, 1, name="publishers", model_name="author" ) self.assertOperationAttributes( changes, "testapp", 0, 2, name="publishers", model_name="author" ) def test_many_to_many_changed_to_concrete_field(self): """ #23938 - Changing a ManyToManyField into a concrete field first removes the m2m field and then adds the concrete field. """ changes = self.get_changes( [self.author_with_m2m, self.publisher], [self.author_with_former_m2m] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["RemoveField", "DeleteModel", "AddField"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="publishers", model_name="author" ) self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertOperationAttributes( changes, "testapp", 0, 2, name="publishers", model_name="author" ) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, max_length=100) def test_non_circular_foreignkey_dependency_removal(self): """ If two models with a ForeignKey from one to the other are removed at the same time, the autodetector should remove them in the correct order. """ changes = self.get_changes( [self.author_with_publisher, self.publisher_with_author], [] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["RemoveField", "DeleteModel", "DeleteModel"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", model_name="publisher" ) self.assertOperationAttributes(changes, "testapp", 0, 1, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 2, name="Publisher") def test_alter_model_options(self): """Changing a model's options should make a change.""" changes = self.get_changes([self.author_empty], [self.author_with_options]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes( changes, "testapp", 0, 0, options={ "permissions": [("can_hire", "Can hire")], "verbose_name": "Authi", }, ) # Changing them back to empty should also make a change changes = self.get_changes([self.author_with_options], [self.author_empty]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", options={} ) def test_alter_model_options_proxy(self): """Changing a proxy model's options should also make a change.""" changes = self.get_changes( [self.author_proxy, self.author_empty], [self.author_proxy_options, self.author_empty], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="authorproxy", options={"verbose_name": "Super Author"}, ) def test_set_alter_order_with_respect_to(self): """Setting order_with_respect_to adds a field.""" changes = self.get_changes( [self.book, self.author_with_book], [self.book, self.author_with_book_order_wrt], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterOrderWithRespectTo"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", order_with_respect_to="book" ) def test_add_alter_order_with_respect_to(self): """ Setting order_with_respect_to when adding the FK too does things in the right order. """ changes = self.get_changes( [self.author_name], [self.book, self.author_with_book_order_wrt] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AddField", "AlterOrderWithRespectTo"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, model_name="author", name="book" ) self.assertOperationAttributes( changes, "testapp", 0, 1, name="author", order_with_respect_to="book" ) def test_remove_alter_order_with_respect_to(self): """ Removing order_with_respect_to when removing the FK too does things in the right order. """ changes = self.get_changes( [self.book, self.author_with_book_order_wrt], [self.author_name] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AlterOrderWithRespectTo", "RemoveField"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", order_with_respect_to=None ) self.assertOperationAttributes( changes, "testapp", 0, 1, model_name="author", name="book" ) def test_add_model_order_with_respect_to(self): """ Setting order_with_respect_to when adding the whole model does things in the right order. """ changes = self.get_changes([], [self.book, self.author_with_book_order_wrt]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="Author", options={"order_with_respect_to": "book"}, ) self.assertNotIn( "_order", [name for name, field in changes["testapp"][0].operations[0].fields], ) def test_add_model_order_with_respect_to_unique_together(self): changes = self.get_changes( [], [ self.book, ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={ "order_with_respect_to": "book", "unique_together": {("id", "_order")}, }, ), ], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="Author", options={ "order_with_respect_to": "book", "unique_together": {("id", "_order")}, }, ) def test_add_model_order_with_respect_to_index_constraint(self): tests = [ ( "AddIndex", { "indexes": [ models.Index(fields=["_order"], name="book_order_idx"), ] }, ), ( "AddConstraint", { "constraints": [ models.CheckConstraint( check=models.Q(_order__gt=1), name="book_order_gt_1", ), ] }, ), ] for operation, extra_option in tests: with self.subTest(operation=operation): after = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={ "order_with_respect_to": "book", **extra_option, }, ) changes = self.get_changes([], [self.book, after]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, [ "CreateModel", operation, ], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="Author", options={"order_with_respect_to": "book"}, ) def test_set_alter_order_with_respect_to_index_constraint_unique_together(self): tests = [ ( "AddIndex", { "indexes": [ models.Index(fields=["_order"], name="book_order_idx"), ] }, ), ( "AddConstraint", { "constraints": [ models.CheckConstraint( check=models.Q(_order__gt=1), name="book_order_gt_1", ), ] }, ), ("AlterUniqueTogether", {"unique_together": {("id", "_order")}}), ] for operation, extra_option in tests: with self.subTest(operation=operation): after = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={ "order_with_respect_to": "book", **extra_option, }, ) changes = self.get_changes( [self.book, self.author_with_book], [self.book, after], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, [ "AlterOrderWithRespectTo", operation, ], ) def test_alter_model_managers(self): """ Changing the model managers adds a new operation. """ changes = self.get_changes([self.other_pony], [self.other_pony_food]) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterModelManagers"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="pony") self.assertEqual( [name for name, mgr in changes["otherapp"][0].operations[0].managers], ["food_qs", "food_mgr", "food_mgr_kwargs"], ) self.assertEqual( changes["otherapp"][0].operations[0].managers[1][1].args, ("a", "b", 1, 2) ) self.assertEqual( changes["otherapp"][0].operations[0].managers[2][1].args, ("x", "y", 3, 4) ) def test_swappable_first_inheritance(self): """Swappable models get their CreateModel first.""" changes = self.get_changes([], [self.custom_user, self.aardvark]) # Right number/type of migrations? self.assertNumberMigrations(changes, "thirdapp", 1) self.assertOperationTypes( changes, "thirdapp", 0, ["CreateModel", "CreateModel"] ) self.assertOperationAttributes(changes, "thirdapp", 0, 0, name="CustomUser") self.assertOperationAttributes(changes, "thirdapp", 0, 1, name="Aardvark") def test_default_related_name_option(self): model_state = ModelState( "app", "model", [ ("id", models.AutoField(primary_key=True)), ], options={"default_related_name": "related_name"}, ) changes = self.get_changes([], [model_state]) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "app", 0, 0, name="model", options={"default_related_name": "related_name"}, ) altered_model_state = ModelState( "app", "Model", [ ("id", models.AutoField(primary_key=True)), ], ) changes = self.get_changes([model_state], [altered_model_state]) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, "app", 0, 0, name="model", options={}) @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") def test_swappable_first_setting(self): """Swappable models get their CreateModel first.""" with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes([], [self.custom_user_no_inherit, self.aardvark]) # Right number/type of migrations? self.assertNumberMigrations(changes, "thirdapp", 1) self.assertOperationTypes( changes, "thirdapp", 0, ["CreateModel", "CreateModel"] ) self.assertOperationAttributes(changes, "thirdapp", 0, 0, name="CustomUser") self.assertOperationAttributes(changes, "thirdapp", 0, 1, name="Aardvark") def test_bases_first(self): """Bases of other models come first.""" changes = self.get_changes( [], [self.aardvark_based_on_author, self.author_name] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Aardvark") def test_bases_first_mixed_case_app_label(self): app_label = "MiXedCaseApp" changes = self.get_changes( [], [ ModelState( app_label, "owner", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( app_label, "place", [ ("id", models.AutoField(primary_key=True)), ( "owner", models.ForeignKey("MiXedCaseApp.owner", models.CASCADE), ), ], ), ModelState(app_label, "restaurant", [], bases=("MiXedCaseApp.place",)), ], ) self.assertNumberMigrations(changes, app_label, 1) self.assertOperationTypes( changes, app_label, 0, [ "CreateModel", "CreateModel", "CreateModel", ], ) self.assertOperationAttributes(changes, app_label, 0, 0, name="owner") self.assertOperationAttributes(changes, app_label, 0, 1, name="place") self.assertOperationAttributes(changes, app_label, 0, 2, name="restaurant") def test_multiple_bases(self): """ Inheriting models doesn't move *_ptr fields into AddField operations. """ A = ModelState("app", "A", [("a_id", models.AutoField(primary_key=True))]) B = ModelState("app", "B", [("b_id", models.AutoField(primary_key=True))]) C = ModelState("app", "C", [], bases=("app.A", "app.B")) D = ModelState("app", "D", [], bases=("app.A", "app.B")) E = ModelState("app", "E", [], bases=("app.A", "app.B")) changes = self.get_changes([], [A, B, C, D, E]) # Right number/type of migrations? self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes( changes, "app", 0, ["CreateModel", "CreateModel", "CreateModel", "CreateModel", "CreateModel"], ) self.assertOperationAttributes(changes, "app", 0, 0, name="A") self.assertOperationAttributes(changes, "app", 0, 1, name="B") self.assertOperationAttributes(changes, "app", 0, 2, name="C") self.assertOperationAttributes(changes, "app", 0, 3, name="D") self.assertOperationAttributes(changes, "app", 0, 4, name="E") def test_proxy_bases_first(self): """Bases of proxies come first.""" changes = self.get_changes( [], [self.author_empty, self.author_proxy, self.author_proxy_proxy] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["CreateModel", "CreateModel", "CreateModel"] ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="AuthorProxy") self.assertOperationAttributes( changes, "testapp", 0, 2, name="AAuthorProxyProxy" ) def test_pk_fk_included(self): """ A relation used as the primary key is kept as part of CreateModel. """ changes = self.get_changes([], [self.aardvark_pk_fk_author, self.author_name]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Aardvark") def test_first_dependency(self): """ A dependency to an app with no migrations uses __first__. """ # Load graph loader = MigrationLoader(connection) before = self.make_project_state([]) after = self.make_project_state([self.book_migrations_fk]) after.real_apps = {"migrations"} autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes(graph=loader.graph) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Book") self.assertMigrationDependencies( changes, "otherapp", 0, [("migrations", "__first__")] ) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_last_dependency(self): """ A dependency to an app with existing migrations uses the last migration of that app. """ # Load graph loader = MigrationLoader(connection) before = self.make_project_state([]) after = self.make_project_state([self.book_migrations_fk]) after.real_apps = {"migrations"} autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes(graph=loader.graph) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Book") self.assertMigrationDependencies( changes, "otherapp", 0, [("migrations", "0002_second")] ) def test_alter_fk_before_model_deletion(self): """ ForeignKeys are altered _before_ the model they used to refer to are deleted. """ changes = self.get_changes( [self.author_name, self.publisher_with_author], [self.aardvark_testapp, self.publisher_with_aardvark_author], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["CreateModel", "AlterField", "DeleteModel"] ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Aardvark") self.assertOperationAttributes(changes, "testapp", 0, 1, name="author") self.assertOperationAttributes(changes, "testapp", 0, 2, name="Author") def test_fk_dependency_other_app(self): """ #23100 - ForeignKeys correctly depend on other apps' models. """ changes = self.get_changes( [self.author_name, self.book], [self.author_with_book, self.book] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="book") self.assertMigrationDependencies( changes, "testapp", 0, [("otherapp", "__first__")] ) def test_alter_unique_together_fk_to_m2m(self): changes = self.get_changes( [self.author_name, self.book_unique_together], [ self.author_name, ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ManyToManyField("testapp.Author")), ("title", models.CharField(max_length=200)), ], ), ], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterUniqueTogether", "RemoveField", "AddField"] ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together=set() ) self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="book", name="author" ) self.assertOperationAttributes( changes, "otherapp", 0, 2, model_name="book", name="author" ) def test_alter_field_to_fk_dependency_other_app(self): changes = self.get_changes( [self.author_empty, self.book_with_no_author_fk], [self.author_empty, self.book], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterField"]) self.assertMigrationDependencies( changes, "otherapp", 0, [("testapp", "__first__")] ) def test_circular_dependency_mixed_addcreate(self): """ #23315 - The dependency resolver knows to put all CreateModel before AddField and not become unsolvable. """ address = ModelState( "a", "Address", [ ("id", models.AutoField(primary_key=True)), ("country", models.ForeignKey("b.DeliveryCountry", models.CASCADE)), ], ) person = ModelState( "a", "Person", [ ("id", models.AutoField(primary_key=True)), ], ) apackage = ModelState( "b", "APackage", [ ("id", models.AutoField(primary_key=True)), ("person", models.ForeignKey("a.Person", models.CASCADE)), ], ) country = ModelState( "b", "DeliveryCountry", [ ("id", models.AutoField(primary_key=True)), ], ) changes = self.get_changes([], [address, person, apackage, country]) # Right number/type of migrations? self.assertNumberMigrations(changes, "a", 2) self.assertNumberMigrations(changes, "b", 1) self.assertOperationTypes(changes, "a", 0, ["CreateModel", "CreateModel"]) self.assertOperationTypes(changes, "a", 1, ["AddField"]) self.assertOperationTypes(changes, "b", 0, ["CreateModel", "CreateModel"]) @override_settings(AUTH_USER_MODEL="a.Tenant") def test_circular_dependency_swappable(self): """ #23322 - The dependency resolver knows to explicitly resolve swappable models. """ with isolate_lru_cache(apps.get_swappable_settings_name): tenant = ModelState( "a", "Tenant", [ ("id", models.AutoField(primary_key=True)), ("primary_address", models.ForeignKey("b.Address", models.CASCADE)), ], bases=(AbstractBaseUser,), ) address = ModelState( "b", "Address", [ ("id", models.AutoField(primary_key=True)), ( "tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE), ), ], ) changes = self.get_changes([], [address, tenant]) # Right number/type of migrations? self.assertNumberMigrations(changes, "a", 2) self.assertOperationTypes(changes, "a", 0, ["CreateModel"]) self.assertOperationTypes(changes, "a", 1, ["AddField"]) self.assertMigrationDependencies(changes, "a", 0, []) self.assertMigrationDependencies( changes, "a", 1, [("a", "auto_1"), ("b", "auto_1")] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "b", 1) self.assertOperationTypes(changes, "b", 0, ["CreateModel"]) self.assertMigrationDependencies( changes, "b", 0, [("__setting__", "AUTH_USER_MODEL")] ) @override_settings(AUTH_USER_MODEL="b.Tenant") def test_circular_dependency_swappable2(self): """ #23322 - The dependency resolver knows to explicitly resolve swappable models but with the swappable not being the first migrated model. """ with isolate_lru_cache(apps.get_swappable_settings_name): address = ModelState( "a", "Address", [ ("id", models.AutoField(primary_key=True)), ( "tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE), ), ], ) tenant = ModelState( "b", "Tenant", [ ("id", models.AutoField(primary_key=True)), ("primary_address", models.ForeignKey("a.Address", models.CASCADE)), ], bases=(AbstractBaseUser,), ) changes = self.get_changes([], [address, tenant]) # Right number/type of migrations? self.assertNumberMigrations(changes, "a", 2) self.assertOperationTypes(changes, "a", 0, ["CreateModel"]) self.assertOperationTypes(changes, "a", 1, ["AddField"]) self.assertMigrationDependencies(changes, "a", 0, []) self.assertMigrationDependencies( changes, "a", 1, [("__setting__", "AUTH_USER_MODEL"), ("a", "auto_1")] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "b", 1) self.assertOperationTypes(changes, "b", 0, ["CreateModel"]) self.assertMigrationDependencies(changes, "b", 0, [("a", "auto_1")]) @override_settings(AUTH_USER_MODEL="a.Person") def test_circular_dependency_swappable_self(self): """ #23322 - The dependency resolver knows to explicitly resolve swappable models. """ with isolate_lru_cache(apps.get_swappable_settings_name): person = ModelState( "a", "Person", [ ("id", models.AutoField(primary_key=True)), ( "parent1", models.ForeignKey( settings.AUTH_USER_MODEL, models.CASCADE, related_name="children", ), ), ], ) changes = self.get_changes([], [person]) # Right number/type of migrations? self.assertNumberMigrations(changes, "a", 1) self.assertOperationTypes(changes, "a", 0, ["CreateModel"]) self.assertMigrationDependencies(changes, "a", 0, []) @override_settings(AUTH_USER_MODEL="a.User") def test_swappable_circular_multi_mti(self): with isolate_lru_cache(apps.get_swappable_settings_name): parent = ModelState( "a", "Parent", [("user", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE))], ) child = ModelState("a", "Child", [], bases=("a.Parent",)) user = ModelState("a", "User", [], bases=(AbstractBaseUser, "a.Child")) changes = self.get_changes([], [parent, child, user]) self.assertNumberMigrations(changes, "a", 1) self.assertOperationTypes( changes, "a", 0, ["CreateModel", "CreateModel", "CreateModel", "AddField"] ) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition", side_effect=AssertionError("Should not have prompted for not null addition"), ) def test_add_blank_textfield_and_charfield(self, mocked_ask_method): """ #23405 - Adding a NOT NULL and blank `CharField` or `TextField` without default should not prompt for a default. """ changes = self.get_changes( [self.author_empty], [self.author_with_biography_blank] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField", "AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition" ) def test_add_non_blank_textfield_and_charfield(self, mocked_ask_method): """ #23405 - Adding a NOT NULL and non-blank `CharField` or `TextField` without default should prompt for a default. """ changes = self.get_changes( [self.author_empty], [self.author_with_biography_non_blank] ) self.assertEqual(mocked_ask_method.call_count, 2) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField", "AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0) def test_mti_inheritance_model_removal(self): Animal = ModelState( "app", "Animal", [ ("id", models.AutoField(primary_key=True)), ], ) Dog = ModelState("app", "Dog", [], bases=("app.Animal",)) changes = self.get_changes([Animal, Dog], [Animal]) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["DeleteModel"]) self.assertOperationAttributes(changes, "app", 0, 0, name="Dog") def test_add_model_with_field_removed_from_base_model(self): """ Removing a base field takes place before adding a new inherited model that has a field with the same name. """ before = [ ModelState( "app", "readable", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=200)), ], ), ] after = [ ModelState( "app", "readable", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "app", "book", [ ("title", models.CharField(max_length=200)), ], bases=("app.readable",), ), ] changes = self.get_changes(before, after) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["RemoveField", "CreateModel"]) self.assertOperationAttributes( changes, "app", 0, 0, name="title", model_name="readable" ) self.assertOperationAttributes(changes, "app", 0, 1, name="book") def test_parse_number(self): tests = [ ("no_number", None), ("0001_initial", 1), ("0002_model3", 2), ("0002_auto_20380101_1112", 2), ("0002_squashed_0003", 3), ("0002_model2_squashed_0003_other4", 3), ("0002_squashed_0003_squashed_0004", 4), ("0002_model2_squashed_0003_other4_squashed_0005_other6", 5), ("0002_custom_name_20380101_1112_squashed_0003_model", 3), ("2_squashed_4", 4), ] for migration_name, expected_number in tests: with self.subTest(migration_name=migration_name): self.assertEqual( MigrationAutodetector.parse_number(migration_name), expected_number, ) def test_add_custom_fk_with_hardcoded_to(self): class HardcodedForeignKey(models.ForeignKey): def __init__(self, *args, **kwargs): kwargs["to"] = "testapp.Author" super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["to"] return name, path, args, kwargs book_hardcoded_fk_to = ModelState( "testapp", "Book", [ ("author", HardcodedForeignKey(on_delete=models.CASCADE)), ], ) changes = self.get_changes( [self.author_empty], [self.author_empty, book_hardcoded_fk_to], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Book") @ignore_warnings(category=RemovedInDjango51Warning) class AutodetectorIndexTogetherTests(BaseAutodetectorTests): book_index_together = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("author", "title")}, }, ) book_index_together_2 = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "author")}, }, ) book_index_together_3 = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "newfield")}, }, ) book_index_together_4 = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield2", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "newfield2")}, }, ) def test_empty_index_together(self): """Empty index_together shouldn't generate a migration.""" # Explicitly testing for not specified, since this is the case after # a CreateModel operation w/o any definition on the original model model_state_not_specified = ModelState( "a", "model", [("id", models.AutoField(primary_key=True))] ) # Explicitly testing for None, since this was the issue in #23452 after # an AlterIndexTogether operation with e.g. () as value model_state_none = ModelState( "a", "model", [("id", models.AutoField(primary_key=True))], { "index_together": None, }, ) # Explicitly testing for the empty set, since we now always have sets. # During removal (('col1', 'col2'),) --> () this becomes set([]) model_state_empty = ModelState( "a", "model", [("id", models.AutoField(primary_key=True))], { "index_together": set(), }, ) def test(from_state, to_state, msg): changes = self.get_changes([from_state], [to_state]) if changes: ops = ", ".join( o.__class__.__name__ for o in changes["a"][0].operations ) self.fail("Created operation(s) %s from %s" % (ops, msg)) tests = ( ( model_state_not_specified, model_state_not_specified, '"not specified" to "not specified"', ), (model_state_not_specified, model_state_none, '"not specified" to "None"'), ( model_state_not_specified, model_state_empty, '"not specified" to "empty"', ), (model_state_none, model_state_not_specified, '"None" to "not specified"'), (model_state_none, model_state_none, '"None" to "None"'), (model_state_none, model_state_empty, '"None" to "empty"'), ( model_state_empty, model_state_not_specified, '"empty" to "not specified"', ), (model_state_empty, model_state_none, '"empty" to "None"'), (model_state_empty, model_state_empty, '"empty" to "empty"'), ) for t in tests: test(*t) def test_rename_index_together_to_index(self): changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together], [AutodetectorTests.author_empty, AutodetectorTests.book_indexes], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RenameIndex"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, model_name="book", new_name="book_title_author_idx", old_fields=("author", "title"), ) def test_rename_index_together_to_index_extra_options(self): # Indexes with extra options don't match indexes in index_together. book_partial_index = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [ models.Index( fields=["author", "title"], condition=models.Q(title__startswith="The"), name="book_title_author_idx", ) ], }, ) changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together], [AutodetectorTests.author_empty, book_partial_index], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterIndexTogether", "AddIndex"], ) def test_rename_index_together_to_index_order_fields(self): # Indexes with reordered fields don't match indexes in index_together. changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together], [AutodetectorTests.author_empty, AutodetectorTests.book_unordered_indexes], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterIndexTogether", "AddIndex"], ) def test_add_index_together(self): changes = self.get_changes( [AutodetectorTests.author_empty, AutodetectorTests.book], [AutodetectorTests.author_empty, self.book_index_together], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterIndexTogether"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", index_together={("author", "title")} ) def test_remove_index_together(self): changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together], [AutodetectorTests.author_empty, AutodetectorTests.book], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterIndexTogether"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", index_together=set() ) def test_index_together_remove_fk(self): changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together], [AutodetectorTests.author_empty, AutodetectorTests.book_with_no_author], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterIndexTogether", "RemoveField"], ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", index_together=set() ) self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="book", name="author" ) def test_index_together_no_changes(self): """ index_together doesn't generate a migration if no changes have been made. """ changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together], [AutodetectorTests.author_empty, self.book_index_together], ) self.assertEqual(len(changes), 0) def test_index_together_ordering(self): """index_together triggers on ordering changes.""" changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together], [AutodetectorTests.author_empty, self.book_index_together_2], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterIndexTogether"], ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", index_together={("title", "author")}, ) def test_add_field_and_index_together(self): """ Added fields will be created before using them in index_together. """ changes = self.get_changes( [AutodetectorTests.author_empty, AutodetectorTests.book], [AutodetectorTests.author_empty, self.book_index_together_3], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AddField", "AlterIndexTogether"], ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", index_together={("title", "newfield")}, ) def test_create_model_and_index_together(self): author = ModelState( "otherapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], ) book_with_author = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("otherapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "author")}, }, ) changes = self.get_changes( [AutodetectorTests.book_with_no_author], [author, book_with_author] ) self.assertEqual(len(changes["otherapp"]), 1) migration = changes["otherapp"][0] self.assertEqual(len(migration.operations), 3) self.assertOperationTypes( changes, "otherapp", 0, ["CreateModel", "AddField", "AlterIndexTogether"], ) def test_remove_field_and_index_together(self): """ Removed fields will be removed after updating index_together. """ changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together_3], [AutodetectorTests.author_empty, self.book_index_together], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterIndexTogether", "RemoveField"], ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", index_together={("author", "title")}, ) self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="book", name="newfield", ) def test_alter_field_and_index_together(self): """Fields are altered after deleting some index_together.""" initial_author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField(db_index=True)), ], { "index_together": {("name",)}, }, ) author_reversed_constraints = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, unique=True)), ("age", models.IntegerField()), ], { "index_together": {("age",)}, }, ) changes = self.get_changes([initial_author], [author_reversed_constraints]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, [ "AlterIndexTogether", "AlterField", "AlterField", "AlterIndexTogether", ], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", index_together=set(), ) self.assertOperationAttributes( changes, "testapp", 0, 1, model_name="author", name="age", ) self.assertOperationAttributes( changes, "testapp", 0, 2, model_name="author", name="name", ) self.assertOperationAttributes( changes, "testapp", 0, 3, name="author", index_together={("age",)}, ) def test_partly_alter_index_together_increase(self): initial_author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "index_together": {("name",)}, }, ) author_new_constraints = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "index_together": {("name",), ("age",)}, }, ) changes = self.get_changes([initial_author], [author_new_constraints]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AlterIndexTogether"], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", index_together={("name",), ("age",)}, ) def test_partly_alter_index_together_decrease(self): initial_author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "index_together": {("name",), ("age",)}, }, ) author_new_constraints = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "index_together": {("age",)}, }, ) changes = self.get_changes([initial_author], [author_new_constraints]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AlterIndexTogether"], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", index_together={("age",)}, ) def test_rename_field_and_index_together(self): """Fields are renamed before updating index_together.""" changes = self.get_changes( [AutodetectorTests.author_empty, self.book_index_together_3], [AutodetectorTests.author_empty, self.book_index_together_4], MigrationQuestioner({"ask_rename": True}), ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["RenameField", "AlterIndexTogether"], ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", index_together={("title", "newfield2")}, ) def test_add_model_order_with_respect_to_index_together(self): changes = self.get_changes( [], [ AutodetectorTests.book, ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={ "order_with_respect_to": "book", "index_together": {("name", "_order")}, }, ), ], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="Author", options={ "order_with_respect_to": "book", "index_together": {("name", "_order")}, }, ) def test_set_alter_order_with_respect_to_index_together(self): after = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={ "order_with_respect_to": "book", "index_together": {("name", "_order")}, }, ) changes = self.get_changes( [AutodetectorTests.book, AutodetectorTests.author_with_book], [AutodetectorTests.book, after], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AlterOrderWithRespectTo", "AlterIndexTogether"], ) class MigrationSuggestNameTests(SimpleTestCase): def test_no_operations(self): class Migration(migrations.Migration): operations = [] migration = Migration("some_migration", "test_app") self.assertIs(migration.suggest_name().startswith("auto_"), True) def test_no_operations_initial(self): class Migration(migrations.Migration): initial = True operations = [] migration = Migration("some_migration", "test_app") self.assertEqual(migration.suggest_name(), "initial") def test_single_operation(self): class Migration(migrations.Migration): operations = [migrations.CreateModel("Person", fields=[])] migration = Migration("0001_initial", "test_app") self.assertEqual(migration.suggest_name(), "person") class Migration(migrations.Migration): operations = [migrations.DeleteModel("Person")] migration = Migration("0002_initial", "test_app") self.assertEqual(migration.suggest_name(), "delete_person") def test_single_operation_long_name(self): class Migration(migrations.Migration): operations = [migrations.CreateModel("A" * 53, fields=[])] migration = Migration("some_migration", "test_app") self.assertEqual(migration.suggest_name(), "a" * 53) def test_two_operations(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel("Person", fields=[]), migrations.DeleteModel("Animal"), ] migration = Migration("some_migration", "test_app") self.assertEqual(migration.suggest_name(), "person_delete_animal") def test_two_create_models(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel("Person", fields=[]), migrations.CreateModel("Animal", fields=[]), ] migration = Migration("0001_initial", "test_app") self.assertEqual(migration.suggest_name(), "person_animal") def test_two_create_models_with_initial_true(self): class Migration(migrations.Migration): initial = True operations = [ migrations.CreateModel("Person", fields=[]), migrations.CreateModel("Animal", fields=[]), ] migration = Migration("0001_initial", "test_app") self.assertEqual(migration.suggest_name(), "initial") def test_many_operations_suffix(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel("Person1", fields=[]), migrations.CreateModel("Person2", fields=[]), migrations.CreateModel("Person3", fields=[]), migrations.DeleteModel("Person4"), migrations.DeleteModel("Person5"), ] migration = Migration("some_migration", "test_app") self.assertEqual( migration.suggest_name(), "person1_person2_person3_delete_person4_and_more", ) def test_operation_with_no_suggested_name(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel("Person", fields=[]), migrations.RunSQL("SELECT 1 FROM person;"), ] migration = Migration("some_migration", "test_app") self.assertIs(migration.suggest_name().startswith("auto_"), True) def test_operation_with_invalid_chars_in_suggested_name(self): class Migration(migrations.Migration): operations = [ migrations.AddConstraint( "Person", models.UniqueConstraint( fields=["name"], name="person.name-*~unique!" ), ), ] migration = Migration("some_migration", "test_app") self.assertEqual(migration.suggest_name(), "person_person_name_unique_") def test_none_name(self): class Migration(migrations.Migration): operations = [migrations.RunSQL("SELECT 1 FROM person;")] migration = Migration("0001_initial", "test_app") suggest_name = migration.suggest_name() self.assertIs(suggest_name.startswith("auto_"), True) def test_none_name_with_initial_true(self): class Migration(migrations.Migration): initial = True operations = [migrations.RunSQL("SELECT 1 FROM person;")] migration = Migration("0001_initial", "test_app") self.assertEqual(migration.suggest_name(), "initial") def test_auto(self): migration = migrations.Migration("0001_initial", "test_app") suggest_name = migration.suggest_name() self.assertIs(suggest_name.startswith("auto_"), True)
aaf30385525d968a840f077bd34e6d2bca13e046f4a73b6a02af2b11db15dab1
from unittest import mock from django.conf.global_settings import PASSWORD_HASHERS from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.hashers import get_hasher from django.contrib.auth.models import ( AnonymousUser, Group, Permission, User, UserManager, ) from django.contrib.contenttypes.models import ContentType from django.core import mail from django.db import connection, migrations from django.db.migrations.state import ModelState, ProjectState from django.db.models.signals import post_save from django.test import SimpleTestCase, TestCase, TransactionTestCase, override_settings from django.test.utils import ignore_warnings from django.utils.deprecation import RemovedInDjango51Warning from .models import CustomEmailField, IntegerUsernameUser class NaturalKeysTestCase(TestCase): def test_user_natural_key(self): staff_user = User.objects.create_user(username="staff") self.assertEqual(User.objects.get_by_natural_key("staff"), staff_user) self.assertEqual(staff_user.natural_key(), ("staff",)) def test_group_natural_key(self): users_group = Group.objects.create(name="users") self.assertEqual(Group.objects.get_by_natural_key("users"), users_group) class LoadDataWithoutNaturalKeysTestCase(TestCase): fixtures = ["regular.json"] def test_user_is_created_and_added_to_group(self): user = User.objects.get(username="my_username") group = Group.objects.get(name="my_group") self.assertEqual(group, user.groups.get()) class LoadDataWithNaturalKeysTestCase(TestCase): fixtures = ["natural.json"] def test_user_is_created_and_added_to_group(self): user = User.objects.get(username="my_username") group = Group.objects.get(name="my_group") self.assertEqual(group, user.groups.get()) class LoadDataWithNaturalKeysAndMultipleDatabasesTestCase(TestCase): databases = {"default", "other"} def test_load_data_with_user_permissions(self): # Create test contenttypes for both databases default_objects = [ ContentType.objects.db_manager("default").create( model="examplemodela", app_label="app_a", ), ContentType.objects.db_manager("default").create( model="examplemodelb", app_label="app_b", ), ] other_objects = [ ContentType.objects.db_manager("other").create( model="examplemodelb", app_label="app_b", ), ContentType.objects.db_manager("other").create( model="examplemodela", app_label="app_a", ), ] # Now we create the test UserPermission Permission.objects.db_manager("default").create( name="Can delete example model b", codename="delete_examplemodelb", content_type=default_objects[1], ) Permission.objects.db_manager("other").create( name="Can delete example model b", codename="delete_examplemodelb", content_type=other_objects[0], ) perm_default = Permission.objects.get_by_natural_key( "delete_examplemodelb", "app_b", "examplemodelb", ) perm_other = Permission.objects.db_manager("other").get_by_natural_key( "delete_examplemodelb", "app_b", "examplemodelb", ) self.assertEqual(perm_default.content_type_id, default_objects[1].id) self.assertEqual(perm_other.content_type_id, other_objects[0].id) class UserManagerTestCase(TransactionTestCase): available_apps = [ "auth_tests", "django.contrib.auth", "django.contrib.contenttypes", ] def test_create_user(self): email_lowercase = "[email protected]" user = User.objects.create_user("user", email_lowercase) self.assertEqual(user.email, email_lowercase) self.assertEqual(user.username, "user") self.assertFalse(user.has_usable_password()) def test_create_user_email_domain_normalize_rfc3696(self): # According to RFC 3696 Section 3 the "@" symbol can be part of the # local part of an email address. returned = UserManager.normalize_email(r"Abc\@[email protected]") self.assertEqual(returned, r"Abc\@[email protected]") def test_create_user_email_domain_normalize(self): returned = UserManager.normalize_email("[email protected]") self.assertEqual(returned, "[email protected]") def test_create_user_email_domain_normalize_with_whitespace(self): returned = UserManager.normalize_email(r"email\ [email protected]") self.assertEqual(returned, r"email\ [email protected]") def test_empty_username(self): with self.assertRaisesMessage(ValueError, "The given username must be set"): User.objects.create_user(username="") def test_create_user_is_staff(self): email = "[email protected]" user = User.objects.create_user("user", email, is_staff=True) self.assertEqual(user.email, email) self.assertEqual(user.username, "user") self.assertTrue(user.is_staff) def test_create_super_user_raises_error_on_false_is_superuser(self): with self.assertRaisesMessage( ValueError, "Superuser must have is_superuser=True." ): User.objects.create_superuser( username="test", email="[email protected]", password="test", is_superuser=False, ) def test_create_superuser_raises_error_on_false_is_staff(self): with self.assertRaisesMessage(ValueError, "Superuser must have is_staff=True."): User.objects.create_superuser( username="test", email="[email protected]", password="test", is_staff=False, ) @ignore_warnings(category=RemovedInDjango51Warning) def test_make_random_password(self): allowed_chars = "abcdefg" password = UserManager().make_random_password(5, allowed_chars) self.assertEqual(len(password), 5) for char in password: self.assertIn(char, allowed_chars) def test_make_random_password_warning(self): msg = "BaseUserManager.make_random_password() is deprecated." with self.assertWarnsMessage(RemovedInDjango51Warning, msg): UserManager().make_random_password() def test_runpython_manager_methods(self): def forwards(apps, schema_editor): UserModel = apps.get_model("auth", "User") user = UserModel.objects.create_user("user1", password="secure") self.assertIsInstance(user, UserModel) operation = migrations.RunPython(forwards, migrations.RunPython.noop) project_state = ProjectState() project_state.add_model(ModelState.from_model(User)) project_state.add_model(ModelState.from_model(Group)) project_state.add_model(ModelState.from_model(Permission)) project_state.add_model(ModelState.from_model(ContentType)) new_state = project_state.clone() with connection.schema_editor() as editor: operation.state_forwards("test_manager_methods", new_state) operation.database_forwards( "test_manager_methods", editor, project_state, new_state, ) user = User.objects.get(username="user1") self.assertTrue(user.check_password("secure")) class AbstractBaseUserTests(SimpleTestCase): def test_has_usable_password(self): """ Passwords are usable even if they don't correspond to a hasher in settings.PASSWORD_HASHERS. """ self.assertIs(User(password="some-gibbberish").has_usable_password(), True) def test_normalize_username(self): self.assertEqual(IntegerUsernameUser().normalize_username(123), 123) def test_clean_normalize_username(self): # The normalization happens in AbstractBaseUser.clean() ohm_username = "iamtheΩ" # U+2126 OHM SIGN for model in ("auth.User", "auth_tests.CustomUser"): with self.subTest(model=model), self.settings(AUTH_USER_MODEL=model): User = get_user_model() user = User(**{User.USERNAME_FIELD: ohm_username, "password": "foo"}) user.clean() username = user.get_username() self.assertNotEqual(username, ohm_username) self.assertEqual( username, "iamtheΩ" ) # U+03A9 GREEK CAPITAL LETTER OMEGA def test_default_email(self): self.assertEqual(AbstractBaseUser.get_email_field_name(), "email") def test_custom_email(self): user = CustomEmailField() self.assertEqual(user.get_email_field_name(), "email_address") class AbstractUserTestCase(TestCase): def test_email_user(self): # valid send_mail parameters kwargs = { "fail_silently": False, "auth_user": None, "auth_password": None, "connection": None, "html_message": None, } user = User(email="[email protected]") user.email_user( subject="Subject here", message="This is a message", from_email="[email protected]", **kwargs, ) self.assertEqual(len(mail.outbox), 1) message = mail.outbox[0] self.assertEqual(message.subject, "Subject here") self.assertEqual(message.body, "This is a message") self.assertEqual(message.from_email, "[email protected]") self.assertEqual(message.to, [user.email]) def test_last_login_default(self): user1 = User.objects.create(username="user1") self.assertIsNone(user1.last_login) user2 = User.objects.create_user(username="user2") self.assertIsNone(user2.last_login) def test_user_clean_normalize_email(self): user = User(username="user", password="foo", email="[email protected]") user.clean() self.assertEqual(user.email, "[email protected]") def test_user_double_save(self): """ Calling user.save() twice should trigger password_changed() once. """ user = User.objects.create_user(username="user", password="foo") user.set_password("bar") with mock.patch( "django.contrib.auth.password_validation.password_changed" ) as pw_changed: user.save() self.assertEqual(pw_changed.call_count, 1) user.save() self.assertEqual(pw_changed.call_count, 1) @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) def test_check_password_upgrade(self): """ password_changed() shouldn't be called if User.check_password() triggers a hash iteration upgrade. """ user = User.objects.create_user(username="user", password="foo") initial_password = user.password self.assertTrue(user.check_password("foo")) hasher = get_hasher("default") self.assertEqual("pbkdf2_sha256", hasher.algorithm) old_iterations = hasher.iterations try: # Upgrade the password iterations hasher.iterations = old_iterations + 1 with mock.patch( "django.contrib.auth.password_validation.password_changed" ) as pw_changed: user.check_password("foo") self.assertEqual(pw_changed.call_count, 0) self.assertNotEqual(initial_password, user.password) finally: hasher.iterations = old_iterations class CustomModelBackend(ModelBackend): def with_perm( self, perm, is_active=True, include_superusers=True, backend=None, obj=None ): if obj is not None and obj.username == "charliebrown": return User.objects.filter(pk=obj.pk) return User.objects.filter(username__startswith="charlie") class UserWithPermTestCase(TestCase): @classmethod def setUpTestData(cls): content_type = ContentType.objects.get_for_model(Group) cls.permission = Permission.objects.create( name="test", content_type=content_type, codename="test", ) # User with permission. cls.user1 = User.objects.create_user("user 1", "[email protected]") cls.user1.user_permissions.add(cls.permission) # User with group permission. group1 = Group.objects.create(name="group 1") group1.permissions.add(cls.permission) group2 = Group.objects.create(name="group 2") group2.permissions.add(cls.permission) cls.user2 = User.objects.create_user("user 2", "[email protected]") cls.user2.groups.add(group1, group2) # Users without permissions. cls.user_charlie = User.objects.create_user("charlie", "[email protected]") cls.user_charlie_b = User.objects.create_user( "charliebrown", "[email protected]" ) # Superuser. cls.superuser = User.objects.create_superuser( "superuser", "[email protected]", "superpassword", ) # Inactive user with permission. cls.inactive_user = User.objects.create_user( "inactive_user", "[email protected]", is_active=False, ) cls.inactive_user.user_permissions.add(cls.permission) def test_invalid_permission_name(self): msg = "Permission name should be in the form app_label.permission_codename." for perm in ("nodots", "too.many.dots", "...", ""): with self.subTest(perm), self.assertRaisesMessage(ValueError, msg): User.objects.with_perm(perm) def test_invalid_permission_type(self): msg = "The `perm` argument must be a string or a permission instance." for perm in (b"auth.test", object(), None): with self.subTest(perm), self.assertRaisesMessage(TypeError, msg): User.objects.with_perm(perm) def test_invalid_backend_type(self): msg = "backend must be a dotted import path string (got %r)." for backend in (b"auth_tests.CustomModelBackend", object()): with self.subTest(backend): with self.assertRaisesMessage(TypeError, msg % backend): User.objects.with_perm("auth.test", backend=backend) def test_basic(self): active_users = [self.user1, self.user2] tests = [ ({}, [*active_users, self.superuser]), ({"obj": self.user1}, []), # Only inactive users. ({"is_active": False}, [self.inactive_user]), # All users. ({"is_active": None}, [*active_users, self.superuser, self.inactive_user]), # Exclude superusers. ({"include_superusers": False}, active_users), ( {"include_superusers": False, "is_active": False}, [self.inactive_user], ), ( {"include_superusers": False, "is_active": None}, [*active_users, self.inactive_user], ), ] for kwargs, expected_users in tests: for perm in ("auth.test", self.permission): with self.subTest(perm=perm, **kwargs): self.assertCountEqual( User.objects.with_perm(perm, **kwargs), expected_users, ) @override_settings( AUTHENTICATION_BACKENDS=["django.contrib.auth.backends.BaseBackend"] ) def test_backend_without_with_perm(self): self.assertSequenceEqual(User.objects.with_perm("auth.test"), []) def test_nonexistent_permission(self): self.assertSequenceEqual(User.objects.with_perm("auth.perm"), [self.superuser]) def test_nonexistent_backend(self): with self.assertRaises(ImportError): User.objects.with_perm( "auth.test", backend="invalid.backend.CustomModelBackend", ) @override_settings( AUTHENTICATION_BACKENDS=["auth_tests.test_models.CustomModelBackend"] ) def test_custom_backend(self): for perm in ("auth.test", self.permission): with self.subTest(perm): self.assertCountEqual( User.objects.with_perm(perm), [self.user_charlie, self.user_charlie_b], ) @override_settings( AUTHENTICATION_BACKENDS=["auth_tests.test_models.CustomModelBackend"] ) def test_custom_backend_pass_obj(self): for perm in ("auth.test", self.permission): with self.subTest(perm): self.assertSequenceEqual( User.objects.with_perm(perm, obj=self.user_charlie_b), [self.user_charlie_b], ) @override_settings( AUTHENTICATION_BACKENDS=[ "auth_tests.test_models.CustomModelBackend", "django.contrib.auth.backends.ModelBackend", ] ) def test_multiple_backends(self): msg = ( "You have multiple authentication backends configured and " "therefore must provide the `backend` argument." ) with self.assertRaisesMessage(ValueError, msg): User.objects.with_perm("auth.test") backend = "auth_tests.test_models.CustomModelBackend" self.assertCountEqual( User.objects.with_perm("auth.test", backend=backend), [self.user_charlie, self.user_charlie_b], ) class IsActiveTestCase(TestCase): """ Tests the behavior of the guaranteed is_active attribute """ def test_builtin_user_isactive(self): user = User.objects.create(username="foo", email="[email protected]") # is_active is true by default self.assertIs(user.is_active, True) user.is_active = False user.save() user_fetched = User.objects.get(pk=user.pk) # the is_active flag is saved self.assertFalse(user_fetched.is_active) @override_settings(AUTH_USER_MODEL="auth_tests.IsActiveTestUser1") def test_is_active_field_default(self): """ tests that the default value for is_active is provided """ UserModel = get_user_model() user = UserModel(username="foo") self.assertIs(user.is_active, True) # you can set the attribute - but it will not save user.is_active = False # there should be no problem saving - but the attribute is not saved user.save() user_fetched = UserModel._default_manager.get(pk=user.pk) # the attribute is always true for newly retrieved instance self.assertIs(user_fetched.is_active, True) class TestCreateSuperUserSignals(TestCase): """ Simple test case for ticket #20541 """ def post_save_listener(self, *args, **kwargs): self.signals_count += 1 def setUp(self): self.signals_count = 0 post_save.connect(self.post_save_listener, sender=User) def tearDown(self): post_save.disconnect(self.post_save_listener, sender=User) def test_create_user(self): User.objects.create_user("JohnDoe") self.assertEqual(self.signals_count, 1) def test_create_superuser(self): User.objects.create_superuser("JohnDoe", "[email protected]", "1") self.assertEqual(self.signals_count, 1) class AnonymousUserTests(SimpleTestCase): no_repr_msg = "Django doesn't provide a DB representation for AnonymousUser." def setUp(self): self.user = AnonymousUser() def test_properties(self): self.assertIsNone(self.user.pk) self.assertEqual(self.user.username, "") self.assertEqual(self.user.get_username(), "") self.assertIs(self.user.is_anonymous, True) self.assertIs(self.user.is_authenticated, False) self.assertIs(self.user.is_staff, False) self.assertIs(self.user.is_active, False) self.assertIs(self.user.is_superuser, False) self.assertEqual(self.user.groups.count(), 0) self.assertEqual(self.user.user_permissions.count(), 0) self.assertEqual(self.user.get_user_permissions(), set()) self.assertEqual(self.user.get_group_permissions(), set()) def test_str(self): self.assertEqual(str(self.user), "AnonymousUser") def test_eq(self): self.assertEqual(self.user, AnonymousUser()) self.assertNotEqual(self.user, User("super", "[email protected]", "super")) def test_hash(self): self.assertEqual(hash(self.user), 1) def test_int(self): msg = ( "Cannot cast AnonymousUser to int. Are you trying to use it in " "place of User?" ) with self.assertRaisesMessage(TypeError, msg): int(self.user) def test_delete(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.delete() def test_save(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.save() def test_set_password(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.set_password("password") def test_check_password(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.check_password("password") class GroupTests(SimpleTestCase): def test_str(self): g = Group(name="Users") self.assertEqual(str(g), "Users") class PermissionTests(TestCase): def test_str(self): p = Permission.objects.get(codename="view_customemailfield") self.assertEqual( str(p), "Auth_Tests | custom email field | Can view custom email field" )
6b1fcfa703a96e1d1a5ffbff451730ed0221c3b202baa361748325f4d19ac31c
from django.conf import settings from django.contrib.auth import get_user, get_user_model from django.contrib.auth.models import AnonymousUser, User from django.core.exceptions import ImproperlyConfigured from django.db import IntegrityError from django.http import HttpRequest from django.test import TestCase, override_settings from django.utils import translation from .models import CustomUser class BasicTestCase(TestCase): def test_user(self): "Users can be created and can set their password" u = User.objects.create_user("testuser", "[email protected]", "testpw") self.assertTrue(u.has_usable_password()) self.assertFalse(u.check_password("bad")) self.assertTrue(u.check_password("testpw")) # Check we can manually set an unusable password u.set_unusable_password() u.save() self.assertFalse(u.check_password("testpw")) self.assertFalse(u.has_usable_password()) u.set_password("testpw") self.assertTrue(u.check_password("testpw")) u.set_password(None) self.assertFalse(u.has_usable_password()) # Check username getter self.assertEqual(u.get_username(), "testuser") # Check authentication/permissions self.assertFalse(u.is_anonymous) self.assertTrue(u.is_authenticated) self.assertFalse(u.is_staff) self.assertTrue(u.is_active) self.assertFalse(u.is_superuser) # Check API-based user creation with no password u2 = User.objects.create_user("testuser2", "[email protected]") self.assertFalse(u2.has_usable_password()) def test_unicode_username(self): User.objects.create_user("jörg") User.objects.create_user("Григорий") # Two equivalent Unicode normalized usernames are duplicates. omega_username = "iamtheΩ" # U+03A9 GREEK CAPITAL LETTER OMEGA ohm_username = "iamtheΩ" # U+2126 OHM SIGN User.objects.create_user(ohm_username) with self.assertRaises(IntegrityError): User.objects.create_user(omega_username) def test_user_no_email(self): "Users can be created without an email" cases = [ {}, {"email": ""}, {"email": None}, ] for i, kwargs in enumerate(cases): with self.subTest(**kwargs): u = User.objects.create_user("testuser{}".format(i), **kwargs) self.assertEqual(u.email, "") def test_superuser(self): "Check the creation and properties of a superuser" super = User.objects.create_superuser("super", "[email protected]", "super") self.assertTrue(super.is_superuser) self.assertTrue(super.is_active) self.assertTrue(super.is_staff) def test_superuser_no_email_or_password(self): cases = [ {}, {"email": ""}, {"email": None}, {"password": None}, ] for i, kwargs in enumerate(cases): with self.subTest(**kwargs): superuser = User.objects.create_superuser("super{}".format(i), **kwargs) self.assertEqual(superuser.email, "") self.assertFalse(superuser.has_usable_password()) def test_get_user_model(self): "The current user model can be retrieved" self.assertEqual(get_user_model(), User) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUser") def test_swappable_user(self): "The current user model can be swapped out for another" self.assertEqual(get_user_model(), CustomUser) with self.assertRaises(AttributeError): User.objects.all() @override_settings(AUTH_USER_MODEL="badsetting") def test_swappable_user_bad_setting(self): "The alternate user setting must point to something in the format app.model" msg = "AUTH_USER_MODEL must be of the form 'app_label.model_name'" with self.assertRaisesMessage(ImproperlyConfigured, msg): get_user_model() @override_settings(AUTH_USER_MODEL="thismodel.doesntexist") def test_swappable_user_nonexistent_model(self): "The current user model must point to an installed model" msg = ( "AUTH_USER_MODEL refers to model 'thismodel.doesntexist' " "that has not been installed" ) with self.assertRaisesMessage(ImproperlyConfigured, msg): get_user_model() def test_user_verbose_names_translatable(self): "Default User model verbose names are translatable (#19945)" with translation.override("en"): self.assertEqual(User._meta.verbose_name, "user") self.assertEqual(User._meta.verbose_name_plural, "users") with translation.override("es"): self.assertEqual(User._meta.verbose_name, "usuario") self.assertEqual(User._meta.verbose_name_plural, "usuarios") class TestGetUser(TestCase): def test_get_user_anonymous(self): request = HttpRequest() request.session = self.client.session user = get_user(request) self.assertIsInstance(user, AnonymousUser) def test_get_user(self): created_user = User.objects.create_user( "testuser", "[email protected]", "testpw" ) self.client.login(username="testuser", password="testpw") request = HttpRequest() request.session = self.client.session user = get_user(request) self.assertIsInstance(user, User) self.assertEqual(user.username, created_user.username) def test_get_user_fallback_secret(self): created_user = User.objects.create_user( "testuser", "[email protected]", "testpw" ) self.client.login(username="testuser", password="testpw") request = HttpRequest() request.session = self.client.session prev_session_key = request.session.session_key with override_settings( SECRET_KEY="newsecret", SECRET_KEY_FALLBACKS=[settings.SECRET_KEY], ): user = get_user(request) self.assertIsInstance(user, User) self.assertEqual(user.username, created_user.username) self.assertNotEqual(request.session.session_key, prev_session_key) # Remove the fallback secret. # The session hash should be updated using the current secret. with override_settings(SECRET_KEY="newsecret"): user = get_user(request) self.assertIsInstance(user, User) self.assertEqual(user.username, created_user.username)
24c7d40f0b5f9c257faf1f9f66b735584988dafddc9b21f7a747c1a17ca1019d
import json import os import shutil import sys import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles import finders, storage from django.contrib.staticfiles.management.commands.collectstatic import ( Command as CollectstaticCommand, ) from django.core.management import call_command from django.test import SimpleTestCase, override_settings from .cases import CollectionTestCase from .settings import TEST_ROOT def hashed_file_path(test, path): fullpath = test.render_template(test.static_template_snippet(path)) return fullpath.replace(settings.STATIC_URL, "") class TestHashedFiles: hashed_file_path = hashed_file_path def tearDown(self): # Clear hashed files to avoid side effects among tests. storage.staticfiles_storage.hashed_files.clear() def assertPostCondition(self): """ Assert post conditions for a test are met. Must be manually called at the end of each test. """ pass def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.dad0999e4f8f.txt") self.assertStaticRenders( "test/file.txt", "/static/test/file.dad0999e4f8f.txt", asvar=True ) self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.5e0040571e1a.css" ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") self.assertPostCondition() def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_ignored_completely(self): relpath = self.hashed_file_path("cached/css/ignored.css") self.assertEqual(relpath, "cached/css/ignored.55e7c226dda1.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"#foobar", content) self.assertIn(b"http:foobar", content) self.assertIn(b"https:foobar", content) self.assertIn(b"data:foobar", content) self.assertIn(b"chrome:foobar", content) self.assertIn(b"//foobar", content) self.assertIn(b"url()", content) self.assertPostCondition() def test_path_with_querystring(self): relpath = self.hashed_file_path("cached/styles.css?spam=eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css?spam=eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_fragment(self): relpath = self.hashed_file_path("cached/styles.css#eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css#eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_querystring_and_fragment(self): relpath = self.hashed_file_path("cached/css/fragments.css") self.assertEqual(relpath, "cached/css/fragments.a60c0e74834f.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"fonts/font.b9b105392eb8.eot?#iefix", content) self.assertIn(b"fonts/font.b8d603e42714.svg#webfontIyfZbseF", content) self.assertIn( b"fonts/font.b8d603e42714.svg#path/to/../../fonts/font.svg", content ) self.assertIn( b"data:font/woff;charset=utf-8;" b"base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA", content, ) self.assertIn(b"#default#VML", content) self.assertPostCondition() def test_template_tag_absolute(self): relpath = self.hashed_file_path("cached/absolute.css") self.assertEqual(relpath, "cached/absolute.eb04def9f9a4.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/cached/styles.css", content) self.assertIn(b"/static/cached/styles.5e0040571e1a.css", content) self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertIn(b"/static/cached/img/relative.acae32e4532b.png", content) self.assertPostCondition() def test_template_tag_absolute_root(self): """ Like test_template_tag_absolute, but for a file in STATIC_ROOT (#26249). """ relpath = self.hashed_file_path("absolute_root.css") self.assertEqual(relpath, "absolute_root.f821df1b64f7.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertPostCondition() def test_template_tag_relative(self): relpath = self.hashed_file_path("cached/relative.css") self.assertEqual(relpath, "cached/relative.c3e9e1ea6f2e.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"../cached/styles.css", content) self.assertNotIn(b'@import "styles.css"', content) self.assertNotIn(b"url(img/relative.png)", content) self.assertIn(b'url("img/relative.acae32e4532b.png")', content) self.assertIn(b"../cached/styles.5e0040571e1a.css", content) self.assertPostCondition() def test_import_replacement(self): "See #18050" relpath = self.hashed_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"""import url("styles.5e0040571e1a.css")""", relfile.read()) self.assertPostCondition() def test_template_tag_deep_relative(self): relpath = self.hashed_file_path("cached/css/window.css") self.assertEqual(relpath, "cached/css/window.5d5c10836967.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"url(img/window.png)", content) self.assertIn(b'url("img/window.acae32e4532b.png")', content) self.assertPostCondition() def test_template_tag_url(self): relpath = self.hashed_file_path("cached/url.css") self.assertEqual(relpath, "cached/url.902310b73412.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"https://", relfile.read()) self.assertPostCondition() def test_module_import(self): relpath = self.hashed_file_path("cached/module.js") self.assertEqual(relpath, "cached/module.55fd6938fbc5.js") tests = [ # Relative imports. b'import testConst from "./module_test.477bbebe77f0.js";', b'import relativeModule from "../nested/js/nested.866475c46bb4.js";', b'import { firstConst, secondConst } from "./module_test.477bbebe77f0.js";', # Absolute import. b'import rootConst from "/static/absolute_root.5586327fe78c.js";', # Dynamic import. b'const dynamicModule = import("./module_test.477bbebe77f0.js");', # Creating a module object. b'import * as NewModule from "./module_test.477bbebe77f0.js";', # Aliases. b'import { testConst as alias } from "./module_test.477bbebe77f0.js";', b"import {\n" b" firstVar1 as firstVarAlias,\n" b" $second_var_2 as secondVarAlias\n" b'} from "./module_test.477bbebe77f0.js";', ] with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() for module_import in tests: with self.subTest(module_import=module_import): self.assertIn(module_import, content) self.assertPostCondition() def test_aggregating_modules(self): relpath = self.hashed_file_path("cached/module.js") self.assertEqual(relpath, "cached/module.55fd6938fbc5.js") tests = [ b'export * from "./module_test.477bbebe77f0.js";', b'export { testConst } from "./module_test.477bbebe77f0.js";', b"export {\n" b" firstVar as firstVarAlias,\n" b" secondVar as secondVarAlias\n" b'} from "./module_test.477bbebe77f0.js";', ] with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() for module_import in tests: with self.subTest(module_import=module_import): self.assertIn(module_import, content) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "loop")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_import_loop(self): finders.get_finder.cache_clear() err = StringIO() with self.assertRaisesMessage(RuntimeError, "Max post-process passes exceeded"): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'All' failed!\n\n", err.getvalue()) self.assertPostCondition() def test_post_processing(self): """ post_processing behaves correctly. Files that are alterable should always be post-processed; files that aren't should be skipped. collectstatic has already been called once in setUp() for this testcase, therefore we check by verifying behavior on a second run. """ collectstatic_args = { "interactive": False, "verbosity": 0, "link": False, "clear": False, "dry_run": False, "post_process": True, "use_default_ignore_patterns": True, "ignore_patterns": ["*.ignoreme"], } collectstatic_cmd = CollectstaticCommand() collectstatic_cmd.set_options(**collectstatic_args) stats = collectstatic_cmd.collect() self.assertIn( os.path.join("cached", "css", "window.css"), stats["post_processed"] ) self.assertIn( os.path.join("cached", "css", "img", "window.png"), stats["unmodified"] ) self.assertIn(os.path.join("test", "nonascii.css"), stats["post_processed"]) # No file should be yielded twice. self.assertCountEqual(stats["post_processed"], set(stats["post_processed"])) self.assertPostCondition() def test_css_import_case_insensitive(self): relpath = self.hashed_file_path("cached/styles_insensitive.css") self.assertEqual(relpath, "cached/styles_insensitive.3fa427592a53.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_css_source_map(self): relpath = self.hashed_file_path("cached/source_map.css") self.assertEqual(relpath, "cached/source_map.b2fceaf426aa.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/*# sourceMappingURL=source_map.css.map*/", content) self.assertIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_tabs(self): relpath = self.hashed_file_path("cached/source_map_tabs.css") self.assertEqual(relpath, "cached/source_map_tabs.b2fceaf426aa.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/*#\tsourceMappingURL=source_map.css.map\t*/", content) self.assertIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.css") self.assertEqual(relpath, "cached/source_map_sensitive.456683f2106f.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"/*# sOuRcEMaPpInGURL=source_map.css.map */", content) self.assertNotIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_js_source_map(self): relpath = self.hashed_file_path("cached/source_map.js") self.assertEqual(relpath, "cached/source_map.cd45b8534a87.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"//# sourceMappingURL=source_map.js.map", content) self.assertIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_trailing_whitespace(self): relpath = self.hashed_file_path("cached/source_map_trailing_whitespace.js") self.assertEqual( relpath, "cached/source_map_trailing_whitespace.cd45b8534a87.js" ) with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"//# sourceMappingURL=source_map.js.map\t ", content) self.assertIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.js") self.assertEqual(relpath, "cached/source_map_sensitive.5da96fdd3cb3.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"//# sOuRcEMaPpInGURL=source_map.js.map", content) self.assertNotIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "faulty")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_post_processing_failure(self): """ post_processing indicates the origin of the error when it fails. """ finders.get_finder.cache_clear() err = StringIO() with self.assertRaises(Exception): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue()) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "nonutf8")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_post_processing_nonutf8(self): finders.get_finder.cache_clear() err = StringIO() with self.assertRaises(UnicodeDecodeError): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'nonutf8.css' failed!\n\n", err.getvalue()) self.assertPostCondition() @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.ExtraPatternsStorage", }, } ) class TestExtraPatternsStorage(CollectionTestCase): def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def cached_file_path(self, path): fullpath = self.render_template(self.static_template_snippet(path)) return fullpath.replace(settings.STATIC_URL, "") def test_multi_extension_patterns(self): """ With storage classes having several file extension patterns, only the files matching a specific file pattern should be affected by the substitution (#19670). """ # CSS files shouldn't be touched by JS patterns. relpath = self.cached_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'import url("styles.5e0040571e1a.css")', relfile.read()) # Confirm JS patterns have been applied to JS files. relpath = self.cached_file_path("cached/test.js") self.assertEqual(relpath, "cached/test.388d7a790d46.js") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'JS_URL("import.f53576679e5a.css")', relfile.read()) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, } ) class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase): """ Tests for the Cache busting storage """ def setUp(self): super().setUp() temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self._clear_filename = os.path.join(temp_dir, "test", "cleared.txt") with open(self._clear_filename, "w") as f: f.write("to be deleted in one test") self.patched_settings = self.settings( STATICFILES_DIRS=settings.STATICFILES_DIRS + [temp_dir], ) self.patched_settings.enable() self.addCleanup(shutil.rmtree, temp_dir) self._manifest_strict = storage.staticfiles_storage.manifest_strict def tearDown(self): self.patched_settings.disable() if os.path.exists(self._clear_filename): os.unlink(self._clear_filename) storage.staticfiles_storage.manifest_strict = self._manifest_strict super().tearDown() def assertPostCondition(self): hashed_files = storage.staticfiles_storage.hashed_files # The in-memory version of the manifest matches the one on disk # since a properly created manifest should cover all filenames. if hashed_files: manifest, _ = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_manifest_exists(self): filename = storage.staticfiles_storage.manifest_name path = storage.staticfiles_storage.path(filename) self.assertTrue(os.path.exists(path)) def test_manifest_does_not_exist(self): storage.staticfiles_storage.manifest_name = "does.not.exist.json" self.assertIsNone(storage.staticfiles_storage.read_manifest()) def test_manifest_does_not_ignore_permission_error(self): with mock.patch("builtins.open", side_effect=PermissionError): with self.assertRaises(PermissionError): storage.staticfiles_storage.read_manifest() def test_loaded_cache(self): self.assertNotEqual(storage.staticfiles_storage.hashed_files, {}) manifest_content = storage.staticfiles_storage.read_manifest() self.assertIn( '"version": "%s"' % storage.staticfiles_storage.manifest_version, manifest_content, ) def test_parse_cache(self): hashed_files = storage.staticfiles_storage.hashed_files manifest, _ = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_clear_empties_manifest(self): cleared_file_name = storage.staticfiles_storage.clean_name( os.path.join("test", "cleared.txt") ) # collect the additional file self.run_collectstatic() hashed_files = storage.staticfiles_storage.hashed_files self.assertIn(cleared_file_name, hashed_files) manifest_content, _ = storage.staticfiles_storage.load_manifest() self.assertIn(cleared_file_name, manifest_content) original_path = storage.staticfiles_storage.path(cleared_file_name) self.assertTrue(os.path.exists(original_path)) # delete the original file form the app, collect with clear os.unlink(self._clear_filename) self.run_collectstatic(clear=True) self.assertFileNotFound(original_path) hashed_files = storage.staticfiles_storage.hashed_files self.assertNotIn(cleared_file_name, hashed_files) manifest_content, _ = storage.staticfiles_storage.load_manifest() self.assertNotIn(cleared_file_name, manifest_content) def test_missing_entry(self): missing_file_name = "cached/missing.css" configured_storage = storage.staticfiles_storage self.assertNotIn(missing_file_name, configured_storage.hashed_files) # File name not found in manifest with self.assertRaisesMessage( ValueError, "Missing staticfiles manifest entry for '%s'" % missing_file_name, ): self.hashed_file_path(missing_file_name) configured_storage.manifest_strict = False # File doesn't exist on disk err_msg = "The file '%s' could not be found with %r." % ( missing_file_name, configured_storage._wrapped, ) with self.assertRaisesMessage(ValueError, err_msg): self.hashed_file_path(missing_file_name) content = StringIO() content.write("Found") configured_storage.save(missing_file_name, content) # File exists on disk self.hashed_file_path(missing_file_name) def test_intermediate_files(self): cached_files = os.listdir(os.path.join(settings.STATIC_ROOT, "cached")) # Intermediate files shouldn't be created for reference. self.assertEqual( len( [ cached_file for cached_file in cached_files if cached_file.startswith("relative.") ] ), 2, ) def test_manifest_hash(self): # Collect the additional file. self.run_collectstatic() _, manifest_hash_orig = storage.staticfiles_storage.load_manifest() self.assertNotEqual(manifest_hash_orig, "") self.assertEqual(storage.staticfiles_storage.manifest_hash, manifest_hash_orig) # Saving doesn't change the hash. storage.staticfiles_storage.save_manifest() self.assertEqual(storage.staticfiles_storage.manifest_hash, manifest_hash_orig) # Delete the original file from the app, collect with clear. os.unlink(self._clear_filename) self.run_collectstatic(clear=True) # Hash is changed. _, manifest_hash = storage.staticfiles_storage.load_manifest() self.assertNotEqual(manifest_hash, manifest_hash_orig) def test_manifest_hash_v1(self): storage.staticfiles_storage.manifest_name = "staticfiles_v1.json" manifest_content, manifest_hash = storage.staticfiles_storage.load_manifest() self.assertEqual(manifest_hash, "") self.assertEqual(manifest_content, {"dummy.txt": "dummy.txt"}) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.NoneHashStorage", }, } ) class TestCollectionNoneHashStorage(CollectionTestCase): hashed_file_path = hashed_file_path def test_hashed_name(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.css") @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.NoPostProcessReplacedPathStorage", }, } ) class TestCollectionNoPostProcessReplacedPaths(CollectionTestCase): run_collectstatic_in_setUp = False def test_collectstatistic_no_post_process_replaced_paths(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout) self.assertIn("post-processed", stdout.getvalue()) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.SimpleStorage", }, } ) class TestCollectionSimpleStorage(CollectionTestCase): hashed_file_path = hashed_file_path def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.deploy12345.txt") self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.deploy12345.css" ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.deploy12345.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.deploy12345.css", content) class CustomManifestStorage(storage.ManifestStaticFilesStorage): def __init__(self, *args, manifest_storage=None, **kwargs): manifest_storage = storage.StaticFilesStorage( location=kwargs.pop("manifest_location"), ) super().__init__(*args, manifest_storage=manifest_storage, **kwargs) class TestCustomManifestStorage(SimpleTestCase): def setUp(self): self.manifest_path = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, self.manifest_path) self.staticfiles_storage = CustomManifestStorage( manifest_location=self.manifest_path, ) self.manifest_file = self.manifest_path / self.staticfiles_storage.manifest_name # Manifest without paths. self.manifest = {"version": self.staticfiles_storage.manifest_version} with self.manifest_file.open("w") as manifest_file: json.dump(self.manifest, manifest_file) def test_read_manifest(self): self.assertEqual( self.staticfiles_storage.read_manifest(), json.dumps(self.manifest), ) def test_read_manifest_nonexistent(self): os.remove(self.manifest_file) self.assertIsNone(self.staticfiles_storage.read_manifest()) def test_save_manifest_override(self): self.assertIs(self.manifest_file.exists(), True) self.staticfiles_storage.save_manifest() self.assertIs(self.manifest_file.exists(), True) new_manifest = json.loads(self.staticfiles_storage.read_manifest()) self.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) def test_save_manifest_create(self): os.remove(self.manifest_file) self.staticfiles_storage.save_manifest() self.assertIs(self.manifest_file.exists(), True) new_manifest = json.loads(self.staticfiles_storage.read_manifest()) self.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) class CustomStaticFilesStorage(storage.StaticFilesStorage): """ Used in TestStaticFilePermissions """ def __init__(self, *args, **kwargs): kwargs["file_permissions_mode"] = 0o640 kwargs["directory_permissions_mode"] = 0o740 super().__init__(*args, **kwargs) @unittest.skipIf(sys.platform == "win32", "Windows only partially supports chmod.") class TestStaticFilePermissions(CollectionTestCase): command_params = { "interactive": False, "verbosity": 0, "ignore_patterns": ["*.ignoreme"], } def setUp(self): self.umask = 0o027 self.old_umask = os.umask(self.umask) super().setUp() def tearDown(self): os.umask(self.old_umask) super().tearDown() # Don't run collectstatic command in this test class. def run_collectstatic(self, **kwargs): pass @override_settings( FILE_UPLOAD_PERMISSIONS=0o655, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, ) def test_collect_static_files_permissions(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o655) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o765) @override_settings( FILE_UPLOAD_PERMISSIONS=None, FILE_UPLOAD_DIRECTORY_PERMISSIONS=None, ) def test_collect_static_files_default_permissions(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o666 & ~self.umask) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o777 & ~self.umask) @override_settings( FILE_UPLOAD_PERMISSIONS=0o655, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.test_storage.CustomStaticFilesStorage", }, }, ) def test_collect_static_files_subclass_of_static_storage(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o640) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o740) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, } ) class TestCollectionHashedFilesCache(CollectionTestCase): """ Files referenced from CSS use the correct final hashed name regardless of the order in which the files are post-processed. """ hashed_file_path = hashed_file_path def setUp(self): super().setUp() self._temp_dir = temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self.addCleanup(shutil.rmtree, temp_dir) def _get_filename_path(self, filename): return os.path.join(self._temp_dir, "test", filename) def test_file_change_after_collectstatic(self): # Create initial static files. file_contents = ( ("foo.png", "foo"), ("bar.css", 'url("foo.png")\nurl("xyz.png")'), ("xyz.png", "xyz"), ) for filename, content in file_contents: with open(self._get_filename_path(filename), "w") as f: f.write(content) with self.modify_settings(STATICFILES_DIRS={"append": self._temp_dir}): finders.get_finder.cache_clear() err = StringIO() # First collectstatic run. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.acbd18db4cc2.png", content) self.assertIn(b"xyz.d16fb36f0911.png", content) # Change the contents of the png files. for filename in ("foo.png", "xyz.png"): with open(self._get_filename_path(filename), "w+b") as f: f.write(b"new content of file to change its hash") # The hashes of the png files in the CSS file are updated after # a second collectstatic. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.57a5cb9ba68d.png", content) self.assertIn(b"xyz.57a5cb9ba68d.png", content)
a8098937aa54b3ca507213743388f3a56e89d8a76fad41fd144ea7efb4932dd6
from django.apps import apps from django.contrib.contenttypes.models import ContentType, ContentTypeManager from django.db import models from django.db.migrations.state import ProjectState from django.test import TestCase, override_settings from django.test.utils import isolate_apps from .models import Author, ConcreteModel, FooWithUrl, ProxyModel class ContentTypesTests(TestCase): def setUp(self): ContentType.objects.clear_cache() def tearDown(self): ContentType.objects.clear_cache() def test_lookup_cache(self): """ The content type cache (see ContentTypeManager) works correctly. Lookups for a particular content type -- by model, ID, or natural key -- should hit the database only on the first lookup. """ # At this point, a lookup for a ContentType should hit the DB with self.assertNumQueries(1): ContentType.objects.get_for_model(ContentType) # A second hit, though, won't hit the DB, nor will a lookup by ID # or natural key with self.assertNumQueries(0): ct = ContentType.objects.get_for_model(ContentType) with self.assertNumQueries(0): ContentType.objects.get_for_id(ct.id) with self.assertNumQueries(0): ContentType.objects.get_by_natural_key("contenttypes", "contenttype") # Once we clear the cache, another lookup will again hit the DB ContentType.objects.clear_cache() with self.assertNumQueries(1): ContentType.objects.get_for_model(ContentType) # The same should happen with a lookup by natural key ContentType.objects.clear_cache() with self.assertNumQueries(1): ContentType.objects.get_by_natural_key("contenttypes", "contenttype") # And a second hit shouldn't hit the DB with self.assertNumQueries(0): ContentType.objects.get_by_natural_key("contenttypes", "contenttype") def test_get_for_models_creation(self): ContentType.objects.all().delete() with self.assertNumQueries(4): cts = ContentType.objects.get_for_models( ContentType, FooWithUrl, ProxyModel, ConcreteModel ) self.assertEqual( cts, { ContentType: ContentType.objects.get_for_model(ContentType), FooWithUrl: ContentType.objects.get_for_model(FooWithUrl), ProxyModel: ContentType.objects.get_for_model(ProxyModel), ConcreteModel: ContentType.objects.get_for_model(ConcreteModel), }, ) def test_get_for_models_empty_cache(self): # Empty cache. with self.assertNumQueries(1): cts = ContentType.objects.get_for_models( ContentType, FooWithUrl, ProxyModel, ConcreteModel ) self.assertEqual( cts, { ContentType: ContentType.objects.get_for_model(ContentType), FooWithUrl: ContentType.objects.get_for_model(FooWithUrl), ProxyModel: ContentType.objects.get_for_model(ProxyModel), ConcreteModel: ContentType.objects.get_for_model(ConcreteModel), }, ) def test_get_for_models_partial_cache(self): # Partial cache ContentType.objects.get_for_model(ContentType) with self.assertNumQueries(1): cts = ContentType.objects.get_for_models(ContentType, FooWithUrl) self.assertEqual( cts, { ContentType: ContentType.objects.get_for_model(ContentType), FooWithUrl: ContentType.objects.get_for_model(FooWithUrl), }, ) def test_get_for_models_migrations(self): state = ProjectState.from_apps(apps.get_app_config("contenttypes")) ContentType = state.apps.get_model("contenttypes", "ContentType") cts = ContentType.objects.get_for_models(ContentType) self.assertEqual( cts, {ContentType: ContentType.objects.get_for_model(ContentType)} ) def test_get_for_models_full_cache(self): # Full cache ContentType.objects.get_for_model(ContentType) ContentType.objects.get_for_model(FooWithUrl) with self.assertNumQueries(0): cts = ContentType.objects.get_for_models(ContentType, FooWithUrl) self.assertEqual( cts, { ContentType: ContentType.objects.get_for_model(ContentType), FooWithUrl: ContentType.objects.get_for_model(FooWithUrl), }, ) @isolate_apps("contenttypes_tests") def test_get_for_model_create_contenttype(self): """ ContentTypeManager.get_for_model() creates the corresponding content type if it doesn't exist in the database. """ class ModelCreatedOnTheFly(models.Model): name = models.CharField() ct = ContentType.objects.get_for_model(ModelCreatedOnTheFly) self.assertEqual(ct.app_label, "contenttypes_tests") self.assertEqual(ct.model, "modelcreatedonthefly") self.assertEqual(str(ct), "modelcreatedonthefly") def test_get_for_concrete_model(self): """ Make sure the `for_concrete_model` kwarg correctly works with concrete, proxy and deferred models """ concrete_model_ct = ContentType.objects.get_for_model(ConcreteModel) self.assertEqual( concrete_model_ct, ContentType.objects.get_for_model(ProxyModel) ) self.assertEqual( concrete_model_ct, ContentType.objects.get_for_model(ConcreteModel, for_concrete_model=False), ) proxy_model_ct = ContentType.objects.get_for_model( ProxyModel, for_concrete_model=False ) self.assertNotEqual(concrete_model_ct, proxy_model_ct) # Make sure deferred model are correctly handled ConcreteModel.objects.create(name="Concrete") DeferredConcreteModel = ConcreteModel.objects.only("pk").get().__class__ DeferredProxyModel = ProxyModel.objects.only("pk").get().__class__ self.assertEqual( concrete_model_ct, ContentType.objects.get_for_model(DeferredConcreteModel) ) self.assertEqual( concrete_model_ct, ContentType.objects.get_for_model( DeferredConcreteModel, for_concrete_model=False ), ) self.assertEqual( concrete_model_ct, ContentType.objects.get_for_model(DeferredProxyModel) ) self.assertEqual( proxy_model_ct, ContentType.objects.get_for_model( DeferredProxyModel, for_concrete_model=False ), ) def test_get_for_concrete_models(self): """ Make sure the `for_concrete_models` kwarg correctly works with concrete, proxy and deferred models. """ concrete_model_ct = ContentType.objects.get_for_model(ConcreteModel) cts = ContentType.objects.get_for_models(ConcreteModel, ProxyModel) self.assertEqual( cts, { ConcreteModel: concrete_model_ct, ProxyModel: concrete_model_ct, }, ) proxy_model_ct = ContentType.objects.get_for_model( ProxyModel, for_concrete_model=False ) cts = ContentType.objects.get_for_models( ConcreteModel, ProxyModel, for_concrete_models=False ) self.assertEqual( cts, { ConcreteModel: concrete_model_ct, ProxyModel: proxy_model_ct, }, ) # Make sure deferred model are correctly handled ConcreteModel.objects.create(name="Concrete") DeferredConcreteModel = ConcreteModel.objects.only("pk").get().__class__ DeferredProxyModel = ProxyModel.objects.only("pk").get().__class__ cts = ContentType.objects.get_for_models( DeferredConcreteModel, DeferredProxyModel ) self.assertEqual( cts, { DeferredConcreteModel: concrete_model_ct, DeferredProxyModel: concrete_model_ct, }, ) cts = ContentType.objects.get_for_models( DeferredConcreteModel, DeferredProxyModel, for_concrete_models=False ) self.assertEqual( cts, { DeferredConcreteModel: concrete_model_ct, DeferredProxyModel: proxy_model_ct, }, ) def test_cache_not_shared_between_managers(self): with self.assertNumQueries(1): ContentType.objects.get_for_model(ContentType) with self.assertNumQueries(0): ContentType.objects.get_for_model(ContentType) other_manager = ContentTypeManager() other_manager.model = ContentType with self.assertNumQueries(1): other_manager.get_for_model(ContentType) with self.assertNumQueries(0): other_manager.get_for_model(ContentType) def test_missing_model(self): """ Displaying content types in admin (or anywhere) doesn't break on leftover content type records in the DB for which no model is defined anymore. """ ct = ContentType.objects.create( app_label="contenttypes", model="OldModel", ) self.assertEqual(str(ct), "OldModel") self.assertIsNone(ct.model_class()) # Stale ContentTypes can be fetched like any other object. ct_fetched = ContentType.objects.get_for_id(ct.pk) self.assertIsNone(ct_fetched.model_class()) def test_missing_model_with_existing_model_name(self): """ Displaying content types in admin (or anywhere) doesn't break on leftover content type records in the DB for which no model is defined anymore, even if a model with the same name exists in another app. """ # Create a stale ContentType that matches the name of an existing # model. ContentType.objects.create(app_label="contenttypes", model="author") ContentType.objects.clear_cache() # get_for_models() should work as expected for existing models. cts = ContentType.objects.get_for_models(ContentType, Author) self.assertEqual( cts, { ContentType: ContentType.objects.get_for_model(ContentType), Author: ContentType.objects.get_for_model(Author), }, ) def test_str(self): ct = ContentType.objects.get(app_label="contenttypes_tests", model="site") self.assertEqual(str(ct), "Contenttypes_Tests | site") def test_str_auth(self): ct = ContentType.objects.get(app_label="auth", model="group") self.assertEqual(str(ct), "Authentication and Authorization | group") def test_name(self): ct = ContentType.objects.get(app_label="contenttypes_tests", model="site") self.assertEqual(ct.name, "site") def test_app_labeled_name(self): ct = ContentType.objects.get(app_label="contenttypes_tests", model="site") self.assertEqual(ct.app_labeled_name, "Contenttypes_Tests | site") def test_name_unknown_model(self): ct = ContentType(app_label="contenttypes_tests", model="unknown") self.assertEqual(ct.name, "unknown") def test_app_labeled_name_unknown_model(self): ct = ContentType(app_label="contenttypes_tests", model="unknown") self.assertEqual(ct.app_labeled_name, "unknown") class TestRouter: def db_for_read(self, model, **hints): return "other" def db_for_write(self, model, **hints): return "default" def allow_relation(self, obj1, obj2, **hints): return True @override_settings(DATABASE_ROUTERS=[TestRouter()]) class ContentTypesMultidbTests(TestCase): databases = {"default", "other"} def test_multidb(self): """ When using multiple databases, ContentType.objects.get_for_model() uses db_for_read(). """ ContentType.objects.clear_cache() with self.assertNumQueries(0, using="default"), self.assertNumQueries( 1, using="other" ): ContentType.objects.get_for_model(Author)
8efe49122b3a5fb1d09297ff794ab192865468cd1257b4e00e33b0484fddee75
from unittest import SkipTest from django.core import validators from django.core.exceptions import ValidationError from django.db import IntegrityError, connection, models from django.test import SimpleTestCase, TestCase from .models import ( BigIntegerModel, IntegerModel, PositiveBigIntegerModel, PositiveIntegerModel, PositiveSmallIntegerModel, SmallIntegerModel, ) class IntegerFieldTests(TestCase): model = IntegerModel documented_range = (-2147483648, 2147483647) rel_db_type_class = models.IntegerField @property def backend_range(self): field = self.model._meta.get_field("value") internal_type = field.get_internal_type() return connection.ops.integer_field_range(internal_type) def test_documented_range(self): """ Values within the documented safe range pass validation, and can be saved and retrieved without corruption. """ min_value, max_value = self.documented_range instance = self.model(value=min_value) instance.full_clean() instance.save() qs = self.model.objects.filter(value__lte=min_value) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, min_value) instance = self.model(value=max_value) instance.full_clean() instance.save() qs = self.model.objects.filter(value__gte=max_value) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, max_value) def test_backend_range_save(self): """ Backend specific ranges can be saved without corruption. """ min_value, max_value = self.backend_range if min_value is not None: instance = self.model(value=min_value) instance.full_clean() instance.save() qs = self.model.objects.filter(value__lte=min_value) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, min_value) if max_value is not None: instance = self.model(value=max_value) instance.full_clean() instance.save() qs = self.model.objects.filter(value__gte=max_value) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, max_value) def test_backend_range_validation(self): """ Backend specific ranges are enforced at the model validation level (#12030). """ min_value, max_value = self.backend_range if min_value is not None: instance = self.model(value=min_value - 1) expected_message = validators.MinValueValidator.message % { "limit_value": min_value, } with self.assertRaisesMessage(ValidationError, expected_message): instance.full_clean() instance.value = min_value instance.full_clean() if max_value is not None: instance = self.model(value=max_value + 1) expected_message = validators.MaxValueValidator.message % { "limit_value": max_value, } with self.assertRaisesMessage(ValidationError, expected_message): instance.full_clean() instance.value = max_value instance.full_clean() def test_backend_range_min_value_lookups(self): min_value = self.backend_range[0] if min_value is None: raise SkipTest("Backend doesn't define an integer min value.") underflow_value = min_value - 1 self.model.objects.create(value=min_value) # A refresh of obj is necessary because last_insert_id() is bugged # on MySQL and returns invalid values. obj = self.model.objects.get(value=min_value) with self.assertNumQueries(0), self.assertRaises(self.model.DoesNotExist): self.model.objects.get(value=underflow_value) with self.assertNumQueries(1): self.assertEqual(self.model.objects.get(value__gt=underflow_value), obj) with self.assertNumQueries(1): self.assertEqual(self.model.objects.get(value__gte=underflow_value), obj) with self.assertNumQueries(0), self.assertRaises(self.model.DoesNotExist): self.model.objects.get(value__lt=underflow_value) with self.assertNumQueries(0), self.assertRaises(self.model.DoesNotExist): self.model.objects.get(value__lte=underflow_value) def test_backend_range_max_value_lookups(self): max_value = self.backend_range[-1] if max_value is None: raise SkipTest("Backend doesn't define an integer max value.") overflow_value = max_value + 1 obj = self.model.objects.create(value=max_value) with self.assertNumQueries(0), self.assertRaises(self.model.DoesNotExist): self.model.objects.get(value=overflow_value) with self.assertNumQueries(0), self.assertRaises(self.model.DoesNotExist): self.model.objects.get(value__gt=overflow_value) with self.assertNumQueries(0), self.assertRaises(self.model.DoesNotExist): self.model.objects.get(value__gte=overflow_value) with self.assertNumQueries(1): self.assertEqual(self.model.objects.get(value__lt=overflow_value), obj) with self.assertNumQueries(1): self.assertEqual(self.model.objects.get(value__lte=overflow_value), obj) def test_redundant_backend_range_validators(self): """ If there are stricter validators than the ones from the database backend then the backend validators aren't added. """ min_backend_value, max_backend_value = self.backend_range for callable_limit in (True, False): with self.subTest(callable_limit=callable_limit): if min_backend_value is not None: min_custom_value = min_backend_value + 1 limit_value = ( (lambda: min_custom_value) if callable_limit else min_custom_value ) ranged_value_field = self.model._meta.get_field("value").__class__( validators=[validators.MinValueValidator(limit_value)] ) field_range_message = validators.MinValueValidator.message % { "limit_value": min_custom_value, } with self.assertRaisesMessage( ValidationError, "[%r]" % field_range_message ): ranged_value_field.run_validators(min_backend_value - 1) if max_backend_value is not None: max_custom_value = max_backend_value - 1 limit_value = ( (lambda: max_custom_value) if callable_limit else max_custom_value ) ranged_value_field = self.model._meta.get_field("value").__class__( validators=[validators.MaxValueValidator(limit_value)] ) field_range_message = validators.MaxValueValidator.message % { "limit_value": max_custom_value, } with self.assertRaisesMessage( ValidationError, "[%r]" % field_range_message ): ranged_value_field.run_validators(max_backend_value + 1) def test_types(self): instance = self.model(value=1) self.assertIsInstance(instance.value, int) instance.save() self.assertIsInstance(instance.value, int) instance = self.model.objects.get() self.assertIsInstance(instance.value, int) def test_coercing(self): self.model.objects.create(value="10") instance = self.model.objects.get(value="10") self.assertEqual(instance.value, 10) def test_invalid_value(self): tests = [ (TypeError, ()), (TypeError, []), (TypeError, {}), (TypeError, set()), (TypeError, object()), (TypeError, complex()), (ValueError, "non-numeric string"), (ValueError, b"non-numeric byte-string"), ] for exception, value in tests: with self.subTest(value): msg = "Field 'value' expected a number but got %r." % (value,) with self.assertRaisesMessage(exception, msg): self.model.objects.create(value=value) def test_rel_db_type(self): field = self.model._meta.get_field("value") rel_db_type = field.rel_db_type(connection) self.assertEqual(rel_db_type, self.rel_db_type_class().db_type(connection)) class SmallIntegerFieldTests(IntegerFieldTests): model = SmallIntegerModel documented_range = (-32768, 32767) rel_db_type_class = models.SmallIntegerField class BigIntegerFieldTests(IntegerFieldTests): model = BigIntegerModel documented_range = (-9223372036854775808, 9223372036854775807) rel_db_type_class = models.BigIntegerField class PositiveSmallIntegerFieldTests(IntegerFieldTests): model = PositiveSmallIntegerModel documented_range = (0, 32767) rel_db_type_class = ( models.PositiveSmallIntegerField if connection.features.related_fields_match_type else models.SmallIntegerField ) class PositiveIntegerFieldTests(IntegerFieldTests): model = PositiveIntegerModel documented_range = (0, 2147483647) rel_db_type_class = ( models.PositiveIntegerField if connection.features.related_fields_match_type else models.IntegerField ) def test_negative_values(self): p = PositiveIntegerModel.objects.create(value=0) p.value = models.F("value") - 1 with self.assertRaises(IntegrityError): p.save() class PositiveBigIntegerFieldTests(IntegerFieldTests): model = PositiveBigIntegerModel documented_range = (0, 9223372036854775807) rel_db_type_class = ( models.PositiveBigIntegerField if connection.features.related_fields_match_type else models.BigIntegerField ) class ValidationTests(SimpleTestCase): class Choices(models.IntegerChoices): A = 1 def test_integerfield_cleans_valid_string(self): f = models.IntegerField() self.assertEqual(f.clean("2", None), 2) def test_integerfield_raises_error_on_invalid_intput(self): f = models.IntegerField() with self.assertRaises(ValidationError): f.clean("a", None) def test_choices_validation_supports_named_groups(self): f = models.IntegerField(choices=(("group", ((10, "A"), (20, "B"))), (30, "C"))) self.assertEqual(10, f.clean(10, None)) def test_nullable_integerfield_raises_error_with_blank_false(self): f = models.IntegerField(null=True, blank=False) with self.assertRaises(ValidationError): f.clean(None, None) def test_nullable_integerfield_cleans_none_on_null_and_blank_true(self): f = models.IntegerField(null=True, blank=True) self.assertIsNone(f.clean(None, None)) def test_integerfield_raises_error_on_empty_input(self): f = models.IntegerField(null=False) with self.assertRaises(ValidationError): f.clean(None, None) with self.assertRaises(ValidationError): f.clean("", None) def test_integerfield_validates_zero_against_choices(self): f = models.IntegerField(choices=((1, 1),)) with self.assertRaises(ValidationError): f.clean("0", None) def test_enum_choices_cleans_valid_string(self): f = models.IntegerField(choices=self.Choices.choices) self.assertEqual(f.clean("1", None), 1) def test_enum_choices_invalid_input(self): f = models.IntegerField(choices=self.Choices.choices) with self.assertRaises(ValidationError): f.clean("A", None) with self.assertRaises(ValidationError): f.clean("3", None)
83d8ec8123bbe3bec74a0c27a2e8bf2c24d8a3e9cce221cd88b2ab918e4bede3
import datetime import pickle from io import StringIO from operator import attrgetter from unittest.mock import Mock from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.core import management from django.db import DEFAULT_DB_ALIAS, router, transaction from django.db.models import signals from django.db.utils import ConnectionRouter from django.test import SimpleTestCase, TestCase, override_settings from .models import Book, Person, Pet, Review, UserProfile from .routers import AuthRouter, TestRouter, WriteRouter class QueryTestCase(TestCase): databases = {"default", "other"} def test_db_selection(self): "Querysets will use the default database by default" self.assertEqual(Book.objects.db, DEFAULT_DB_ALIAS) self.assertEqual(Book.objects.all().db, DEFAULT_DB_ALIAS) self.assertEqual(Book.objects.using("other").db, "other") self.assertEqual(Book.objects.db_manager("other").db, "other") self.assertEqual(Book.objects.db_manager("other").all().db, "other") def test_default_creation(self): "Objects created on the default database don't leak onto other databases" # Create a book on the default database using create() Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) # Create a book on the default database using a save dive = Book() dive.title = "Dive into Python" dive.published = datetime.date(2009, 5, 4) dive.save() # Book exists on the default database, but not on other database try: Book.objects.get(title="Pro Django") Book.objects.using("default").get(title="Pro Django") except Book.DoesNotExist: self.fail('"Pro Django" should exist on default database') with self.assertRaises(Book.DoesNotExist): Book.objects.using("other").get(title="Pro Django") try: Book.objects.get(title="Dive into Python") Book.objects.using("default").get(title="Dive into Python") except Book.DoesNotExist: self.fail('"Dive into Python" should exist on default database') with self.assertRaises(Book.DoesNotExist): Book.objects.using("other").get(title="Dive into Python") def test_other_creation(self): "Objects created on another database don't leak onto the default database" # Create a book on the second database Book.objects.using("other").create( title="Pro Django", published=datetime.date(2008, 12, 16) ) # Create a book on the default database using a save dive = Book() dive.title = "Dive into Python" dive.published = datetime.date(2009, 5, 4) dive.save(using="other") # Book exists on the default database, but not on other database try: Book.objects.using("other").get(title="Pro Django") except Book.DoesNotExist: self.fail('"Pro Django" should exist on other database') with self.assertRaises(Book.DoesNotExist): Book.objects.get(title="Pro Django") with self.assertRaises(Book.DoesNotExist): Book.objects.using("default").get(title="Pro Django") try: Book.objects.using("other").get(title="Dive into Python") except Book.DoesNotExist: self.fail('"Dive into Python" should exist on other database') with self.assertRaises(Book.DoesNotExist): Book.objects.get(title="Dive into Python") with self.assertRaises(Book.DoesNotExist): Book.objects.using("default").get(title="Dive into Python") def test_refresh(self): dive = Book(title="Dive into Python", published=datetime.date(2009, 5, 4)) dive.save(using="other") dive2 = Book.objects.using("other").get() dive2.title = "Dive into Python (on default)" dive2.save(using="default") dive.refresh_from_db() self.assertEqual(dive.title, "Dive into Python") dive.refresh_from_db(using="default") self.assertEqual(dive.title, "Dive into Python (on default)") self.assertEqual(dive._state.db, "default") def test_refresh_router_instance_hint(self): router = Mock() router.db_for_read.return_value = None book = Book.objects.create( title="Dive Into Python", published=datetime.date(1957, 10, 12) ) with self.settings(DATABASE_ROUTERS=[router]): book.refresh_from_db() router.db_for_read.assert_called_once_with(Book, instance=book) def test_basic_queries(self): "Queries are constrained to a single database" dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) dive = Book.objects.using("other").get(published=datetime.date(2009, 5, 4)) self.assertEqual(dive.title, "Dive into Python") with self.assertRaises(Book.DoesNotExist): Book.objects.using("default").get(published=datetime.date(2009, 5, 4)) dive = Book.objects.using("other").get(title__icontains="dive") self.assertEqual(dive.title, "Dive into Python") with self.assertRaises(Book.DoesNotExist): Book.objects.using("default").get(title__icontains="dive") dive = Book.objects.using("other").get(title__iexact="dive INTO python") self.assertEqual(dive.title, "Dive into Python") with self.assertRaises(Book.DoesNotExist): Book.objects.using("default").get(title__iexact="dive INTO python") dive = Book.objects.using("other").get(published__year=2009) self.assertEqual(dive.title, "Dive into Python") self.assertEqual(dive.published, datetime.date(2009, 5, 4)) with self.assertRaises(Book.DoesNotExist): Book.objects.using("default").get(published__year=2009) years = Book.objects.using("other").dates("published", "year") self.assertEqual([o.year for o in years], [2009]) years = Book.objects.using("default").dates("published", "year") self.assertEqual([o.year for o in years], []) months = Book.objects.using("other").dates("published", "month") self.assertEqual([o.month for o in months], [5]) months = Book.objects.using("default").dates("published", "month") self.assertEqual([o.month for o in months], []) def test_m2m_separation(self): "M2M fields are constrained to a single database" # Create a book and author on the default database pro = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) marty = Person.objects.create(name="Marty Alchin") # Create a book and author on the other database dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) mark = Person.objects.using("other").create(name="Mark Pilgrim") # Save the author relations pro.authors.set([marty]) dive.authors.set([mark]) # Inspect the m2m tables directly. # There should be 1 entry in each database self.assertEqual(Book.authors.through.objects.using("default").count(), 1) self.assertEqual(Book.authors.through.objects.using("other").count(), 1) # Queries work across m2m joins self.assertEqual( list( Book.objects.using("default") .filter(authors__name="Marty Alchin") .values_list("title", flat=True) ), ["Pro Django"], ) self.assertEqual( list( Book.objects.using("other") .filter(authors__name="Marty Alchin") .values_list("title", flat=True) ), [], ) self.assertEqual( list( Book.objects.using("default") .filter(authors__name="Mark Pilgrim") .values_list("title", flat=True) ), [], ) self.assertEqual( list( Book.objects.using("other") .filter(authors__name="Mark Pilgrim") .values_list("title", flat=True) ), ["Dive into Python"], ) # Reget the objects to clear caches dive = Book.objects.using("other").get(title="Dive into Python") mark = Person.objects.using("other").get(name="Mark Pilgrim") # Retrieve related object by descriptor. Related objects should be # database-bound. self.assertEqual( list(dive.authors.values_list("name", flat=True)), ["Mark Pilgrim"] ) self.assertEqual( list(mark.book_set.values_list("title", flat=True)), ["Dive into Python"], ) def test_m2m_forward_operations(self): "M2M forward manipulations are all constrained to a single DB" # Create a book and author on the other database dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) mark = Person.objects.using("other").create(name="Mark Pilgrim") # Save the author relations dive.authors.set([mark]) # Add a second author john = Person.objects.using("other").create(name="John Smith") self.assertEqual( list( Book.objects.using("other") .filter(authors__name="John Smith") .values_list("title", flat=True) ), [], ) dive.authors.add(john) self.assertEqual( list( Book.objects.using("other") .filter(authors__name="Mark Pilgrim") .values_list("title", flat=True) ), ["Dive into Python"], ) self.assertEqual( list( Book.objects.using("other") .filter(authors__name="John Smith") .values_list("title", flat=True) ), ["Dive into Python"], ) # Remove the second author dive.authors.remove(john) self.assertEqual( list( Book.objects.using("other") .filter(authors__name="Mark Pilgrim") .values_list("title", flat=True) ), ["Dive into Python"], ) self.assertEqual( list( Book.objects.using("other") .filter(authors__name="John Smith") .values_list("title", flat=True) ), [], ) # Clear all authors dive.authors.clear() self.assertEqual( list( Book.objects.using("other") .filter(authors__name="Mark Pilgrim") .values_list("title", flat=True) ), [], ) self.assertEqual( list( Book.objects.using("other") .filter(authors__name="John Smith") .values_list("title", flat=True) ), [], ) # Create an author through the m2m interface dive.authors.create(name="Jane Brown") self.assertEqual( list( Book.objects.using("other") .filter(authors__name="Mark Pilgrim") .values_list("title", flat=True) ), [], ) self.assertEqual( list( Book.objects.using("other") .filter(authors__name="Jane Brown") .values_list("title", flat=True) ), ["Dive into Python"], ) def test_m2m_reverse_operations(self): "M2M reverse manipulations are all constrained to a single DB" # Create a book and author on the other database dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) mark = Person.objects.using("other").create(name="Mark Pilgrim") # Save the author relations dive.authors.set([mark]) # Create a second book on the other database grease = Book.objects.using("other").create( title="Greasemonkey Hacks", published=datetime.date(2005, 11, 1) ) # Add a books to the m2m mark.book_set.add(grease) self.assertEqual( list( Person.objects.using("other") .filter(book__title="Dive into Python") .values_list("name", flat=True) ), ["Mark Pilgrim"], ) self.assertEqual( list( Person.objects.using("other") .filter(book__title="Greasemonkey Hacks") .values_list("name", flat=True) ), ["Mark Pilgrim"], ) # Remove a book from the m2m mark.book_set.remove(grease) self.assertEqual( list( Person.objects.using("other") .filter(book__title="Dive into Python") .values_list("name", flat=True) ), ["Mark Pilgrim"], ) self.assertEqual( list( Person.objects.using("other") .filter(book__title="Greasemonkey Hacks") .values_list("name", flat=True) ), [], ) # Clear the books associated with mark mark.book_set.clear() self.assertEqual( list( Person.objects.using("other") .filter(book__title="Dive into Python") .values_list("name", flat=True) ), [], ) self.assertEqual( list( Person.objects.using("other") .filter(book__title="Greasemonkey Hacks") .values_list("name", flat=True) ), [], ) # Create a book through the m2m interface mark.book_set.create( title="Dive into HTML5", published=datetime.date(2020, 1, 1) ) self.assertEqual( list( Person.objects.using("other") .filter(book__title="Dive into Python") .values_list("name", flat=True) ), [], ) self.assertEqual( list( Person.objects.using("other") .filter(book__title="Dive into HTML5") .values_list("name", flat=True) ), ["Mark Pilgrim"], ) def test_m2m_cross_database_protection(self): "Operations that involve sharing M2M objects across databases raise an error" # Create a book and author on the default database pro = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) marty = Person.objects.create(name="Marty Alchin") # Create a book and author on the other database dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) mark = Person.objects.using("other").create(name="Mark Pilgrim") # Set a foreign key set with an object from a different database msg = ( 'Cannot assign "<Person: Marty Alchin>": the current database ' "router prevents this relation." ) with self.assertRaisesMessage(ValueError, msg): with transaction.atomic(using="default"): marty.edited.set([pro, dive]) # Add to an m2m with an object from a different database msg = ( 'Cannot add "<Book: Dive into Python>": instance is on ' 'database "default", value is on database "other"' ) with self.assertRaisesMessage(ValueError, msg): with transaction.atomic(using="default"): marty.book_set.add(dive) # Set a m2m with an object from a different database with self.assertRaisesMessage(ValueError, msg): with transaction.atomic(using="default"): marty.book_set.set([pro, dive]) # Add to a reverse m2m with an object from a different database msg = ( 'Cannot add "<Person: Marty Alchin>": instance is on ' 'database "other", value is on database "default"' ) with self.assertRaisesMessage(ValueError, msg): with transaction.atomic(using="other"): dive.authors.add(marty) # Set a reverse m2m with an object from a different database with self.assertRaisesMessage(ValueError, msg): with transaction.atomic(using="other"): dive.authors.set([mark, marty]) def test_m2m_deletion(self): "Cascaded deletions of m2m relations issue queries on the right database" # Create a book and author on the other database dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) mark = Person.objects.using("other").create(name="Mark Pilgrim") dive.authors.set([mark]) # Check the initial state self.assertEqual(Person.objects.using("default").count(), 0) self.assertEqual(Book.objects.using("default").count(), 0) self.assertEqual(Book.authors.through.objects.using("default").count(), 0) self.assertEqual(Person.objects.using("other").count(), 1) self.assertEqual(Book.objects.using("other").count(), 1) self.assertEqual(Book.authors.through.objects.using("other").count(), 1) # Delete the object on the other database dive.delete(using="other") self.assertEqual(Person.objects.using("default").count(), 0) self.assertEqual(Book.objects.using("default").count(), 0) self.assertEqual(Book.authors.through.objects.using("default").count(), 0) # The person still exists ... self.assertEqual(Person.objects.using("other").count(), 1) # ... but the book has been deleted self.assertEqual(Book.objects.using("other").count(), 0) # ... and the relationship object has also been deleted. self.assertEqual(Book.authors.through.objects.using("other").count(), 0) # Now try deletion in the reverse direction. Set up the relation again dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) dive.authors.set([mark]) # Check the initial state self.assertEqual(Person.objects.using("default").count(), 0) self.assertEqual(Book.objects.using("default").count(), 0) self.assertEqual(Book.authors.through.objects.using("default").count(), 0) self.assertEqual(Person.objects.using("other").count(), 1) self.assertEqual(Book.objects.using("other").count(), 1) self.assertEqual(Book.authors.through.objects.using("other").count(), 1) # Delete the object on the other database mark.delete(using="other") self.assertEqual(Person.objects.using("default").count(), 0) self.assertEqual(Book.objects.using("default").count(), 0) self.assertEqual(Book.authors.through.objects.using("default").count(), 0) # The person has been deleted ... self.assertEqual(Person.objects.using("other").count(), 0) # ... but the book still exists self.assertEqual(Book.objects.using("other").count(), 1) # ... and the relationship object has been deleted. self.assertEqual(Book.authors.through.objects.using("other").count(), 0) def test_foreign_key_separation(self): "FK fields are constrained to a single database" # Create a book and author on the default database pro = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) george = Person.objects.create(name="George Vilches") # Create a book and author on the other database dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) chris = Person.objects.using("other").create(name="Chris Mills") # Save the author's favorite books pro.editor = george pro.save() dive.editor = chris dive.save() pro = Book.objects.using("default").get(title="Pro Django") self.assertEqual(pro.editor.name, "George Vilches") dive = Book.objects.using("other").get(title="Dive into Python") self.assertEqual(dive.editor.name, "Chris Mills") # Queries work across foreign key joins self.assertEqual( list( Person.objects.using("default") .filter(edited__title="Pro Django") .values_list("name", flat=True) ), ["George Vilches"], ) self.assertEqual( list( Person.objects.using("other") .filter(edited__title="Pro Django") .values_list("name", flat=True) ), [], ) self.assertEqual( list( Person.objects.using("default") .filter(edited__title="Dive into Python") .values_list("name", flat=True) ), [], ) self.assertEqual( list( Person.objects.using("other") .filter(edited__title="Dive into Python") .values_list("name", flat=True) ), ["Chris Mills"], ) # Reget the objects to clear caches chris = Person.objects.using("other").get(name="Chris Mills") dive = Book.objects.using("other").get(title="Dive into Python") # Retrieve related object by descriptor. Related objects should be # database-bound. self.assertEqual( list(chris.edited.values_list("title", flat=True)), ["Dive into Python"] ) def test_foreign_key_reverse_operations(self): "FK reverse manipulations are all constrained to a single DB" dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) chris = Person.objects.using("other").create(name="Chris Mills") # Save the author relations dive.editor = chris dive.save() # Add a second book edited by chris html5 = Book.objects.using("other").create( title="Dive into HTML5", published=datetime.date(2010, 3, 15) ) self.assertEqual( list( Person.objects.using("other") .filter(edited__title="Dive into HTML5") .values_list("name", flat=True) ), [], ) chris.edited.add(html5) self.assertEqual( list( Person.objects.using("other") .filter(edited__title="Dive into HTML5") .values_list("name", flat=True) ), ["Chris Mills"], ) self.assertEqual( list( Person.objects.using("other") .filter(edited__title="Dive into Python") .values_list("name", flat=True) ), ["Chris Mills"], ) # Remove the second editor chris.edited.remove(html5) self.assertEqual( list( Person.objects.using("other") .filter(edited__title="Dive into HTML5") .values_list("name", flat=True) ), [], ) self.assertEqual( list( Person.objects.using("other") .filter(edited__title="Dive into Python") .values_list("name", flat=True) ), ["Chris Mills"], ) # Clear all edited books chris.edited.clear() self.assertEqual( list( Person.objects.using("other") .filter(edited__title="Dive into HTML5") .values_list("name", flat=True) ), [], ) self.assertEqual( list( Person.objects.using("other") .filter(edited__title="Dive into Python") .values_list("name", flat=True) ), [], ) # Create an author through the m2m interface chris.edited.create( title="Dive into Water", published=datetime.date(2010, 3, 15) ) self.assertEqual( list( Person.objects.using("other") .filter(edited__title="Dive into HTML5") .values_list("name", flat=True) ), [], ) self.assertEqual( list( Person.objects.using("other") .filter(edited__title="Dive into Water") .values_list("name", flat=True) ), ["Chris Mills"], ) self.assertEqual( list( Person.objects.using("other") .filter(edited__title="Dive into Python") .values_list("name", flat=True) ), [], ) def test_foreign_key_cross_database_protection(self): "Operations that involve sharing FK objects across databases raise an error" # Create a book and author on the default database pro = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) marty = Person.objects.create(name="Marty Alchin") # Create a book and author on the other database dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) # Set a foreign key with an object from a different database msg = ( 'Cannot assign "<Person: Marty Alchin>": the current database ' "router prevents this relation." ) with self.assertRaisesMessage(ValueError, msg): dive.editor = marty # Set a foreign key set with an object from a different database with self.assertRaisesMessage(ValueError, msg): with transaction.atomic(using="default"): marty.edited.set([pro, dive]) # Add to a foreign key set with an object from a different database with self.assertRaisesMessage(ValueError, msg): with transaction.atomic(using="default"): marty.edited.add(dive) def test_foreign_key_deletion(self): """ Cascaded deletions of Foreign Key relations issue queries on the right database. """ mark = Person.objects.using("other").create(name="Mark Pilgrim") Pet.objects.using("other").create(name="Fido", owner=mark) # Check the initial state self.assertEqual(Person.objects.using("default").count(), 0) self.assertEqual(Pet.objects.using("default").count(), 0) self.assertEqual(Person.objects.using("other").count(), 1) self.assertEqual(Pet.objects.using("other").count(), 1) # Delete the person object, which will cascade onto the pet mark.delete(using="other") self.assertEqual(Person.objects.using("default").count(), 0) self.assertEqual(Pet.objects.using("default").count(), 0) # Both the pet and the person have been deleted from the right database self.assertEqual(Person.objects.using("other").count(), 0) self.assertEqual(Pet.objects.using("other").count(), 0) def test_foreign_key_validation(self): "ForeignKey.validate() uses the correct database" mickey = Person.objects.using("other").create(name="Mickey") pluto = Pet.objects.using("other").create(name="Pluto", owner=mickey) self.assertIsNone(pluto.full_clean()) # Any router that accesses `model` in db_for_read() works here. @override_settings(DATABASE_ROUTERS=[AuthRouter()]) def test_foreign_key_validation_with_router(self): """ ForeignKey.validate() passes `model` to db_for_read() even if model_instance=None. """ mickey = Person.objects.create(name="Mickey") owner_field = Pet._meta.get_field("owner") self.assertEqual(owner_field.clean(mickey.pk, None), mickey.pk) def test_o2o_separation(self): "OneToOne fields are constrained to a single database" # Create a user and profile on the default database alice = User.objects.db_manager("default").create_user( "alice", "[email protected]" ) alice_profile = UserProfile.objects.using("default").create( user=alice, flavor="chocolate" ) # Create a user and profile on the other database bob = User.objects.db_manager("other").create_user("bob", "[email protected]") bob_profile = UserProfile.objects.using("other").create( user=bob, flavor="crunchy frog" ) # Retrieve related objects; queries should be database constrained alice = User.objects.using("default").get(username="alice") self.assertEqual(alice.userprofile.flavor, "chocolate") bob = User.objects.using("other").get(username="bob") self.assertEqual(bob.userprofile.flavor, "crunchy frog") # Queries work across joins self.assertEqual( list( User.objects.using("default") .filter(userprofile__flavor="chocolate") .values_list("username", flat=True) ), ["alice"], ) self.assertEqual( list( User.objects.using("other") .filter(userprofile__flavor="chocolate") .values_list("username", flat=True) ), [], ) self.assertEqual( list( User.objects.using("default") .filter(userprofile__flavor="crunchy frog") .values_list("username", flat=True) ), [], ) self.assertEqual( list( User.objects.using("other") .filter(userprofile__flavor="crunchy frog") .values_list("username", flat=True) ), ["bob"], ) # Reget the objects to clear caches alice_profile = UserProfile.objects.using("default").get(flavor="chocolate") bob_profile = UserProfile.objects.using("other").get(flavor="crunchy frog") # Retrieve related object by descriptor. Related objects should be # database-bound. self.assertEqual(alice_profile.user.username, "alice") self.assertEqual(bob_profile.user.username, "bob") def test_o2o_cross_database_protection(self): "Operations that involve sharing FK objects across databases raise an error" # Create a user and profile on the default database alice = User.objects.db_manager("default").create_user( "alice", "[email protected]" ) # Create a user and profile on the other database bob = User.objects.db_manager("other").create_user("bob", "[email protected]") # Set a one-to-one relation with an object from a different database alice_profile = UserProfile.objects.using("default").create( user=alice, flavor="chocolate" ) msg = ( 'Cannot assign "%r": the current database router prevents this ' "relation." % alice_profile ) with self.assertRaisesMessage(ValueError, msg): bob.userprofile = alice_profile # BUT! if you assign a FK object when the base object hasn't # been saved yet, you implicitly assign the database for the # base object. bob_profile = UserProfile.objects.using("other").create( user=bob, flavor="crunchy frog" ) new_bob_profile = UserProfile(flavor="spring surprise") # assigning a profile requires an explicit pk as the object isn't saved charlie = User(pk=51, username="charlie", email="[email protected]") charlie.set_unusable_password() # initially, no db assigned self.assertIsNone(new_bob_profile._state.db) self.assertIsNone(charlie._state.db) # old object comes from 'other', so the new object is set to use 'other'... new_bob_profile.user = bob charlie.userprofile = bob_profile self.assertEqual(new_bob_profile._state.db, "other") self.assertEqual(charlie._state.db, "other") # ... but it isn't saved yet self.assertEqual( list(User.objects.using("other").values_list("username", flat=True)), ["bob"], ) self.assertEqual( list(UserProfile.objects.using("other").values_list("flavor", flat=True)), ["crunchy frog"], ) # When saved (no using required), new objects goes to 'other' charlie.save() bob_profile.save() new_bob_profile.save() self.assertEqual( list(User.objects.using("default").values_list("username", flat=True)), ["alice"], ) self.assertEqual( list(User.objects.using("other").values_list("username", flat=True)), ["bob", "charlie"], ) self.assertEqual( list(UserProfile.objects.using("default").values_list("flavor", flat=True)), ["chocolate"], ) self.assertEqual( list(UserProfile.objects.using("other").values_list("flavor", flat=True)), ["crunchy frog", "spring surprise"], ) # This also works if you assign the O2O relation in the constructor denise = User.objects.db_manager("other").create_user( "denise", "[email protected]" ) denise_profile = UserProfile(flavor="tofu", user=denise) self.assertEqual(denise_profile._state.db, "other") # ... but it isn't saved yet self.assertEqual( list(UserProfile.objects.using("default").values_list("flavor", flat=True)), ["chocolate"], ) self.assertEqual( list(UserProfile.objects.using("other").values_list("flavor", flat=True)), ["crunchy frog", "spring surprise"], ) # When saved, the new profile goes to 'other' denise_profile.save() self.assertEqual( list(UserProfile.objects.using("default").values_list("flavor", flat=True)), ["chocolate"], ) self.assertEqual( list(UserProfile.objects.using("other").values_list("flavor", flat=True)), ["crunchy frog", "spring surprise", "tofu"], ) def test_generic_key_separation(self): "Generic fields are constrained to a single database" # Create a book and author on the default database pro = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) review1 = Review.objects.create(source="Python Monthly", content_object=pro) # Create a book and author on the other database dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) review2 = Review.objects.using("other").create( source="Python Weekly", content_object=dive ) review1 = Review.objects.using("default").get(source="Python Monthly") self.assertEqual(review1.content_object.title, "Pro Django") review2 = Review.objects.using("other").get(source="Python Weekly") self.assertEqual(review2.content_object.title, "Dive into Python") # Reget the objects to clear caches dive = Book.objects.using("other").get(title="Dive into Python") # Retrieve related object by descriptor. Related objects should be # database-bound. self.assertEqual( list(dive.reviews.values_list("source", flat=True)), ["Python Weekly"] ) def test_generic_key_reverse_operations(self): "Generic reverse manipulations are all constrained to a single DB" dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) temp = Book.objects.using("other").create( title="Temp", published=datetime.date(2009, 5, 4) ) review1 = Review.objects.using("other").create( source="Python Weekly", content_object=dive ) review2 = Review.objects.using("other").create( source="Python Monthly", content_object=temp ) self.assertEqual( list( Review.objects.using("default") .filter(object_id=dive.pk) .values_list("source", flat=True) ), [], ) self.assertEqual( list( Review.objects.using("other") .filter(object_id=dive.pk) .values_list("source", flat=True) ), ["Python Weekly"], ) # Add a second review dive.reviews.add(review2) self.assertEqual( list( Review.objects.using("default") .filter(object_id=dive.pk) .values_list("source", flat=True) ), [], ) self.assertEqual( list( Review.objects.using("other") .filter(object_id=dive.pk) .values_list("source", flat=True) ), ["Python Monthly", "Python Weekly"], ) # Remove the second author dive.reviews.remove(review1) self.assertEqual( list( Review.objects.using("default") .filter(object_id=dive.pk) .values_list("source", flat=True) ), [], ) self.assertEqual( list( Review.objects.using("other") .filter(object_id=dive.pk) .values_list("source", flat=True) ), ["Python Monthly"], ) # Clear all reviews dive.reviews.clear() self.assertEqual( list( Review.objects.using("default") .filter(object_id=dive.pk) .values_list("source", flat=True) ), [], ) self.assertEqual( list( Review.objects.using("other") .filter(object_id=dive.pk) .values_list("source", flat=True) ), [], ) # Create an author through the generic interface dive.reviews.create(source="Python Daily") self.assertEqual( list( Review.objects.using("default") .filter(object_id=dive.pk) .values_list("source", flat=True) ), [], ) self.assertEqual( list( Review.objects.using("other") .filter(object_id=dive.pk) .values_list("source", flat=True) ), ["Python Daily"], ) def test_generic_key_cross_database_protection(self): """ Operations that involve sharing generic key objects across databases raise an error. """ # Create a book and author on the default database pro = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) review1 = Review.objects.create(source="Python Monthly", content_object=pro) # Create a book and author on the other database dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) Review.objects.using("other").create( source="Python Weekly", content_object=dive ) # Set a foreign key with an object from a different database msg = ( 'Cannot assign "<ContentType: Multiple_Database | book>": the ' "current database router prevents this relation." ) with self.assertRaisesMessage(ValueError, msg): review1.content_object = dive # Add to a foreign key set with an object from a different database msg = ( "<Review: Python Monthly> instance isn't saved. " "Use bulk=False or save the object first." ) with self.assertRaisesMessage(ValueError, msg): with transaction.atomic(using="other"): dive.reviews.add(review1) # BUT! if you assign a FK object when the base object hasn't # been saved yet, you implicitly assign the database for the # base object. review3 = Review(source="Python Daily") # initially, no db assigned self.assertIsNone(review3._state.db) # Dive comes from 'other', so review3 is set to use 'other'... review3.content_object = dive self.assertEqual(review3._state.db, "other") # ... but it isn't saved yet self.assertEqual( list( Review.objects.using("default") .filter(object_id=pro.pk) .values_list("source", flat=True) ), ["Python Monthly"], ) self.assertEqual( list( Review.objects.using("other") .filter(object_id=dive.pk) .values_list("source", flat=True) ), ["Python Weekly"], ) # When saved, John goes to 'other' review3.save() self.assertEqual( list( Review.objects.using("default") .filter(object_id=pro.pk) .values_list("source", flat=True) ), ["Python Monthly"], ) self.assertEqual( list( Review.objects.using("other") .filter(object_id=dive.pk) .values_list("source", flat=True) ), ["Python Daily", "Python Weekly"], ) def test_generic_key_deletion(self): """ Cascaded deletions of Generic Key relations issue queries on the right database. """ dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) Review.objects.using("other").create( source="Python Weekly", content_object=dive ) # Check the initial state self.assertEqual(Book.objects.using("default").count(), 0) self.assertEqual(Review.objects.using("default").count(), 0) self.assertEqual(Book.objects.using("other").count(), 1) self.assertEqual(Review.objects.using("other").count(), 1) # Delete the Book object, which will cascade onto the pet dive.delete(using="other") self.assertEqual(Book.objects.using("default").count(), 0) self.assertEqual(Review.objects.using("default").count(), 0) # Both the pet and the person have been deleted from the right database self.assertEqual(Book.objects.using("other").count(), 0) self.assertEqual(Review.objects.using("other").count(), 0) def test_ordering(self): "get_next_by_XXX commands stick to a single database" Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) learn = Book.objects.using("other").create( title="Learning Python", published=datetime.date(2008, 7, 16) ) self.assertEqual(learn.get_next_by_published().title, "Dive into Python") self.assertEqual(dive.get_previous_by_published().title, "Learning Python") def test_raw(self): "test the raw() method across databases" dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) val = Book.objects.db_manager("other").raw( "SELECT id FROM multiple_database_book" ) self.assertQuerySetEqual(val, [dive.pk], attrgetter("pk")) val = Book.objects.raw("SELECT id FROM multiple_database_book").using("other") self.assertQuerySetEqual(val, [dive.pk], attrgetter("pk")) def test_select_related(self): """ Database assignment is retained if an object is retrieved with select_related(). """ # Create a book and author on the other database mark = Person.objects.using("other").create(name="Mark Pilgrim") Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4), editor=mark, ) # Retrieve the Person using select_related() book = ( Book.objects.using("other") .select_related("editor") .get(title="Dive into Python") ) # The editor instance should have a db state self.assertEqual(book.editor._state.db, "other") def test_subquery(self): """Make sure as_sql works with subqueries and primary/replica.""" sub = Person.objects.using("other").filter(name="fff") qs = Book.objects.filter(editor__in=sub) # When you call __str__ on the query object, it doesn't know about using # so it falls back to the default. If the subquery explicitly uses a # different database, an error should be raised. msg = ( "Subqueries aren't allowed across different databases. Force the " "inner query to be evaluated using `list(inner_query)`." ) with self.assertRaisesMessage(ValueError, msg): str(qs.query) # Evaluating the query shouldn't work, either with self.assertRaisesMessage(ValueError, msg): for obj in qs: pass def test_related_manager(self): "Related managers return managers, not querysets" mark = Person.objects.using("other").create(name="Mark Pilgrim") # extra_arg is removed by the BookManager's implementation of # create(); but the BookManager's implementation won't get called # unless edited returns a Manager, not a queryset mark.book_set.create( title="Dive into Python", published=datetime.date(2009, 5, 4), extra_arg=True, ) mark.book_set.get_or_create( title="Dive into Python", published=datetime.date(2009, 5, 4), extra_arg=True, ) mark.edited.create( title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True ) mark.edited.get_or_create( title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True ) class ConnectionRouterTestCase(SimpleTestCase): @override_settings( DATABASE_ROUTERS=[ "multiple_database.tests.TestRouter", "multiple_database.tests.WriteRouter", ] ) def test_router_init_default(self): connection_router = ConnectionRouter() self.assertEqual( [r.__class__.__name__ for r in connection_router.routers], ["TestRouter", "WriteRouter"], ) def test_router_init_arg(self): connection_router = ConnectionRouter( [ "multiple_database.tests.TestRouter", "multiple_database.tests.WriteRouter", ] ) self.assertEqual( [r.__class__.__name__ for r in connection_router.routers], ["TestRouter", "WriteRouter"], ) # Init with instances instead of strings connection_router = ConnectionRouter([TestRouter(), WriteRouter()]) self.assertEqual( [r.__class__.__name__ for r in connection_router.routers], ["TestRouter", "WriteRouter"], ) # Make the 'other' database appear to be a replica of the 'default' @override_settings(DATABASE_ROUTERS=[TestRouter()]) class RouterTestCase(TestCase): databases = {"default", "other"} def test_db_selection(self): "Querysets obey the router for db suggestions" self.assertEqual(Book.objects.db, "other") self.assertEqual(Book.objects.all().db, "other") self.assertEqual(Book.objects.using("default").db, "default") self.assertEqual(Book.objects.db_manager("default").db, "default") self.assertEqual(Book.objects.db_manager("default").all().db, "default") def test_migrate_selection(self): "Synchronization behavior is predictable" self.assertTrue(router.allow_migrate_model("default", User)) self.assertTrue(router.allow_migrate_model("default", Book)) self.assertTrue(router.allow_migrate_model("other", User)) self.assertTrue(router.allow_migrate_model("other", Book)) with override_settings(DATABASE_ROUTERS=[TestRouter(), AuthRouter()]): # Add the auth router to the chain. TestRouter is a universal # synchronizer, so it should have no effect. self.assertTrue(router.allow_migrate_model("default", User)) self.assertTrue(router.allow_migrate_model("default", Book)) self.assertTrue(router.allow_migrate_model("other", User)) self.assertTrue(router.allow_migrate_model("other", Book)) with override_settings(DATABASE_ROUTERS=[AuthRouter(), TestRouter()]): # Now check what happens if the router order is reversed. self.assertFalse(router.allow_migrate_model("default", User)) self.assertTrue(router.allow_migrate_model("default", Book)) self.assertTrue(router.allow_migrate_model("other", User)) self.assertTrue(router.allow_migrate_model("other", Book)) def test_partial_router(self): "A router can choose to implement a subset of methods" dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) # First check the baseline behavior. self.assertEqual(router.db_for_read(User), "other") self.assertEqual(router.db_for_read(Book), "other") self.assertEqual(router.db_for_write(User), "default") self.assertEqual(router.db_for_write(Book), "default") self.assertTrue(router.allow_relation(dive, dive)) self.assertTrue(router.allow_migrate_model("default", User)) self.assertTrue(router.allow_migrate_model("default", Book)) with override_settings( DATABASE_ROUTERS=[WriteRouter(), AuthRouter(), TestRouter()] ): self.assertEqual(router.db_for_read(User), "default") self.assertEqual(router.db_for_read(Book), "other") self.assertEqual(router.db_for_write(User), "writer") self.assertEqual(router.db_for_write(Book), "writer") self.assertTrue(router.allow_relation(dive, dive)) self.assertFalse(router.allow_migrate_model("default", User)) self.assertTrue(router.allow_migrate_model("default", Book)) def test_database_routing(self): marty = Person.objects.using("default").create(name="Marty Alchin") pro = Book.objects.using("default").create( title="Pro Django", published=datetime.date(2008, 12, 16), editor=marty, ) pro.authors.set([marty]) # Create a book and author on the other database Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) # An update query will be routed to the default database Book.objects.filter(title="Pro Django").update(pages=200) with self.assertRaises(Book.DoesNotExist): # By default, the get query will be directed to 'other' Book.objects.get(title="Pro Django") # But the same query issued explicitly at a database will work. pro = Book.objects.using("default").get(title="Pro Django") # The update worked. self.assertEqual(pro.pages, 200) # An update query with an explicit using clause will be routed # to the requested database. Book.objects.using("other").filter(title="Dive into Python").update(pages=300) self.assertEqual(Book.objects.get(title="Dive into Python").pages, 300) # Related object queries stick to the same database # as the original object, regardless of the router self.assertEqual( list(pro.authors.values_list("name", flat=True)), ["Marty Alchin"] ) self.assertEqual(pro.editor.name, "Marty Alchin") # get_or_create is a special case. The get needs to be targeted at # the write database in order to avoid potential transaction # consistency problems book, created = Book.objects.get_or_create(title="Pro Django") self.assertFalse(created) book, created = Book.objects.get_or_create( title="Dive Into Python", defaults={"published": datetime.date(2009, 5, 4)} ) self.assertTrue(created) # Check the head count of objects self.assertEqual(Book.objects.using("default").count(), 2) self.assertEqual(Book.objects.using("other").count(), 1) # If a database isn't specified, the read database is used self.assertEqual(Book.objects.count(), 1) # A delete query will also be routed to the default database Book.objects.filter(pages__gt=150).delete() # The default database has lost the book. self.assertEqual(Book.objects.using("default").count(), 1) self.assertEqual(Book.objects.using("other").count(), 1) def test_invalid_set_foreign_key_assignment(self): marty = Person.objects.using("default").create(name="Marty Alchin") dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4), ) # Set a foreign key set with an object from a different database msg = ( "<Book: Dive into Python> instance isn't saved. Use bulk=False or save the " "object first." ) with self.assertRaisesMessage(ValueError, msg): marty.edited.set([dive]) def test_foreign_key_cross_database_protection(self): "Foreign keys can cross databases if they two databases have a common source" # Create a book and author on the default database pro = Book.objects.using("default").create( title="Pro Django", published=datetime.date(2008, 12, 16) ) marty = Person.objects.using("default").create(name="Marty Alchin") # Create a book and author on the other database dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) mark = Person.objects.using("other").create(name="Mark Pilgrim") # Set a foreign key with an object from a different database dive.editor = marty # Database assignments of original objects haven't changed... self.assertEqual(marty._state.db, "default") self.assertEqual(pro._state.db, "default") self.assertEqual(dive._state.db, "other") self.assertEqual(mark._state.db, "other") # ... but they will when the affected object is saved. dive.save() self.assertEqual(dive._state.db, "default") # ...and the source database now has a copy of any object saved Book.objects.using("default").get(title="Dive into Python").delete() # This isn't a real primary/replica database, so restore the original from other dive = Book.objects.using("other").get(title="Dive into Python") self.assertEqual(dive._state.db, "other") # Set a foreign key set with an object from a different database marty.edited.set([pro, dive], bulk=False) # Assignment implies a save, so database assignments of original # objects have changed... self.assertEqual(marty._state.db, "default") self.assertEqual(pro._state.db, "default") self.assertEqual(dive._state.db, "default") self.assertEqual(mark._state.db, "other") # ...and the source database now has a copy of any object saved Book.objects.using("default").get(title="Dive into Python").delete() # This isn't a real primary/replica database, so restore the original from other dive = Book.objects.using("other").get(title="Dive into Python") self.assertEqual(dive._state.db, "other") # Add to a foreign key set with an object from a different database marty.edited.add(dive, bulk=False) # Add implies a save, so database assignments of original objects have # changed... self.assertEqual(marty._state.db, "default") self.assertEqual(pro._state.db, "default") self.assertEqual(dive._state.db, "default") self.assertEqual(mark._state.db, "other") # ...and the source database now has a copy of any object saved Book.objects.using("default").get(title="Dive into Python").delete() # This isn't a real primary/replica database, so restore the original from other dive = Book.objects.using("other").get(title="Dive into Python") # If you assign a FK object when the base object hasn't # been saved yet, you implicitly assign the database for the # base object. chris = Person(name="Chris Mills") html5 = Book(title="Dive into HTML5", published=datetime.date(2010, 3, 15)) # initially, no db assigned self.assertIsNone(chris._state.db) self.assertIsNone(html5._state.db) # old object comes from 'other', so the new object is set to use the # source of 'other'... self.assertEqual(dive._state.db, "other") chris.save() dive.editor = chris html5.editor = mark self.assertEqual(dive._state.db, "other") self.assertEqual(mark._state.db, "other") self.assertEqual(chris._state.db, "default") self.assertEqual(html5._state.db, "default") # This also works if you assign the FK in the constructor water = Book( title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark ) self.assertEqual(water._state.db, "default") # For the remainder of this test, create a copy of 'mark' in the # 'default' database to prevent integrity errors on backends that # don't defer constraints checks until the end of the transaction mark.save(using="default") # This moved 'mark' in the 'default' database, move it back in 'other' mark.save(using="other") self.assertEqual(mark._state.db, "other") # If you create an object through a FK relation, it will be # written to the write database, even if the original object # was on the read database cheesecake = mark.edited.create( title="Dive into Cheesecake", published=datetime.date(2010, 3, 15) ) self.assertEqual(cheesecake._state.db, "default") # Same goes for get_or_create, regardless of whether getting or creating cheesecake, created = mark.edited.get_or_create( title="Dive into Cheesecake", published=datetime.date(2010, 3, 15), ) self.assertEqual(cheesecake._state.db, "default") puddles, created = mark.edited.get_or_create( title="Dive into Puddles", published=datetime.date(2010, 3, 15) ) self.assertEqual(puddles._state.db, "default") def test_m2m_cross_database_protection(self): "M2M relations can cross databases if the database share a source" # Create books and authors on the inverse to the usual database pro = Book.objects.using("other").create( pk=1, title="Pro Django", published=datetime.date(2008, 12, 16) ) marty = Person.objects.using("other").create(pk=1, name="Marty Alchin") dive = Book.objects.using("default").create( pk=2, title="Dive into Python", published=datetime.date(2009, 5, 4) ) mark = Person.objects.using("default").create(pk=2, name="Mark Pilgrim") # Now save back onto the usual database. # This simulates primary/replica - the objects exist on both database, # but the _state.db is as it is for all other tests. pro.save(using="default") marty.save(using="default") dive.save(using="other") mark.save(using="other") # We have 2 of both types of object on both databases self.assertEqual(Book.objects.using("default").count(), 2) self.assertEqual(Book.objects.using("other").count(), 2) self.assertEqual(Person.objects.using("default").count(), 2) self.assertEqual(Person.objects.using("other").count(), 2) # Set a m2m set with an object from a different database marty.book_set.set([pro, dive]) # Database assignments don't change self.assertEqual(marty._state.db, "default") self.assertEqual(pro._state.db, "default") self.assertEqual(dive._state.db, "other") self.assertEqual(mark._state.db, "other") # All m2m relations should be saved on the default database self.assertEqual(Book.authors.through.objects.using("default").count(), 2) self.assertEqual(Book.authors.through.objects.using("other").count(), 0) # Reset relations Book.authors.through.objects.using("default").delete() # Add to an m2m with an object from a different database marty.book_set.add(dive) # Database assignments don't change self.assertEqual(marty._state.db, "default") self.assertEqual(pro._state.db, "default") self.assertEqual(dive._state.db, "other") self.assertEqual(mark._state.db, "other") # All m2m relations should be saved on the default database self.assertEqual(Book.authors.through.objects.using("default").count(), 1) self.assertEqual(Book.authors.through.objects.using("other").count(), 0) # Reset relations Book.authors.through.objects.using("default").delete() # Set a reverse m2m with an object from a different database dive.authors.set([mark, marty]) # Database assignments don't change self.assertEqual(marty._state.db, "default") self.assertEqual(pro._state.db, "default") self.assertEqual(dive._state.db, "other") self.assertEqual(mark._state.db, "other") # All m2m relations should be saved on the default database self.assertEqual(Book.authors.through.objects.using("default").count(), 2) self.assertEqual(Book.authors.through.objects.using("other").count(), 0) # Reset relations Book.authors.through.objects.using("default").delete() self.assertEqual(Book.authors.through.objects.using("default").count(), 0) self.assertEqual(Book.authors.through.objects.using("other").count(), 0) # Add to a reverse m2m with an object from a different database dive.authors.add(marty) # Database assignments don't change self.assertEqual(marty._state.db, "default") self.assertEqual(pro._state.db, "default") self.assertEqual(dive._state.db, "other") self.assertEqual(mark._state.db, "other") # All m2m relations should be saved on the default database self.assertEqual(Book.authors.through.objects.using("default").count(), 1) self.assertEqual(Book.authors.through.objects.using("other").count(), 0) # If you create an object through a M2M relation, it will be # written to the write database, even if the original object # was on the read database alice = dive.authors.create(name="Alice", pk=3) self.assertEqual(alice._state.db, "default") # Same goes for get_or_create, regardless of whether getting or creating alice, created = dive.authors.get_or_create(name="Alice") self.assertEqual(alice._state.db, "default") bob, created = dive.authors.get_or_create(name="Bob", defaults={"pk": 4}) self.assertEqual(bob._state.db, "default") def test_o2o_cross_database_protection(self): "Operations that involve sharing FK objects across databases raise an error" # Create a user and profile on the default database alice = User.objects.db_manager("default").create_user( "alice", "[email protected]" ) # Create a user and profile on the other database bob = User.objects.db_manager("other").create_user("bob", "[email protected]") # Set a one-to-one relation with an object from a different database alice_profile = UserProfile.objects.create(user=alice, flavor="chocolate") bob.userprofile = alice_profile # Database assignments of original objects haven't changed... self.assertEqual(alice._state.db, "default") self.assertEqual(alice_profile._state.db, "default") self.assertEqual(bob._state.db, "other") # ... but they will when the affected object is saved. bob.save() self.assertEqual(bob._state.db, "default") def test_generic_key_cross_database_protection(self): "Generic Key operations can span databases if they share a source" # Create a book and author on the default database pro = Book.objects.using("default").create( title="Pro Django", published=datetime.date(2008, 12, 16) ) review1 = Review.objects.using("default").create( source="Python Monthly", content_object=pro ) # Create a book and author on the other database dive = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) review2 = Review.objects.using("other").create( source="Python Weekly", content_object=dive ) # Set a generic foreign key with an object from a different database review1.content_object = dive # Database assignments of original objects haven't changed... self.assertEqual(pro._state.db, "default") self.assertEqual(review1._state.db, "default") self.assertEqual(dive._state.db, "other") self.assertEqual(review2._state.db, "other") # ... but they will when the affected object is saved. dive.save() self.assertEqual(review1._state.db, "default") self.assertEqual(dive._state.db, "default") # ...and the source database now has a copy of any object saved Book.objects.using("default").get(title="Dive into Python").delete() # This isn't a real primary/replica database, so restore the original from other dive = Book.objects.using("other").get(title="Dive into Python") self.assertEqual(dive._state.db, "other") # Add to a generic foreign key set with an object from a different database dive.reviews.add(review1) # Database assignments of original objects haven't changed... self.assertEqual(pro._state.db, "default") self.assertEqual(review1._state.db, "default") self.assertEqual(dive._state.db, "other") self.assertEqual(review2._state.db, "other") # ... but they will when the affected object is saved. dive.save() self.assertEqual(dive._state.db, "default") # ...and the source database now has a copy of any object saved Book.objects.using("default").get(title="Dive into Python").delete() # BUT! if you assign a FK object when the base object hasn't # been saved yet, you implicitly assign the database for the # base object. review3 = Review(source="Python Daily") # initially, no db assigned self.assertIsNone(review3._state.db) # Dive comes from 'other', so review3 is set to use the source of 'other'... review3.content_object = dive self.assertEqual(review3._state.db, "default") # If you create an object through a M2M relation, it will be # written to the write database, even if the original object # was on the read database dive = Book.objects.using("other").get(title="Dive into Python") nyt = dive.reviews.create(source="New York Times", content_object=dive) self.assertEqual(nyt._state.db, "default") def test_m2m_managers(self): "M2M relations are represented by managers, and can be controlled like managers" pro = Book.objects.using("other").create( pk=1, title="Pro Django", published=datetime.date(2008, 12, 16) ) marty = Person.objects.using("other").create(pk=1, name="Marty Alchin") self.assertEqual(pro.authors.db, "other") self.assertEqual(pro.authors.db_manager("default").db, "default") self.assertEqual(pro.authors.db_manager("default").all().db, "default") self.assertEqual(marty.book_set.db, "other") self.assertEqual(marty.book_set.db_manager("default").db, "default") self.assertEqual(marty.book_set.db_manager("default").all().db, "default") def test_foreign_key_managers(self): """ FK reverse relations are represented by managers, and can be controlled like managers. """ marty = Person.objects.using("other").create(pk=1, name="Marty Alchin") Book.objects.using("other").create( pk=1, title="Pro Django", published=datetime.date(2008, 12, 16), editor=marty, ) self.assertEqual(marty.edited.db, "other") self.assertEqual(marty.edited.db_manager("default").db, "default") self.assertEqual(marty.edited.db_manager("default").all().db, "default") def test_generic_key_managers(self): """ Generic key relations are represented by managers, and can be controlled like managers. """ pro = Book.objects.using("other").create( title="Pro Django", published=datetime.date(2008, 12, 16) ) Review.objects.using("other").create( source="Python Monthly", content_object=pro ) self.assertEqual(pro.reviews.db, "other") self.assertEqual(pro.reviews.db_manager("default").db, "default") self.assertEqual(pro.reviews.db_manager("default").all().db, "default") def test_subquery(self): """Make sure as_sql works with subqueries and primary/replica.""" # Create a book and author on the other database mark = Person.objects.using("other").create(name="Mark Pilgrim") Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4), editor=mark, ) sub = Person.objects.filter(name="Mark Pilgrim") qs = Book.objects.filter(editor__in=sub) # When you call __str__ on the query object, it doesn't know about using # so it falls back to the default. Don't let routing instructions # force the subquery to an incompatible database. str(qs.query) # If you evaluate the query, it should work, running on 'other' self.assertEqual(list(qs.values_list("title", flat=True)), ["Dive into Python"]) def test_deferred_models(self): mark_def = Person.objects.using("default").create(name="Mark Pilgrim") mark_other = Person.objects.using("other").create(name="Mark Pilgrim") orig_b = Book.objects.using("other").create( title="Dive into Python", published=datetime.date(2009, 5, 4), editor=mark_other, ) b = Book.objects.using("other").only("title").get(pk=orig_b.pk) self.assertEqual(b.published, datetime.date(2009, 5, 4)) b = Book.objects.using("other").only("title").get(pk=orig_b.pk) b.editor = mark_def b.save(using="default") self.assertEqual( Book.objects.using("default").get(pk=b.pk).published, datetime.date(2009, 5, 4), ) @override_settings(DATABASE_ROUTERS=[AuthRouter()]) class AuthTestCase(TestCase): databases = {"default", "other"} def test_auth_manager(self): "The methods on the auth manager obey database hints" # Create one user using default allocation policy User.objects.create_user("alice", "[email protected]") # Create another user, explicitly specifying the database User.objects.db_manager("default").create_user("bob", "[email protected]") # The second user only exists on the other database alice = User.objects.using("other").get(username="alice") self.assertEqual(alice.username, "alice") self.assertEqual(alice._state.db, "other") with self.assertRaises(User.DoesNotExist): User.objects.using("default").get(username="alice") # The second user only exists on the default database bob = User.objects.using("default").get(username="bob") self.assertEqual(bob.username, "bob") self.assertEqual(bob._state.db, "default") with self.assertRaises(User.DoesNotExist): User.objects.using("other").get(username="bob") # That is... there is one user on each database self.assertEqual(User.objects.using("default").count(), 1) self.assertEqual(User.objects.using("other").count(), 1) def test_dumpdata(self): "dumpdata honors allow_migrate restrictions on the router" User.objects.create_user("alice", "[email protected]") User.objects.db_manager("default").create_user("bob", "[email protected]") # dumping the default database doesn't try to include auth because # allow_migrate prohibits auth on default new_io = StringIO() management.call_command( "dumpdata", "auth", format="json", database="default", stdout=new_io ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "[]") # dumping the other database does include auth new_io = StringIO() management.call_command( "dumpdata", "auth", format="json", database="other", stdout=new_io ) command_output = new_io.getvalue().strip() self.assertIn('"email": "[email protected]"', command_output) class AntiPetRouter: # A router that only expresses an opinion on migrate, # passing pets to the 'other' database def allow_migrate(self, db, app_label, model_name=None, **hints): if db == "other": return model_name == "pet" else: return model_name != "pet" class FixtureTestCase(TestCase): databases = {"default", "other"} fixtures = ["multidb-common", "multidb"] @override_settings(DATABASE_ROUTERS=[AntiPetRouter()]) def test_fixture_loading(self): "Multi-db fixtures are loaded correctly" # "Pro Django" exists on the default database, but not on other database Book.objects.get(title="Pro Django") Book.objects.using("default").get(title="Pro Django") with self.assertRaises(Book.DoesNotExist): Book.objects.using("other").get(title="Pro Django") # "Dive into Python" exists on the default database, but not on other database Book.objects.using("other").get(title="Dive into Python") with self.assertRaises(Book.DoesNotExist): Book.objects.get(title="Dive into Python") with self.assertRaises(Book.DoesNotExist): Book.objects.using("default").get(title="Dive into Python") # "Definitive Guide" exists on the both databases Book.objects.get(title="The Definitive Guide to Django") Book.objects.using("default").get(title="The Definitive Guide to Django") Book.objects.using("other").get(title="The Definitive Guide to Django") @override_settings(DATABASE_ROUTERS=[AntiPetRouter()]) def test_pseudo_empty_fixtures(self): """ A fixture can contain entries, but lead to nothing in the database; this shouldn't raise an error (#14068). """ new_io = StringIO() management.call_command("loaddata", "pets", stdout=new_io, stderr=new_io) command_output = new_io.getvalue().strip() # No objects will actually be loaded self.assertEqual( command_output, "Installed 0 object(s) (of 2) from 1 fixture(s)" ) class PickleQuerySetTestCase(TestCase): databases = {"default", "other"} def test_pickling(self): for db in self.databases: Book.objects.using(db).create( title="Dive into Python", published=datetime.date(2009, 5, 4) ) qs = Book.objects.all() self.assertEqual(qs.db, pickle.loads(pickle.dumps(qs)).db) class DatabaseReceiver: """ Used in the tests for the database argument in signals (#13552) """ def __call__(self, signal, sender, **kwargs): self._database = kwargs["using"] class WriteToOtherRouter: """ A router that sends all writes to the other database. """ def db_for_write(self, model, **hints): return "other" class SignalTests(TestCase): databases = {"default", "other"} def override_router(self): return override_settings(DATABASE_ROUTERS=[WriteToOtherRouter()]) def test_database_arg_save_and_delete(self): """ The pre/post_save signal contains the correct database. """ # Make some signal receivers pre_save_receiver = DatabaseReceiver() post_save_receiver = DatabaseReceiver() pre_delete_receiver = DatabaseReceiver() post_delete_receiver = DatabaseReceiver() # Make model and connect receivers signals.pre_save.connect(sender=Person, receiver=pre_save_receiver) signals.post_save.connect(sender=Person, receiver=post_save_receiver) signals.pre_delete.connect(sender=Person, receiver=pre_delete_receiver) signals.post_delete.connect(sender=Person, receiver=post_delete_receiver) p = Person.objects.create(name="Darth Vader") # Save and test receivers got calls p.save() self.assertEqual(pre_save_receiver._database, DEFAULT_DB_ALIAS) self.assertEqual(post_save_receiver._database, DEFAULT_DB_ALIAS) # Delete, and test p.delete() self.assertEqual(pre_delete_receiver._database, DEFAULT_DB_ALIAS) self.assertEqual(post_delete_receiver._database, DEFAULT_DB_ALIAS) # Save again to a different database p.save(using="other") self.assertEqual(pre_save_receiver._database, "other") self.assertEqual(post_save_receiver._database, "other") # Delete, and test p.delete(using="other") self.assertEqual(pre_delete_receiver._database, "other") self.assertEqual(post_delete_receiver._database, "other") signals.pre_save.disconnect(sender=Person, receiver=pre_save_receiver) signals.post_save.disconnect(sender=Person, receiver=post_save_receiver) signals.pre_delete.disconnect(sender=Person, receiver=pre_delete_receiver) signals.post_delete.disconnect(sender=Person, receiver=post_delete_receiver) def test_database_arg_m2m(self): """ The m2m_changed signal has a correct database arg. """ # Make a receiver receiver = DatabaseReceiver() # Connect it signals.m2m_changed.connect(receiver=receiver) # Create the models that will be used for the tests b = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) p = Person.objects.create(name="Marty Alchin") # Create a copy of the models on the 'other' database to prevent # integrity errors on backends that don't defer constraints checks Book.objects.using("other").create( pk=b.pk, title=b.title, published=b.published ) Person.objects.using("other").create(pk=p.pk, name=p.name) # Test addition b.authors.add(p) self.assertEqual(receiver._database, DEFAULT_DB_ALIAS) with self.override_router(): b.authors.add(p) self.assertEqual(receiver._database, "other") # Test removal b.authors.remove(p) self.assertEqual(receiver._database, DEFAULT_DB_ALIAS) with self.override_router(): b.authors.remove(p) self.assertEqual(receiver._database, "other") # Test addition in reverse p.book_set.add(b) self.assertEqual(receiver._database, DEFAULT_DB_ALIAS) with self.override_router(): p.book_set.add(b) self.assertEqual(receiver._database, "other") # Test clearing b.authors.clear() self.assertEqual(receiver._database, DEFAULT_DB_ALIAS) with self.override_router(): b.authors.clear() self.assertEqual(receiver._database, "other") class AttributeErrorRouter: "A router to test the exception handling of ConnectionRouter" def db_for_read(self, model, **hints): raise AttributeError def db_for_write(self, model, **hints): raise AttributeError class RouterAttributeErrorTestCase(TestCase): databases = {"default", "other"} def override_router(self): return override_settings(DATABASE_ROUTERS=[AttributeErrorRouter()]) def test_attribute_error_read(self): "The AttributeError from AttributeErrorRouter bubbles up" b = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) with self.override_router(): with self.assertRaises(AttributeError): Book.objects.get(pk=b.pk) def test_attribute_error_save(self): "The AttributeError from AttributeErrorRouter bubbles up" dive = Book() dive.title = "Dive into Python" dive.published = datetime.date(2009, 5, 4) with self.override_router(): with self.assertRaises(AttributeError): dive.save() def test_attribute_error_delete(self): "The AttributeError from AttributeErrorRouter bubbles up" b = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) p = Person.objects.create(name="Marty Alchin") b.authors.set([p]) b.editor = p with self.override_router(): with self.assertRaises(AttributeError): b.delete() def test_attribute_error_m2m(self): "The AttributeError from AttributeErrorRouter bubbles up" b = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) p = Person.objects.create(name="Marty Alchin") with self.override_router(): with self.assertRaises(AttributeError): b.authors.set([p]) class ModelMetaRouter: "A router to ensure model arguments are real model classes" def db_for_write(self, model, **hints): if not hasattr(model, "_meta"): raise ValueError @override_settings(DATABASE_ROUTERS=[ModelMetaRouter()]) class RouterModelArgumentTestCase(TestCase): databases = {"default", "other"} def test_m2m_collection(self): b = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) p = Person.objects.create(name="Marty Alchin") # test add b.authors.add(p) # test remove b.authors.remove(p) # test clear b.authors.clear() # test setattr b.authors.set([p]) # test M2M collection b.delete() def test_foreignkey_collection(self): person = Person.objects.create(name="Bob") Pet.objects.create(owner=person, name="Wart") # test related FK collection person.delete() class SyncOnlyDefaultDatabaseRouter: def allow_migrate(self, db, app_label, **hints): return db == DEFAULT_DB_ALIAS class MigrateTestCase(TestCase): # Limit memory usage when calling 'migrate'. available_apps = [ "multiple_database", "django.contrib.auth", "django.contrib.contenttypes", ] databases = {"default", "other"} def test_migrate_to_other_database(self): """Regression test for #16039: migrate with --database option.""" cts = ContentType.objects.using("other").filter(app_label="multiple_database") count = cts.count() self.assertGreater(count, 0) cts.delete() management.call_command( "migrate", verbosity=0, interactive=False, database="other" ) self.assertEqual(cts.count(), count) def test_migrate_to_other_database_with_router(self): """Regression test for #16039: migrate with --database option.""" cts = ContentType.objects.using("other").filter(app_label="multiple_database") cts.delete() with override_settings(DATABASE_ROUTERS=[SyncOnlyDefaultDatabaseRouter()]): management.call_command( "migrate", verbosity=0, interactive=False, database="other" ) self.assertEqual(cts.count(), 0) class RouterUsed(Exception): WRITE = "write" def __init__(self, mode, model, hints): self.mode = mode self.model = model self.hints = hints class RouteForWriteTestCase(TestCase): databases = {"default", "other"} class WriteCheckRouter: def db_for_write(self, model, **hints): raise RouterUsed(mode=RouterUsed.WRITE, model=model, hints=hints) def override_router(self): return override_settings( DATABASE_ROUTERS=[RouteForWriteTestCase.WriteCheckRouter()] ) def test_fk_delete(self): owner = Person.objects.create(name="Someone") pet = Pet.objects.create(name="fido", owner=owner) with self.assertRaises(RouterUsed) as cm: with self.override_router(): pet.owner.delete() e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Person) self.assertEqual(e.hints, {"instance": owner}) def test_reverse_fk_delete(self): owner = Person.objects.create(name="Someone") to_del_qs = owner.pet_set.all() with self.assertRaises(RouterUsed) as cm: with self.override_router(): to_del_qs.delete() e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Pet) self.assertEqual(e.hints, {"instance": owner}) def test_reverse_fk_get_or_create(self): owner = Person.objects.create(name="Someone") with self.assertRaises(RouterUsed) as cm: with self.override_router(): owner.pet_set.get_or_create(name="fido") e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Pet) self.assertEqual(e.hints, {"instance": owner}) def test_reverse_fk_update(self): owner = Person.objects.create(name="Someone") Pet.objects.create(name="fido", owner=owner) with self.assertRaises(RouterUsed) as cm: with self.override_router(): owner.pet_set.update(name="max") e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Pet) self.assertEqual(e.hints, {"instance": owner}) def test_m2m_add(self): auth = Person.objects.create(name="Someone") book = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) with self.assertRaises(RouterUsed) as cm: with self.override_router(): book.authors.add(auth) e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Book.authors.through) self.assertEqual(e.hints, {"instance": book}) def test_m2m_clear(self): auth = Person.objects.create(name="Someone") book = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) book.authors.add(auth) with self.assertRaises(RouterUsed) as cm: with self.override_router(): book.authors.clear() e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Book.authors.through) self.assertEqual(e.hints, {"instance": book}) def test_m2m_delete(self): auth = Person.objects.create(name="Someone") book = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) book.authors.add(auth) with self.assertRaises(RouterUsed) as cm: with self.override_router(): book.authors.all().delete() e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Person) self.assertEqual(e.hints, {"instance": book}) def test_m2m_get_or_create(self): Person.objects.create(name="Someone") book = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) with self.assertRaises(RouterUsed) as cm: with self.override_router(): book.authors.get_or_create(name="Someone else") e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Book) self.assertEqual(e.hints, {"instance": book}) def test_m2m_remove(self): auth = Person.objects.create(name="Someone") book = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) book.authors.add(auth) with self.assertRaises(RouterUsed) as cm: with self.override_router(): book.authors.remove(auth) e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Book.authors.through) self.assertEqual(e.hints, {"instance": book}) def test_m2m_update(self): auth = Person.objects.create(name="Someone") book = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) book.authors.add(auth) with self.assertRaises(RouterUsed) as cm: with self.override_router(): book.authors.update(name="Different") e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Person) self.assertEqual(e.hints, {"instance": book}) def test_reverse_m2m_add(self): auth = Person.objects.create(name="Someone") book = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) with self.assertRaises(RouterUsed) as cm: with self.override_router(): auth.book_set.add(book) e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Book.authors.through) self.assertEqual(e.hints, {"instance": auth}) def test_reverse_m2m_clear(self): auth = Person.objects.create(name="Someone") book = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) book.authors.add(auth) with self.assertRaises(RouterUsed) as cm: with self.override_router(): auth.book_set.clear() e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Book.authors.through) self.assertEqual(e.hints, {"instance": auth}) def test_reverse_m2m_delete(self): auth = Person.objects.create(name="Someone") book = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) book.authors.add(auth) with self.assertRaises(RouterUsed) as cm: with self.override_router(): auth.book_set.all().delete() e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Book) self.assertEqual(e.hints, {"instance": auth}) def test_reverse_m2m_get_or_create(self): auth = Person.objects.create(name="Someone") Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) with self.assertRaises(RouterUsed) as cm: with self.override_router(): auth.book_set.get_or_create( title="New Book", published=datetime.datetime.now() ) e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Person) self.assertEqual(e.hints, {"instance": auth}) def test_reverse_m2m_remove(self): auth = Person.objects.create(name="Someone") book = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) book.authors.add(auth) with self.assertRaises(RouterUsed) as cm: with self.override_router(): auth.book_set.remove(book) e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Book.authors.through) self.assertEqual(e.hints, {"instance": auth}) def test_reverse_m2m_update(self): auth = Person.objects.create(name="Someone") book = Book.objects.create( title="Pro Django", published=datetime.date(2008, 12, 16) ) book.authors.add(auth) with self.assertRaises(RouterUsed) as cm: with self.override_router(): auth.book_set.update(title="Different") e = cm.exception self.assertEqual(e.mode, RouterUsed.WRITE) self.assertEqual(e.model, Book) self.assertEqual(e.hints, {"instance": auth}) class NoRelationRouter: """Disallow all relations.""" def allow_relation(self, obj1, obj2, **hints): return False @override_settings(DATABASE_ROUTERS=[NoRelationRouter()]) class RelationAssignmentTests(SimpleTestCase): """allow_relation() is called with unsaved model instances.""" databases = {"default", "other"} router_prevents_msg = "the current database router prevents this relation" def test_foreign_key_relation(self): person = Person(name="Someone") pet = Pet() with self.assertRaisesMessage(ValueError, self.router_prevents_msg): pet.owner = person def test_reverse_one_to_one_relation(self): user = User(username="Someone", password="fake_hash") profile = UserProfile() with self.assertRaisesMessage(ValueError, self.router_prevents_msg): user.userprofile = profile
3ded6c5f81cbe55f44b6d99ae0419ebd96b6ea351f91c5e418bcf8d4a4f62478
import os from django.contrib.contenttypes.models import ContentType from django.test import TestCase, override_settings from django.utils import translation @override_settings( USE_I18N=True, LOCALE_PATHS=[ os.path.join(os.path.dirname(__file__), "locale"), ], LANGUAGE_CODE="en", LANGUAGES=[ ("en", "English"), ("fr", "French"), ], ) class ContentTypeTests(TestCase): def test_verbose_name(self): company_type = ContentType.objects.get(app_label="i18n", model="company") with translation.override("en"): self.assertEqual(str(company_type), "I18N | Company") with translation.override("fr"): self.assertEqual(str(company_type), "I18N | Société")
62d24c3b81042eef18846b8d22a90a1a56851aaf6d81e28410cda23e0cb4ea80
# Django documentation build configuration file, created by # sphinx-quickstart on Thu Mar 27 09:06:53 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't picklable (module imports are okay, they're removed automatically). # # All configuration values have a default; values that are commented out # serve to show the default. import sys from os.path import abspath, dirname, join # Workaround for sphinx-build recursion limit overflow: # pickle.dump(doctree, f, pickle.HIGHEST_PROTOCOL) # RuntimeError: maximum recursion depth exceeded while pickling an object # # Python's default allowed recursion depth is 1000 but this isn't enough for # building docs/ref/settings.txt sometimes. # https://groups.google.com/g/sphinx-dev/c/MtRf64eGtv4/discussion sys.setrecursionlimit(2000) # Make sure we get the version of this copy of Django sys.path.insert(1, dirname(dirname(abspath(__file__)))) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.append(abspath(join(dirname(__file__), "_ext"))) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = "4.5.0" # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "djangodocs", "sphinx.ext.extlinks", "sphinx.ext.intersphinx", "sphinx.ext.viewcode", "sphinx.ext.autosectionlabel", ] # AutosectionLabel settings. # Uses a <page>:<label> schema which doesn't work for duplicate sub-section # labels, so set max depth. autosectionlabel_prefix_document = True autosectionlabel_maxdepth = 2 # Linkcheck settings. linkcheck_ignore = [ # Special-use addresses and domain names. (RFC 6761/6890) r"^https?://(?:127\.0\.0\.1|\[::1\])(?::\d+)?/", r"^https?://(?:[^/\.]+\.)*example\.(?:com|net|org)(?::\d+)?/", r"^https?://(?:[^/\.]+\.)*(?:example|invalid|localhost|test)(?::\d+)?/", # Pages that are inaccessible because they require authentication. r"^https://github\.com/[^/]+/[^/]+/fork", r"^https://code\.djangoproject\.com/github/login", r"^https://code\.djangoproject\.com/newticket", r"^https://(?:code|www)\.djangoproject\.com/admin/", r"^https://www\.djangoproject\.com/community/add/blogs/", r"^https://www\.google\.com/webmasters/tools/ping", r"^https://search\.google\.com/search-console/welcome", # Fragments used to dynamically switch content or populate fields. r"^https://web\.libera\.chat/#", r"^https://github\.com/[^#]+#L\d+-L\d+$", r"^https://help\.apple\.com/itc/podcasts_connect/#/itc", # Anchors on certain pages with missing a[name] attributes. r"^https://tools\.ietf\.org/html/rfc1123\.html#section-", ] # Spelling check needs an additional module that is not installed by default. # Add it only if spelling check is requested so docs can be generated without it. if "spelling" in sys.argv: extensions.append("sphinxcontrib.spelling") # Spelling language. spelling_lang = "en_US" # Location of word list. spelling_word_list_filename = "spelling_wordlist" spelling_warning = True # Add any paths that contain templates here, relative to this directory. # templates_path = [] # The suffix of source filenames. source_suffix = ".txt" # The encoding of source files. # source_encoding = 'utf-8-sig' # The root toctree document. root_doc = "contents" # Disable auto-created table of contents entries for all domain objects (e.g. # functions, classes, attributes, etc.) in Sphinx 5.2+. toc_object_entries = False # General substitutions. project = "Django" copyright = "Django Software Foundation and contributors" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "5.0" # The full version, including alpha/beta/rc tags. try: from django import VERSION, get_version except ImportError: release = version else: def django_release(): pep440ver = get_version() if VERSION[3:5] == ("alpha", 0) and "dev" not in pep440ver: return pep440ver + ".dev" return pep440ver release = django_release() # The "development version" of Django django_next_version = "5.0" extlinks = { "bpo": ("https://bugs.python.org/issue?@action=redirect&bpo=%s", "bpo-%s"), "commit": ("https://github.com/django/django/commit/%s", "%s"), "cve": ("https://nvd.nist.gov/vuln/detail/CVE-%s", "CVE-%s"), # A file or directory. GitHub redirects from blob to tree if needed. "source": ("https://github.com/django/django/blob/main/%s", "%s"), "ticket": ("https://code.djangoproject.com/ticket/%s", "#%s"), } # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # Location for .po/.mo translation files used when language is set locale_dirs = ["locale/"] # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = "%B %d, %Y" # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build", "_theme", "requirements.txt"] # The reST default role (used for this markup: `text`) to use for all documents. default_role = "default-role-error" # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = False # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "trac" # Links to Python's docs should reference the most recent version of the 3.x # branch, which is located at this URL. intersphinx_mapping = { "python": ("https://docs.python.org/3/", None), "sphinx": ("https://www.sphinx-doc.org/en/master/", None), "psycopg": ("https://www.psycopg.org/psycopg3/docs/", None), } # Python's docs don't change every week. intersphinx_cache_limit = 90 # days # The 'versionadded' and 'versionchanged' directives are overridden. suppress_warnings = ["app.add_directive"] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "djangodocs" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ["_theme"] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = "%b %d, %Y" # Content template for the index page. # html_index = '' # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "Djangodoc" modindex_common_prefix = ["django."] # Appended to every page rst_epilog = """ .. |django-users| replace:: :ref:`django-users <django-users-mailing-list>` .. |django-developers| replace:: :ref:`django-developers <django-developers-mailing-list>` .. |django-announce| replace:: :ref:`django-announce <django-announce-mailing-list>` .. |django-updates| replace:: :ref:`django-updates <django-updates-mailing-list>` """ # NOQA # -- Options for LaTeX output -------------------------------------------------- # Use XeLaTeX for Unicode support. latex_engine = "xelatex" latex_use_xindy = False # Set font for CJK and fallbacks for unicode characters. latex_elements = { "fontpkg": r""" \setmainfont{Symbola} """, "preamble": r""" \usepackage{newunicodechar} \usepackage[UTF8]{ctex} \newunicodechar{π}{\ensuremath{\pi}} \newunicodechar{≤}{\ensuremath{\le}} \newunicodechar{≥}{\ensuremath{\ge}} \newunicodechar{♥}{\ensuremath{\heartsuit}} \newunicodechar{…}{\ensuremath{\ldots}} """, } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). # latex_documents = [] latex_documents = [ ( "contents", "django.tex", "Django Documentation", "Django Software Foundation", "manual", ), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ( "ref/django-admin", "django-admin", "Utility script for the Django web framework", ["Django Software Foundation"], 1, ) ] # -- Options for Texinfo output ------------------------------------------------ # List of tuples (startdocname, targetname, title, author, dir_entry, # description, category, toctree_only) texinfo_documents = [ ( root_doc, "django", "", "", "Django", "Documentation of the Django framework", "Web development", False, ) ] # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = "Django Software Foundation" epub_publisher = "Django Software Foundation" epub_copyright = copyright # The basename for the epub file. It defaults to the project name. # epub_basename = 'Django' # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. epub_theme = "djangodocs-epub" # The language of the text. It defaults to the language option # or en if the language is not set. # epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. # epub_scheme = '' # The unique identifier of the text. This can be an ISBN number # or the project homepage. # epub_identifier = '' # A unique identification for the text. # epub_uid = '' # A tuple containing the cover image and cover page html template filenames. epub_cover = ("", "epub-cover.html") # A sequence of (type, uri, title) tuples for the guide element of content.opf. # epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_pre_files = [] # HTML files that should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_post_files = [] # A list of files that should not be packed into the epub file. # epub_exclude_files = [] # The depth of the table of contents in toc.ncx. # epub_tocdepth = 3 # Allow duplicate toc entries. # epub_tocdup = True # Choose between 'default' and 'includehidden'. # epub_tocscope = 'default' # Fix unsupported image types using the PIL. # epub_fix_images = False # Scale large images. # epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. # epub_show_urls = 'inline' # If false, no index is generated. # epub_use_index = True
d491b83aa66aa4a5974b35008efb8438d8d6b5029b10ce209149860dae26d617
""" HTML Widget classes """ import copy import datetime import warnings from collections import defaultdict from graphlib import CycleError, TopologicalSorter from itertools import chain from django.forms.utils import to_current_timezone from django.templatetags.static import static from django.utils import formats 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.regex_helper import _lazy_re_compile from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ from .renderers import get_default_renderer __all__ = ( "Media", "MediaDefiningClass", "Widget", "TextInput", "NumberInput", "EmailInput", "URLInput", "PasswordInput", "HiddenInput", "MultipleHiddenInput", "FileInput", "ClearableFileInput", "Textarea", "DateInput", "DateTimeInput", "TimeInput", "CheckboxInput", "Select", "NullBooleanSelect", "SelectMultiple", "RadioSelect", "CheckboxSelectMultiple", "MultiWidget", "SplitDateTimeWidget", "SplitHiddenDateTimeWidget", "SelectDateWidget", ) MEDIA_TYPES = ("css", "js") class MediaOrderConflictWarning(RuntimeWarning): pass @html_safe class Media: def __init__(self, media=None, css=None, js=None): if media is not None: css = getattr(media, "css", {}) js = getattr(media, "js", []) else: if css is None: css = {} if js is None: js = [] self._css_lists = [css] self._js_lists = [js] def __repr__(self): return "Media(css=%r, js=%r)" % (self._css, self._js) def __str__(self): return self.render() @property def _css(self): 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): 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 ) ) ) def render_js(self): return [ path.__html__() if hasattr(path, "__html__") else format_html('<script src="{}"></script>', self.absolute_path(path)) for path in self._js ] def render_css(self): # To keep rendering order consistent, we can't just iterate over items(). # We need to sort the keys, and iterate over the sorted list. media = sorted(self._css) return chain.from_iterable( [ path.__html__() if hasattr(path, "__html__") else format_html( '<link href="{}" media="{}" rel="stylesheet">', self.absolute_path(path), medium, ) for path in self._css[medium] ] for medium in media ) def absolute_path(self, path): """ Given a relative or absolute path to a static asset, return an absolute path. An absolute path will be returned unchanged while a relative path will be passed to django.templatetags.static.static(). """ if path.startswith(("http://", "https://", "/")): return path return static(path) def __getitem__(self, name): """Return a Media object that only contains media of the given type.""" if name in MEDIA_TYPES: return Media(**{str(name): getattr(self, "_" + name)}) raise KeyError('Unknown media type "%s"' % name) @staticmethod def merge(*lists): """ 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. """ ts = TopologicalSorter() for head, *tail in filter(None, lists): ts.add(head) # Ensure that the first items are included. for item in tail: if head != item: # Avoid circular dependency to self. ts.add(item, head) head = item try: return list(ts.static_order()) except CycleError: warnings.warn( "Detected duplicate Media files in an opposite order: {}".format( ", ".join(repr(list_) for list_ in lists) ), MediaOrderConflictWarning, ) return list(dict.fromkeys(chain.from_iterable(filter(None, lists)))) def __add__(self, other): combined = Media() combined._css_lists = self._css_lists[:] combined._js_lists = self._js_lists[:] for item in other._css_lists: if item and item not in self._css_lists: combined._css_lists.append(item) for item in other._js_lists: if item and item not in self._js_lists: combined._js_lists.append(item) return combined def media_property(cls): def _media(self): # Get the media property of the superclass, if it exists sup_cls = super(cls, self) try: base = sup_cls.media except AttributeError: base = Media() # Get the media definition for this class definition = getattr(cls, "Media", None) if definition: extend = getattr(definition, "extend", True) if extend: if extend is True: m = base else: m = Media() for medium in extend: m += base[medium] return m + Media(definition) return Media(definition) return base return property(_media) class MediaDefiningClass(type): """ Metaclass for classes that can have media definitions. """ def __new__(mcs, name, bases, attrs): new_class = super().__new__(mcs, name, bases, attrs) if "media" not in attrs: new_class.media = media_property(new_class) return new_class class Widget(metaclass=MediaDefiningClass): needs_multipart_form = False # Determines does this widget need multipart form is_localized = False is_required = False supports_microseconds = True use_fieldset = False def __init__(self, attrs=None): self.attrs = {} if attrs is None else attrs.copy() def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() memo[id(self)] = obj return obj @property def is_hidden(self): return self.input_type == "hidden" if hasattr(self, "input_type") else False def subwidgets(self, name, value, attrs=None): context = self.get_context(name, value, attrs) yield context["widget"] def format_value(self, value): """ Return a value as it should appear when rendered in a template. """ if value == "" or value is None: return None if self.is_localized: return formats.localize_input(value) return str(value) def get_context(self, name, value, attrs): return { "widget": { "name": name, "is_hidden": self.is_hidden, "required": self.is_required, "value": self.format_value(value), "attrs": self.build_attrs(self.attrs, attrs), "template_name": self.template_name, }, } def render(self, name, value, attrs=None, renderer=None): """Render the widget as an HTML string.""" context = self.get_context(name, value, attrs) return self._render(self.template_name, context, renderer) def _render(self, template_name, context, renderer=None): if renderer is None: renderer = get_default_renderer() return mark_safe(renderer.render(template_name, context)) def build_attrs(self, base_attrs, extra_attrs=None): """Build an attribute dictionary.""" return {**base_attrs, **(extra_attrs or {})} def value_from_datadict(self, data, files, name): """ Given a dictionary of data and this widget's name, return the value of this widget or None if it's not provided. """ return data.get(name) def value_omitted_from_data(self, data, files, name): return name not in data def id_for_label(self, id_): """ Return the HTML ID attribute of this Widget for use by a <label>, given the ID of the field. Return an empty string if no ID is available. This hook is necessary because some widgets have multiple HTML elements and, thus, multiple IDs. In that case, this method should return an ID value that corresponds to the first ID in the widget's tags. """ return id_ def use_required_attribute(self, initial): return not self.is_hidden class Input(Widget): """ Base class for all <input> widgets. """ input_type = None # Subclasses must define this. template_name = "django/forms/widgets/input.html" def __init__(self, attrs=None): if attrs is not None: attrs = attrs.copy() self.input_type = attrs.pop("type", self.input_type) super().__init__(attrs) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context["widget"]["type"] = self.input_type return context class TextInput(Input): input_type = "text" template_name = "django/forms/widgets/text.html" class NumberInput(Input): input_type = "number" template_name = "django/forms/widgets/number.html" class EmailInput(Input): input_type = "email" template_name = "django/forms/widgets/email.html" class URLInput(Input): input_type = "url" template_name = "django/forms/widgets/url.html" class PasswordInput(Input): input_type = "password" template_name = "django/forms/widgets/password.html" def __init__(self, attrs=None, render_value=False): super().__init__(attrs) self.render_value = render_value def get_context(self, name, value, attrs): if not self.render_value: value = None return super().get_context(name, value, attrs) class HiddenInput(Input): input_type = "hidden" template_name = "django/forms/widgets/hidden.html" class MultipleHiddenInput(HiddenInput): """ Handle <input type="hidden"> for fields that have a list of values. """ template_name = "django/forms/widgets/multiple_hidden.html" def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) final_attrs = context["widget"]["attrs"] id_ = context["widget"]["attrs"].get("id") subwidgets = [] for index, value_ in enumerate(context["widget"]["value"]): widget_attrs = final_attrs.copy() if id_: # An ID attribute was given. Add a numeric index as a suffix # so that the inputs don't all have the same ID attribute. widget_attrs["id"] = "%s_%s" % (id_, index) widget = HiddenInput() widget.is_required = self.is_required subwidgets.append(widget.get_context(name, value_, widget_attrs)["widget"]) context["widget"]["subwidgets"] = subwidgets return context def value_from_datadict(self, data, files, name): try: getter = data.getlist except AttributeError: getter = data.get return getter(name) def format_value(self, value): return [] if value is None else value class FileInput(Input): input_type = "file" needs_multipart_form = True template_name = "django/forms/widgets/file.html" def format_value(self, value): """File input never renders a value.""" return def value_from_datadict(self, data, files, name): "File widgets take data from FILES, not POST" return files.get(name) def value_omitted_from_data(self, data, files, name): return name not in files def use_required_attribute(self, initial): return super().use_required_attribute(initial) and not initial FILE_INPUT_CONTRADICTION = object() class ClearableFileInput(FileInput): clear_checkbox_label = _("Clear") initial_text = _("Currently") input_text = _("Change") template_name = "django/forms/widgets/clearable_file_input.html" def clear_checkbox_name(self, name): """ Given the name of the file input, return the name of the clear checkbox input. """ return name + "-clear" def clear_checkbox_id(self, name): """ Given the name of the clear checkbox input, return the HTML id for it. """ return name + "_id" def is_initial(self, value): """ Return whether value is considered to be initial value. """ return bool(value and getattr(value, "url", False)) def format_value(self, value): """ Return the file object if it has a defined url attribute. """ if self.is_initial(value): return value def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) checkbox_name = self.clear_checkbox_name(name) checkbox_id = self.clear_checkbox_id(checkbox_name) context["widget"].update( { "checkbox_name": checkbox_name, "checkbox_id": checkbox_id, "is_initial": self.is_initial(value), "input_text": self.input_text, "initial_text": self.initial_text, "clear_checkbox_label": self.clear_checkbox_label, } ) context["widget"]["attrs"].setdefault("disabled", False) return context def value_from_datadict(self, data, files, name): upload = super().value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name) ): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload def value_omitted_from_data(self, data, files, name): return ( super().value_omitted_from_data(data, files, name) and self.clear_checkbox_name(name) not in data ) class Textarea(Widget): template_name = "django/forms/widgets/textarea.html" def __init__(self, attrs=None): # Use slightly better defaults than HTML's 20x2 box default_attrs = {"cols": "40", "rows": "10"} if attrs: default_attrs.update(attrs) super().__init__(default_attrs) class DateTimeBaseInput(TextInput): format_key = "" supports_microseconds = False def __init__(self, attrs=None, format=None): super().__init__(attrs) self.format = format or None def format_value(self, value): return formats.localize_input( value, self.format or formats.get_format(self.format_key)[0] ) class DateInput(DateTimeBaseInput): format_key = "DATE_INPUT_FORMATS" template_name = "django/forms/widgets/date.html" class DateTimeInput(DateTimeBaseInput): format_key = "DATETIME_INPUT_FORMATS" template_name = "django/forms/widgets/datetime.html" class TimeInput(DateTimeBaseInput): format_key = "TIME_INPUT_FORMATS" template_name = "django/forms/widgets/time.html" # Defined at module level so that CheckboxInput is picklable (#17976) def boolean_check(v): return not (v is False or v is None or v == "") class CheckboxInput(Input): input_type = "checkbox" template_name = "django/forms/widgets/checkbox.html" def __init__(self, attrs=None, check_test=None): super().__init__(attrs) # check_test is a callable that takes a value and returns True # if the checkbox should be checked for that value. self.check_test = boolean_check if check_test is None else check_test def format_value(self, value): """Only return the 'value' attribute if value isn't empty.""" if value is True or value is False or value is None or value == "": return return str(value) def get_context(self, name, value, attrs): if self.check_test(value): attrs = {**(attrs or {}), "checked": True} return super().get_context(name, value, attrs) def value_from_datadict(self, data, files, name): if name not in data: # A missing value means False because HTML form submission does not # send results for unselected checkboxes. return False value = data.get(name) # Translate true and false strings to boolean values. values = {"true": True, "false": False} if isinstance(value, str): value = values.get(value.lower(), value) return bool(value) def value_omitted_from_data(self, data, files, name): # HTML checkboxes don't appear in POST data if not checked, so it's # never known if the value is actually omitted. return False class ChoiceWidget(Widget): allow_multiple_selected = False input_type = None template_name = None option_template_name = None add_id_index = True checked_attribute = {"checked": True} option_inherits_attrs = True def __init__(self, attrs=None, choices=()): super().__init__(attrs) # choices can be any iterable, but we may need to render this widget # multiple times. Thus, collapse it into a list so it can be consumed # more than once. self.choices = list(choices) def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() obj.choices = copy.copy(self.choices) memo[id(self)] = obj return obj def subwidgets(self, name, value, attrs=None): """ Yield all "subwidgets" of this widget. Used to enable iterating options from a BoundField for choice widgets. """ value = self.format_value(value) yield from self.options(name, value, attrs) def options(self, name, value, attrs=None): """Yield a flat list of options for this widget.""" for group in self.optgroups(name, value, attrs): yield from group[1] def optgroups(self, name, value, attrs=None): """Return a list of optgroups for this widget.""" groups = [] has_selected = False for index, (option_value, option_label) in enumerate(self.choices): if option_value is None: option_value = "" subgroup = [] if isinstance(option_label, (list, tuple)): group_name = option_value subindex = 0 choices = option_label else: group_name = None subindex = None choices = [(option_value, option_label)] groups.append((group_name, subgroup, index)) for subvalue, sublabel in choices: selected = (not has_selected or self.allow_multiple_selected) and str( subvalue ) in value has_selected |= selected subgroup.append( self.create_option( name, subvalue, sublabel, selected, index, subindex=subindex, attrs=attrs, ) ) if subindex is not None: subindex += 1 return groups def create_option( self, name, value, label, selected, index, subindex=None, attrs=None ): index = str(index) if subindex is None else "%s_%s" % (index, subindex) option_attrs = ( self.build_attrs(self.attrs, attrs) if self.option_inherits_attrs else {} ) if selected: option_attrs.update(self.checked_attribute) if "id" in option_attrs: option_attrs["id"] = self.id_for_label(option_attrs["id"], index) return { "name": name, "value": value, "label": label, "selected": selected, "index": index, "attrs": option_attrs, "type": self.input_type, "template_name": self.option_template_name, "wrap_label": True, } def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context["widget"]["optgroups"] = self.optgroups( name, context["widget"]["value"], attrs ) return context def id_for_label(self, id_, index="0"): """ Use an incremented id for each option where the main widget references the zero index. """ if id_ and self.add_id_index: id_ = "%s_%s" % (id_, index) return id_ def value_from_datadict(self, data, files, name): getter = data.get if self.allow_multiple_selected: try: getter = data.getlist except AttributeError: pass return getter(name) def format_value(self, value): """Return selected values as a list.""" if value is None and self.allow_multiple_selected: return [] if not isinstance(value, (tuple, list)): value = [value] return [str(v) if v is not None else "" for v in value] class Select(ChoiceWidget): input_type = "select" template_name = "django/forms/widgets/select.html" option_template_name = "django/forms/widgets/select_option.html" add_id_index = False checked_attribute = {"selected": True} option_inherits_attrs = False def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) if self.allow_multiple_selected: context["widget"]["attrs"]["multiple"] = True return context @staticmethod def _choice_has_empty_value(choice): """Return True if the choice's value is empty string or None.""" value, _ = choice return value is None or value == "" def use_required_attribute(self, initial): """ Don't render 'required' if the first <option> has a value, as that's invalid HTML. """ use_required_attribute = super().use_required_attribute(initial) # 'required' is always okay for <select multiple>. if self.allow_multiple_selected: return use_required_attribute first_choice = next(iter(self.choices), None) return ( use_required_attribute and first_choice is not None and self._choice_has_empty_value(first_choice) ) class NullBooleanSelect(Select): """ A Select Widget intended to be used with NullBooleanField. """ def __init__(self, attrs=None): choices = ( ("unknown", _("Unknown")), ("true", _("Yes")), ("false", _("No")), ) super().__init__(attrs, choices) def format_value(self, value): try: return { True: "true", False: "false", "true": "true", "false": "false", # For backwards compatibility with Django < 2.2. "2": "true", "3": "false", }[value] except KeyError: return "unknown" def value_from_datadict(self, data, files, name): value = data.get(name) return { True: True, "True": True, "False": False, False: False, "true": True, "false": False, # For backwards compatibility with Django < 2.2. "2": True, "3": False, }.get(value) class SelectMultiple(Select): allow_multiple_selected = True def value_from_datadict(self, data, files, name): try: getter = data.getlist except AttributeError: getter = data.get return getter(name) def value_omitted_from_data(self, data, files, name): # An unselected <select multiple> doesn't appear in POST data, so it's # never known if the value is actually omitted. return False class RadioSelect(ChoiceWidget): input_type = "radio" template_name = "django/forms/widgets/radio.html" option_template_name = "django/forms/widgets/radio_option.html" use_fieldset = True def id_for_label(self, id_, index=None): """ Don't include for="field_0" in <label> to improve accessibility when using a screen reader, in addition clicking such a label would toggle the first input. """ if index is None: return "" return super().id_for_label(id_, index) class CheckboxSelectMultiple(RadioSelect): allow_multiple_selected = True input_type = "checkbox" template_name = "django/forms/widgets/checkbox_select.html" option_template_name = "django/forms/widgets/checkbox_option.html" def use_required_attribute(self, initial): # Don't use the 'required' attribute because browser validation would # require all checkboxes to be checked instead of at least one. return False def value_omitted_from_data(self, data, files, name): # HTML checkboxes don't appear in POST data if not checked, so it's # never known if the value is actually omitted. return False class MultiWidget(Widget): """ A widget that is composed of multiple widgets. In addition to the values added by Widget.get_context(), this widget adds a list of subwidgets to the context as widget['subwidgets']. These can be looped over and rendered like normal widgets. You'll probably want to use this class with MultiValueField. """ template_name = "django/forms/widgets/multiwidget.html" use_fieldset = True def __init__(self, widgets, attrs=None): if isinstance(widgets, dict): self.widgets_names = [("_%s" % name) if name else "" for name in widgets] widgets = widgets.values() else: self.widgets_names = ["_%s" % i for i in range(len(widgets))] self.widgets = [w() if isinstance(w, type) else w for w in widgets] super().__init__(attrs) @property def is_hidden(self): return all(w.is_hidden for w in self.widgets) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) if self.is_localized: for widget in self.widgets: widget.is_localized = self.is_localized # value is a list/tuple of values, each corresponding to a widget # in self.widgets. if not isinstance(value, (list, tuple)): value = self.decompress(value) final_attrs = context["widget"]["attrs"] input_type = final_attrs.pop("type", None) id_ = final_attrs.get("id") subwidgets = [] for i, (widget_name, widget) in enumerate( zip(self.widgets_names, self.widgets) ): if input_type is not None: widget.input_type = input_type widget_name = name + widget_name try: widget_value = value[i] except IndexError: widget_value = None if id_: widget_attrs = final_attrs.copy() widget_attrs["id"] = "%s_%s" % (id_, i) else: widget_attrs = final_attrs subwidgets.append( widget.get_context(widget_name, widget_value, widget_attrs)["widget"] ) context["widget"]["subwidgets"] = subwidgets return context def id_for_label(self, id_): return "" def value_from_datadict(self, data, files, name): return [ widget.value_from_datadict(data, files, name + widget_name) for widget_name, widget in zip(self.widgets_names, self.widgets) ] def value_omitted_from_data(self, data, files, name): return all( widget.value_omitted_from_data(data, files, name + widget_name) for widget_name, widget in zip(self.widgets_names, self.widgets) ) def decompress(self, value): """ Return a list of decompressed values for the given compressed value. The given value can be assumed to be valid, but not necessarily non-empty. """ raise NotImplementedError("Subclasses must implement this method.") def _get_media(self): """ Media for a multiwidget is the combination of all media of the subwidgets. """ media = Media() for w in self.widgets: media += w.media return media media = property(_get_media) def __deepcopy__(self, memo): obj = super().__deepcopy__(memo) obj.widgets = copy.deepcopy(self.widgets) return obj @property def needs_multipart_form(self): return any(w.needs_multipart_form for w in self.widgets) class SplitDateTimeWidget(MultiWidget): """ A widget that splits datetime input into two <input type="text"> boxes. """ supports_microseconds = False template_name = "django/forms/widgets/splitdatetime.html" def __init__( self, attrs=None, date_format=None, time_format=None, date_attrs=None, time_attrs=None, ): widgets = ( DateInput( attrs=attrs if date_attrs is None else date_attrs, format=date_format, ), TimeInput( attrs=attrs if time_attrs is None else time_attrs, format=time_format, ), ) super().__init__(widgets) def decompress(self, value): if value: value = to_current_timezone(value) return [value.date(), value.time()] return [None, None] class SplitHiddenDateTimeWidget(SplitDateTimeWidget): """ A widget that splits datetime input into two <input type="hidden"> inputs. """ template_name = "django/forms/widgets/splithiddendatetime.html" def __init__( self, attrs=None, date_format=None, time_format=None, date_attrs=None, time_attrs=None, ): super().__init__(attrs, date_format, time_format, date_attrs, time_attrs) for widget in self.widgets: widget.input_type = "hidden" class SelectDateWidget(Widget): """ A widget that splits date input into three <select> boxes. This also serves as an example of a Widget that has more than one HTML element and hence implements value_from_datadict. """ none_value = ("", "---") month_field = "%s_month" day_field = "%s_day" year_field = "%s_year" template_name = "django/forms/widgets/select_date.html" input_type = "select" select_widget = Select date_re = _lazy_re_compile(r"(\d{4}|0)-(\d\d?)-(\d\d?)$") use_fieldset = True def __init__(self, attrs=None, years=None, months=None, empty_label=None): self.attrs = attrs or {} # Optional list or tuple of years to use in the "year" select box. if years: self.years = years else: this_year = datetime.date.today().year self.years = range(this_year, this_year + 10) # Optional dict of months to use in the "month" select box. if months: self.months = months else: self.months = MONTHS # Optional string, list, or tuple to use as empty_label. if isinstance(empty_label, (list, tuple)): if not len(empty_label) == 3: raise ValueError("empty_label list/tuple must have 3 elements.") self.year_none_value = ("", empty_label[0]) self.month_none_value = ("", empty_label[1]) self.day_none_value = ("", empty_label[2]) else: if empty_label is not None: self.none_value = ("", empty_label) self.year_none_value = self.none_value self.month_none_value = self.none_value self.day_none_value = self.none_value def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) date_context = {} year_choices = [(i, str(i)) for i in self.years] if not self.is_required: year_choices.insert(0, self.year_none_value) year_name = self.year_field % name date_context["year"] = self.select_widget( attrs, choices=year_choices ).get_context( name=year_name, value=context["widget"]["value"]["year"], attrs={**context["widget"]["attrs"], "id": "id_%s" % year_name}, ) month_choices = list(self.months.items()) if not self.is_required: month_choices.insert(0, self.month_none_value) month_name = self.month_field % name date_context["month"] = self.select_widget( attrs, choices=month_choices ).get_context( name=month_name, value=context["widget"]["value"]["month"], attrs={**context["widget"]["attrs"], "id": "id_%s" % month_name}, ) day_choices = [(i, i) for i in range(1, 32)] if not self.is_required: day_choices.insert(0, self.day_none_value) day_name = self.day_field % name date_context["day"] = self.select_widget( attrs, choices=day_choices, ).get_context( name=day_name, value=context["widget"]["value"]["day"], attrs={**context["widget"]["attrs"], "id": "id_%s" % day_name}, ) subwidgets = [] for field in self._parse_date_fmt(): subwidgets.append(date_context[field]["widget"]) context["widget"]["subwidgets"] = subwidgets return context def format_value(self, value): """ Return a dict containing the year, month, and day of the current value. Use dict instead of a datetime to allow invalid dates such as February 31 to display correctly. """ year, month, day = None, None, None if isinstance(value, (datetime.date, datetime.datetime)): year, month, day = value.year, value.month, value.day elif isinstance(value, str): match = self.date_re.match(value) if match: # Convert any zeros in the date to empty strings to match the # empty option value. year, month, day = [int(val) or "" for val in match.groups()] else: input_format = get_format("DATE_INPUT_FORMATS")[0] try: d = datetime.datetime.strptime(value, input_format) except ValueError: pass else: year, month, day = d.year, d.month, d.day return {"year": year, "month": month, "day": day} @staticmethod def _parse_date_fmt(): fmt = get_format("DATE_FORMAT") escaped = False for char in fmt: if escaped: escaped = False elif char == "\\": escaped = True elif char in "Yy": yield "year" elif char in "bEFMmNn": yield "month" elif char in "dj": yield "day" def id_for_label(self, id_): for first_select in self._parse_date_fmt(): return "%s_%s" % (id_, first_select) return "%s_month" % id_ def value_from_datadict(self, data, files, name): y = data.get(self.year_field % name) m = data.get(self.month_field % name) d = data.get(self.day_field % name) if y == m == d == "": return None if y is not None and m is not None and d is not None: input_format = get_format("DATE_INPUT_FORMATS")[0] input_format = formats.sanitize_strftime_format(input_format) try: date_value = datetime.date(int(y), int(m), int(d)) except ValueError: # Return pseudo-ISO dates with zeros for any unselected values, # e.g. '2017-0-23'. return "%s-%s-%s" % (y or 0, m or 0, d or 0) except OverflowError: return "0-0-0" return date_value.strftime(input_format) return data.get(name) def value_omitted_from_data(self, data, files, name): return not any( ("{}_{}".format(name, interval) in data) for interval in ("year", "month", "day") )
c4008c65198bf3847e4cf0bae633b96e26960f235a11106175c796c751f6c226
import re from django.core.exceptions import ValidationError from django.forms.utils import RenderableFieldMixin, pretty_name from django.forms.widgets import MultiWidget, Textarea, TextInput from django.utils.functional import cached_property from django.utils.html import format_html, html_safe from django.utils.translation import gettext_lazy as _ __all__ = ("BoundField",) class BoundField(RenderableFieldMixin): "A Field plus data" def __init__(self, form, field, name): self.form = form self.field = field self.name = name self.html_name = form.add_prefix(name) self.html_initial_name = form.add_initial_prefix(name) self.html_initial_id = form.add_initial_prefix(self.auto_id) if self.field.label is None: self.label = pretty_name(name) else: self.label = self.field.label self.help_text = field.help_text or "" self.renderer = form.renderer @cached_property def subwidgets(self): """ Most widgets yield a single subwidget, but others like RadioSelect and CheckboxSelectMultiple produce one subwidget for each choice. This property is cached so that only one database query occurs when rendering ModelChoiceFields. """ id_ = self.field.widget.attrs.get("id") or self.auto_id attrs = {"id": id_} if id_ else {} attrs = self.build_widget_attrs(attrs) return [ BoundWidget(self.field.widget, widget, self.form.renderer) for widget in self.field.widget.subwidgets( self.html_name, self.value(), attrs=attrs ) ] def __bool__(self): # BoundField evaluates to True even if it doesn't have subwidgets. return True def __iter__(self): return iter(self.subwidgets) def __len__(self): return len(self.subwidgets) def __getitem__(self, idx): # Prevent unnecessary reevaluation when accessing BoundField's attrs # from templates. if not isinstance(idx, (int, slice)): raise TypeError( "BoundField indices must be integers or slices, not %s." % type(idx).__name__ ) return self.subwidgets[idx] @property def errors(self): """ Return an ErrorList (empty if there are no errors) for this field. """ return self.form.errors.get( self.name, self.form.error_class(renderer=self.form.renderer) ) @property def template_name(self): return self.field.template_name or self.form.renderer.field_template_name def get_context(self): return {"field": self} def as_widget(self, widget=None, attrs=None, only_initial=False): """ Render the field by rendering the passed widget, adding any HTML attributes passed as attrs. If a widget isn't specified, use the field's default widget. """ widget = widget or self.field.widget if self.field.localize: widget.is_localized = True attrs = attrs or {} attrs = self.build_widget_attrs(attrs, widget) if self.auto_id and "id" not in widget.attrs: attrs.setdefault( "id", self.html_initial_id if only_initial else self.auto_id ) if only_initial and self.html_initial_name in self.form.data: # Propagate the hidden initial value. value = self.form._widget_data_value( self.field.hidden_widget(), self.html_initial_name, ) else: value = self.value() return widget.render( name=self.html_initial_name if only_initial else self.html_name, value=value, attrs=attrs, renderer=self.form.renderer, ) def as_text(self, attrs=None, **kwargs): """ Return a string of HTML for representing this as an <input type="text">. """ return self.as_widget(TextInput(), attrs, **kwargs) def as_textarea(self, attrs=None, **kwargs): """Return a string of HTML for representing this as a <textarea>.""" return self.as_widget(Textarea(), attrs, **kwargs) def as_hidden(self, attrs=None, **kwargs): """ Return a string of HTML for representing this as an <input type="hidden">. """ return self.as_widget(self.field.hidden_widget(), attrs, **kwargs) @property def data(self): """ Return the data for this BoundField, or None if it wasn't given. """ return self.form._widget_data_value(self.field.widget, self.html_name) def value(self): """ Return the value for this BoundField, using the initial value if the form is not bound or the data otherwise. """ data = self.initial if self.form.is_bound: data = self.field.bound_data(self.data, data) return self.field.prepare_value(data) def _has_changed(self): field = self.field if field.show_hidden_initial: hidden_widget = field.hidden_widget() initial_value = self.form._widget_data_value( hidden_widget, self.html_initial_name, ) try: initial_value = field.to_python(initial_value) except ValidationError: # Always assume data has changed if validation fails. return True else: initial_value = self.initial return field.has_changed(initial_value, self.data) def label_tag(self, contents=None, attrs=None, label_suffix=None, tag=None): """ Wrap the given contents in a <label>, if the field has an ID attribute. contents should be mark_safe'd to avoid HTML escaping. If contents aren't given, use the field's HTML-escaped label. If attrs are given, use them as HTML attributes on the <label> tag. label_suffix overrides the form's label_suffix. """ contents = contents or self.label if label_suffix is None: label_suffix = ( self.field.label_suffix if self.field.label_suffix is not None else self.form.label_suffix ) # Only add the suffix if the label does not end in punctuation. # Translators: If found as last label character, these punctuation # characters will prevent the default label_suffix to be appended to the label if label_suffix and contents and contents[-1] not in _(":?.!"): contents = format_html("{}{}", contents, label_suffix) widget = self.field.widget id_ = widget.attrs.get("id") or self.auto_id if id_: id_for_label = widget.id_for_label(id_) if id_for_label: attrs = {**(attrs or {}), "for": id_for_label} if self.field.required and hasattr(self.form, "required_css_class"): attrs = attrs or {} if "class" in attrs: attrs["class"] += " " + self.form.required_css_class else: attrs["class"] = self.form.required_css_class context = { "field": self, "label": contents, "attrs": attrs, "use_tag": bool(id_), "tag": tag or "label", } return self.form.render(self.form.template_name_label, context) def legend_tag(self, contents=None, attrs=None, label_suffix=None): """ Wrap the given contents in a <legend>, if the field has an ID attribute. Contents should be mark_safe'd to avoid HTML escaping. If contents aren't given, use the field's HTML-escaped label. If attrs are given, use them as HTML attributes on the <legend> tag. label_suffix overrides the form's label_suffix. """ return self.label_tag(contents, attrs, label_suffix, tag="legend") def css_classes(self, extra_classes=None): """ Return a string of space-separated CSS classes for this field. """ if hasattr(extra_classes, "split"): extra_classes = extra_classes.split() extra_classes = set(extra_classes or []) if self.errors and hasattr(self.form, "error_css_class"): extra_classes.add(self.form.error_css_class) if self.field.required and hasattr(self.form, "required_css_class"): extra_classes.add(self.form.required_css_class) return " ".join(extra_classes) @property def is_hidden(self): """Return True if this BoundField's widget is hidden.""" return self.field.widget.is_hidden @property def auto_id(self): """ Calculate and return the ID attribute for this BoundField, if the associated Form has specified auto_id. Return an empty string otherwise. """ auto_id = self.form.auto_id # Boolean or string if auto_id and "%s" in str(auto_id): return auto_id % self.html_name elif auto_id: return self.html_name return "" @property def id_for_label(self): """ Wrapper around the field widget's `id_for_label` method. Useful, for example, for focusing on this field regardless of whether it has a single widget or a MultiWidget. """ widget = self.field.widget id_ = widget.attrs.get("id") or self.auto_id return widget.id_for_label(id_) @cached_property def initial(self): return self.form.get_initial_for_field(self.field, self.name) def build_widget_attrs(self, attrs, widget=None): widget = widget or self.field.widget attrs = dict(attrs) # Copy attrs to avoid modifying the argument. if ( widget.use_required_attribute(self.initial) and self.field.required and self.form.use_required_attribute ): # MultiValueField has require_all_fields: if False, fall back # on subfields. if ( hasattr(self.field, "require_all_fields") and not self.field.require_all_fields and isinstance(self.field.widget, MultiWidget) ): for subfield, subwidget in zip(self.field.fields, widget.widgets): subwidget.attrs["required"] = ( subwidget.use_required_attribute(self.initial) and subfield.required ) else: attrs["required"] = True if self.field.disabled: attrs["disabled"] = True return attrs @property def widget_type(self): return re.sub( r"widget$|input$", "", self.field.widget.__class__.__name__.lower() ) @property def use_fieldset(self): """ Return the value of this BoundField widget's use_fieldset attribute. """ return self.field.widget.use_fieldset @html_safe class BoundWidget: """ A container class used for iterating over widgets. This is useful for widgets that have choices. For example, the following can be used in a template: {% for radio in myform.beatles %} <label for="{{ radio.id_for_label }}"> {{ radio.choice_label }} <span class="radio">{{ radio.tag }}</span> </label> {% endfor %} """ def __init__(self, parent_widget, data, renderer): self.parent_widget = parent_widget self.data = data self.renderer = renderer def __str__(self): return self.tag(wrap_label=True) def tag(self, wrap_label=False): context = {"widget": {**self.data, "wrap_label": wrap_label}} return self.parent_widget._render(self.template_name, context, self.renderer) @property def template_name(self): if "template_name" in self.data: return self.data["template_name"] return self.parent_widget.template_name @property def id_for_label(self): return self.data["attrs"].get("id") @property def choice_label(self): return self.data["label"]
f352b1c11658df635b88cd9cae7abdab2f70c5f5417f84968da785adccec559d
""" Field classes. """ import copy import datetime import json import math import operator import os import re import uuid from decimal import Decimal, DecimalException from io import BytesIO from urllib.parse import urlsplit, urlunsplit from django.core import validators from django.core.exceptions import ValidationError from django.db.models.enums import ChoicesMeta from django.forms.boundfield import BoundField from django.forms.utils import from_current_timezone, to_current_timezone from django.forms.widgets import ( FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput, DateInput, DateTimeInput, EmailInput, FileInput, HiddenInput, MultipleHiddenInput, NullBooleanSelect, NumberInput, Select, SelectMultiple, SplitDateTimeWidget, SplitHiddenDateTimeWidget, Textarea, TextInput, TimeInput, URLInput, ) from django.utils import formats from django.utils.dateparse import parse_datetime, parse_duration from django.utils.duration import duration_string from django.utils.ipv6 import clean_ipv6_address from django.utils.regex_helper import _lazy_re_compile from django.utils.translation import gettext_lazy as _ from django.utils.translation import ngettext_lazy __all__ = ( "Field", "CharField", "IntegerField", "DateField", "TimeField", "DateTimeField", "DurationField", "RegexField", "EmailField", "FileField", "ImageField", "URLField", "BooleanField", "NullBooleanField", "ChoiceField", "MultipleChoiceField", "ComboField", "MultiValueField", "FloatField", "DecimalField", "SplitDateTimeField", "GenericIPAddressField", "FilePathField", "JSONField", "SlugField", "TypedChoiceField", "TypedMultipleChoiceField", "UUIDField", ) class Field: widget = TextInput # Default widget to use when rendering this type of Field. hidden_widget = ( HiddenInput # Default widget to use when rendering this as "hidden". ) default_validators = [] # Default set of validators # Add an 'invalid' entry to default_error_message if you want a specific # field error message not raised by the field validators. default_error_messages = { "required": _("This field is required."), } empty_values = list(validators.EMPTY_VALUES) def __init__( self, *, required=True, widget=None, label=None, initial=None, help_text="", error_messages=None, show_hidden_initial=False, validators=(), localize=False, disabled=False, label_suffix=None, template_name=None, ): # required -- Boolean that specifies whether the field is required. # True by default. # widget -- A Widget class, or instance of a Widget class, that should # be used for this Field when displaying it. Each Field has a # default Widget that it'll use if you don't specify this. In # most cases, the default widget is TextInput. # label -- A verbose name for this field, for use in displaying this # field in a form. By default, Django will use a "pretty" # version of the form field name, if the Field is part of a # Form. # initial -- A value to use in this Field's initial display. This value # is *not* used as a fallback if data isn't given. # help_text -- An optional string to use as "help text" for this Field. # error_messages -- An optional dictionary to override the default # messages that the field will raise. # show_hidden_initial -- Boolean that specifies if it is needed to render a # hidden widget with initial value after widget. # validators -- List of additional validators to use # localize -- Boolean that specifies if the field should be localized. # disabled -- Boolean that specifies whether the field is disabled, that # is its widget is shown in the form but not editable. # label_suffix -- Suffix to be added to the label. Overrides # form's label_suffix. self.required, self.label, self.initial = required, label, initial self.show_hidden_initial = show_hidden_initial self.help_text = help_text self.disabled = disabled self.label_suffix = label_suffix widget = widget or self.widget if isinstance(widget, type): widget = widget() else: widget = copy.deepcopy(widget) # Trigger the localization machinery if needed. self.localize = localize if self.localize: widget.is_localized = True # Let the widget know whether it should display as required. widget.is_required = self.required # Hook into self.widget_attrs() for any Field-specific HTML attributes. extra_attrs = self.widget_attrs(widget) if extra_attrs: widget.attrs.update(extra_attrs) self.widget = widget messages = {} for c in reversed(self.__class__.__mro__): messages.update(getattr(c, "default_error_messages", {})) messages.update(error_messages or {}) self.error_messages = messages self.validators = [*self.default_validators, *validators] self.template_name = template_name super().__init__() def prepare_value(self, value): return value def to_python(self, value): return value def validate(self, value): if value in self.empty_values and self.required: raise ValidationError(self.error_messages["required"], code="required") def run_validators(self, value): if value in self.empty_values: return errors = [] for v in self.validators: try: v(value) except ValidationError as e: if hasattr(e, "code") and e.code in self.error_messages: e.message = self.error_messages[e.code] errors.extend(e.error_list) if errors: raise ValidationError(errors) def clean(self, value): """ Validate the given value and return its "cleaned" value as an appropriate Python object. Raise ValidationError for any errors. """ value = self.to_python(value) self.validate(value) self.run_validators(value) return value def bound_data(self, data, initial): """ Return the value that should be shown for this field on render of a bound form, given the submitted POST data for the field and the initial data, if any. For most fields, this will simply be data; FileFields need to handle it a bit differently. """ if self.disabled: return initial return data def widget_attrs(self, widget): """ Given a Widget instance (*not* a Widget class), return a dictionary of any HTML attributes that should be added to the Widget, based on this Field. """ return {} def has_changed(self, initial, data): """Return True if data differs from initial.""" # Always return False if the field is disabled since self.bound_data # always uses the initial value in this case. if self.disabled: return False try: data = self.to_python(data) if hasattr(self, "_coerce"): return self._coerce(data) != self._coerce(initial) except ValidationError: return True # For purposes of seeing whether something has changed, None is # the same as an empty string, if the data or initial value we get # is None, replace it with ''. initial_value = initial if initial is not None else "" data_value = data if data is not None else "" return initial_value != data_value def get_bound_field(self, form, field_name): """ Return a BoundField instance that will be used when accessing the form field in a template. """ return BoundField(form, self, field_name) def __deepcopy__(self, memo): result = copy.copy(self) memo[id(self)] = result result.widget = copy.deepcopy(self.widget, memo) result.error_messages = self.error_messages.copy() result.validators = self.validators[:] return result class CharField(Field): def __init__( self, *, max_length=None, min_length=None, strip=True, empty_value="", **kwargs ): self.max_length = max_length self.min_length = min_length self.strip = strip self.empty_value = empty_value super().__init__(**kwargs) if min_length is not None: self.validators.append(validators.MinLengthValidator(int(min_length))) if max_length is not None: self.validators.append(validators.MaxLengthValidator(int(max_length))) self.validators.append(validators.ProhibitNullCharactersValidator()) def to_python(self, value): """Return a string.""" if value not in self.empty_values: value = str(value) if self.strip: value = value.strip() if value in self.empty_values: return self.empty_value return value def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if self.max_length is not None and not widget.is_hidden: # The HTML attribute is maxlength, not max_length. attrs["maxlength"] = str(self.max_length) if self.min_length is not None and not widget.is_hidden: # The HTML attribute is minlength, not min_length. attrs["minlength"] = str(self.min_length) return attrs class IntegerField(Field): widget = NumberInput default_error_messages = { "invalid": _("Enter a whole number."), } re_decimal = _lazy_re_compile(r"\.0*\s*$") def __init__(self, *, max_value=None, min_value=None, step_size=None, **kwargs): self.max_value, self.min_value, self.step_size = max_value, min_value, step_size if kwargs.get("localize") and self.widget == NumberInput: # Localized number input is not well supported on most browsers kwargs.setdefault("widget", super().widget) super().__init__(**kwargs) if max_value is not None: self.validators.append(validators.MaxValueValidator(max_value)) if min_value is not None: self.validators.append(validators.MinValueValidator(min_value)) if step_size is not None: self.validators.append(validators.StepValueValidator(step_size)) def to_python(self, value): """ Validate that int() can be called on the input. Return the result of int() or None for empty values. """ value = super().to_python(value) if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) # Strip trailing decimal and zeros. try: value = int(self.re_decimal.sub("", str(value))) except (ValueError, TypeError): raise ValidationError(self.error_messages["invalid"], code="invalid") return value def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput): if self.min_value is not None: attrs["min"] = self.min_value if self.max_value is not None: attrs["max"] = self.max_value if self.step_size is not None: attrs["step"] = self.step_size return attrs class FloatField(IntegerField): default_error_messages = { "invalid": _("Enter a number."), } def to_python(self, value): """ Validate that float() can be called on the input. Return the result of float() or None for empty values. """ value = super(IntegerField, self).to_python(value) if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) try: value = float(value) except (ValueError, TypeError): raise ValidationError(self.error_messages["invalid"], code="invalid") return value def validate(self, value): super().validate(value) if value in self.empty_values: return if not math.isfinite(value): raise ValidationError(self.error_messages["invalid"], code="invalid") def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput) and "step" not in widget.attrs: if self.step_size is not None: step = str(self.step_size) else: step = "any" attrs.setdefault("step", step) return attrs class DecimalField(IntegerField): default_error_messages = { "invalid": _("Enter a number."), } def __init__( self, *, max_value=None, min_value=None, max_digits=None, decimal_places=None, **kwargs, ): self.max_digits, self.decimal_places = max_digits, decimal_places super().__init__(max_value=max_value, min_value=min_value, **kwargs) self.validators.append(validators.DecimalValidator(max_digits, decimal_places)) def to_python(self, value): """ Validate that the input is a decimal number. Return a Decimal instance or None for empty values. Ensure that there are no more than max_digits in the number and no more than decimal_places digits after the decimal point. """ if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) try: value = Decimal(str(value)) except DecimalException: raise ValidationError(self.error_messages["invalid"], code="invalid") return value def validate(self, value): super().validate(value) if value in self.empty_values: return if not value.is_finite(): raise ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput) and "step" not in widget.attrs: if self.decimal_places is not None: # Use exponential notation for small values since they might # be parsed as 0 otherwise. ref #20765 step = str(Decimal(1).scaleb(-self.decimal_places)).lower() else: step = "any" attrs.setdefault("step", step) return attrs class BaseTemporalField(Field): def __init__(self, *, input_formats=None, **kwargs): super().__init__(**kwargs) if input_formats is not None: self.input_formats = input_formats def to_python(self, value): value = value.strip() # Try to strptime against each input format. for format in self.input_formats: try: return self.strptime(value, format) except (ValueError, TypeError): continue raise ValidationError(self.error_messages["invalid"], code="invalid") def strptime(self, value, format): raise NotImplementedError("Subclasses must define this method.") class DateField(BaseTemporalField): widget = DateInput input_formats = formats.get_format_lazy("DATE_INPUT_FORMATS") default_error_messages = { "invalid": _("Enter a valid date."), } def to_python(self, value): """ Validate that the input can be converted to a date. Return a Python datetime.date object. """ if value in self.empty_values: return None if isinstance(value, datetime.datetime): return value.date() if isinstance(value, datetime.date): return value return super().to_python(value) def strptime(self, value, format): return datetime.datetime.strptime(value, format).date() class TimeField(BaseTemporalField): widget = TimeInput input_formats = formats.get_format_lazy("TIME_INPUT_FORMATS") default_error_messages = {"invalid": _("Enter a valid time.")} def to_python(self, value): """ Validate that the input can be converted to a time. Return a Python datetime.time object. """ if value in self.empty_values: return None if isinstance(value, datetime.time): return value return super().to_python(value) def strptime(self, value, format): return datetime.datetime.strptime(value, format).time() class DateTimeFormatsIterator: def __iter__(self): yield from formats.get_format("DATETIME_INPUT_FORMATS") yield from formats.get_format("DATE_INPUT_FORMATS") class DateTimeField(BaseTemporalField): widget = DateTimeInput input_formats = DateTimeFormatsIterator() default_error_messages = { "invalid": _("Enter a valid date/time."), } def prepare_value(self, value): if isinstance(value, datetime.datetime): value = to_current_timezone(value) return value def to_python(self, value): """ Validate that the input can be converted to a datetime. Return a Python datetime.datetime object. """ if value in self.empty_values: return None if isinstance(value, datetime.datetime): return from_current_timezone(value) if isinstance(value, datetime.date): result = datetime.datetime(value.year, value.month, value.day) return from_current_timezone(result) try: result = parse_datetime(value.strip()) except ValueError: raise ValidationError(self.error_messages["invalid"], code="invalid") if not result: result = super().to_python(value) return from_current_timezone(result) def strptime(self, value, format): return datetime.datetime.strptime(value, format) class DurationField(Field): default_error_messages = { "invalid": _("Enter a valid duration."), "overflow": _("The number of days must be between {min_days} and {max_days}."), } def prepare_value(self, value): if isinstance(value, datetime.timedelta): return duration_string(value) return value def to_python(self, value): if value in self.empty_values: return None if isinstance(value, datetime.timedelta): return value try: value = parse_duration(str(value)) except OverflowError: raise ValidationError( self.error_messages["overflow"].format( min_days=datetime.timedelta.min.days, max_days=datetime.timedelta.max.days, ), code="overflow", ) if value is None: raise ValidationError(self.error_messages["invalid"], code="invalid") return value class RegexField(CharField): def __init__(self, regex, **kwargs): """ regex can be either a string or a compiled regular expression object. """ kwargs.setdefault("strip", False) super().__init__(**kwargs) self._set_regex(regex) def _get_regex(self): return self._regex def _set_regex(self, regex): if isinstance(regex, str): regex = re.compile(regex) self._regex = regex if ( hasattr(self, "_regex_validator") and self._regex_validator in self.validators ): self.validators.remove(self._regex_validator) self._regex_validator = validators.RegexValidator(regex=regex) self.validators.append(self._regex_validator) regex = property(_get_regex, _set_regex) class EmailField(CharField): widget = EmailInput default_validators = [validators.validate_email] def __init__(self, **kwargs): super().__init__(strip=True, **kwargs) class FileField(Field): widget = ClearableFileInput default_error_messages = { "invalid": _("No file was submitted. Check the encoding type on the form."), "missing": _("No file was submitted."), "empty": _("The submitted file is empty."), "max_length": ngettext_lazy( "Ensure this filename has at most %(max)d character (it has %(length)d).", "Ensure this filename has at most %(max)d characters (it has %(length)d).", "max", ), "contradiction": _( "Please either submit a file or check the clear checkbox, not both." ), } def __init__(self, *, max_length=None, allow_empty_file=False, **kwargs): self.max_length = max_length self.allow_empty_file = allow_empty_file super().__init__(**kwargs) def to_python(self, data): if data in self.empty_values: return None # UploadedFile objects should have name and size attributes. try: file_name = data.name file_size = data.size except AttributeError: raise ValidationError(self.error_messages["invalid"], code="invalid") if self.max_length is not None and len(file_name) > self.max_length: params = {"max": self.max_length, "length": len(file_name)} raise ValidationError( self.error_messages["max_length"], code="max_length", params=params ) if not file_name: raise ValidationError(self.error_messages["invalid"], code="invalid") if not self.allow_empty_file and not file_size: raise ValidationError(self.error_messages["empty"], code="empty") return data def clean(self, data, initial=None): # If the widget got contradictory inputs, we raise a validation error if data is FILE_INPUT_CONTRADICTION: raise ValidationError( self.error_messages["contradiction"], code="contradiction" ) # False means the field value should be cleared; further validation is # not needed. if data is False: if not self.required: return False # If the field is required, clearing is not possible (the widget # shouldn't return False data in that case anyway). False is not # in self.empty_value; if a False value makes it this far # it should be validated from here on out as None (so it will be # caught by the required check). data = None if not data and initial: return initial return super().clean(data) def bound_data(self, _, initial): return initial def has_changed(self, initial, data): return not self.disabled and data is not None class ImageField(FileField): default_validators = [validators.validate_image_file_extension] default_error_messages = { "invalid_image": _( "Upload a valid image. The file you uploaded was either not an " "image or a corrupted image." ), } def to_python(self, data): """ Check that the file-upload field data contains a valid image (GIF, JPG, PNG, etc. -- whatever Pillow supports). """ f = super().to_python(data) if f is None: return None from PIL import Image # We need to get a file object for Pillow. We might have a path or we might # have to read the data into memory. if hasattr(data, "temporary_file_path"): file = data.temporary_file_path() else: if hasattr(data, "read"): file = BytesIO(data.read()) else: file = BytesIO(data["content"]) try: # load() could spot a truncated JPEG, but it loads the entire # image in memory, which is a DoS vector. See #3848 and #18520. image = Image.open(file) # verify() must be called immediately after the constructor. image.verify() # Annotating so subclasses can reuse it for their own validation f.image = image # Pillow doesn't detect the MIME type of all formats. In those # cases, content_type will be None. f.content_type = Image.MIME.get(image.format) except Exception as exc: # Pillow doesn't recognize it as an image. raise ValidationError( self.error_messages["invalid_image"], code="invalid_image", ) from exc if hasattr(f, "seek") and callable(f.seek): f.seek(0) return f def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, FileInput) and "accept" not in widget.attrs: attrs.setdefault("accept", "image/*") return attrs class URLField(CharField): widget = URLInput default_error_messages = { "invalid": _("Enter a valid URL."), } default_validators = [validators.URLValidator()] def __init__(self, **kwargs): super().__init__(strip=True, **kwargs) def to_python(self, value): def split_url(url): """ Return a list of url parts via urlparse.urlsplit(), or raise ValidationError for some malformed URLs. """ try: return list(urlsplit(url)) except ValueError: # urlparse.urlsplit can raise a ValueError with some # misformatted URLs. raise ValidationError(self.error_messages["invalid"], code="invalid") value = super().to_python(value) if value: url_fields = split_url(value) if not url_fields[0]: # If no URL scheme given, assume http:// url_fields[0] = "http" if not url_fields[1]: # Assume that if no domain is provided, that the path segment # contains the domain. url_fields[1] = url_fields[2] url_fields[2] = "" # Rebuild the url_fields list, since the domain segment may now # contain the path too. url_fields = split_url(urlunsplit(url_fields)) value = urlunsplit(url_fields) return value class BooleanField(Field): widget = CheckboxInput def to_python(self, value): """Return a Python boolean object.""" # Explicitly check for the string 'False', which is what a hidden field # will submit for False. Also check for '0', since this is what # RadioSelect will provide. Because bool("True") == bool('1') == True, # we don't need to handle that explicitly. if isinstance(value, str) and value.lower() in ("false", "0"): value = False else: value = bool(value) return super().to_python(value) def validate(self, value): if not value and self.required: raise ValidationError(self.error_messages["required"], code="required") def has_changed(self, initial, data): if self.disabled: return False # Sometimes data or initial may be a string equivalent of a boolean # so we should run it through to_python first to get a boolean value return self.to_python(initial) != self.to_python(data) class NullBooleanField(BooleanField): """ A field whose valid values are None, True, and False. Clean invalid values to None. """ widget = NullBooleanSelect def to_python(self, value): """ Explicitly check for the string 'True' and 'False', which is what a hidden field will submit for True and False, for 'true' and 'false', which are likely to be returned by JavaScript serializations of forms, and for '1' and '0', which is what a RadioField will submit. Unlike the Booleanfield, this field must check for True because it doesn't use the bool() function. """ if value in (True, "True", "true", "1"): return True elif value in (False, "False", "false", "0"): return False else: return None def validate(self, value): pass class CallableChoiceIterator: def __init__(self, choices_func): self.choices_func = choices_func def __iter__(self): yield from self.choices_func() class ChoiceField(Field): widget = Select default_error_messages = { "invalid_choice": _( "Select a valid choice. %(value)s is not one of the available choices." ), } def __init__(self, *, choices=(), **kwargs): super().__init__(**kwargs) if isinstance(choices, ChoicesMeta): choices = choices.choices self.choices = choices def __deepcopy__(self, memo): result = super().__deepcopy__(memo) result._choices = copy.deepcopy(self._choices, memo) return result def _get_choices(self): return self._choices def _set_choices(self, value): # Setting choices also sets the choices on the widget. # choices can be any iterable, but we call list() on it because # it will be consumed more than once. if callable(value): value = CallableChoiceIterator(value) else: value = list(value) self._choices = self.widget.choices = value choices = property(_get_choices, _set_choices) def to_python(self, value): """Return a string.""" if value in self.empty_values: return "" return str(value) def validate(self, value): """Validate that the input is in self.choices.""" super().validate(value) if value and not self.valid_value(value): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}, ) def valid_value(self, value): """Check to see if the provided value is a valid choice.""" text_value = str(value) for k, v in self.choices: if isinstance(v, (list, tuple)): # This is an optgroup, so look inside the group for options for k2, v2 in v: if value == k2 or text_value == str(k2): return True else: if value == k or text_value == str(k): return True return False class TypedChoiceField(ChoiceField): def __init__(self, *, coerce=lambda val: val, empty_value="", **kwargs): self.coerce = coerce self.empty_value = empty_value super().__init__(**kwargs) def _coerce(self, value): """ Validate that the value can be coerced to the right type (if not empty). """ if value == self.empty_value or value in self.empty_values: return self.empty_value try: value = self.coerce(value) except (ValueError, TypeError, ValidationError): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}, ) return value def clean(self, value): value = super().clean(value) return self._coerce(value) class MultipleChoiceField(ChoiceField): hidden_widget = MultipleHiddenInput widget = SelectMultiple default_error_messages = { "invalid_choice": _( "Select a valid choice. %(value)s is not one of the available choices." ), "invalid_list": _("Enter a list of values."), } def to_python(self, value): if not value: return [] elif not isinstance(value, (list, tuple)): raise ValidationError( self.error_messages["invalid_list"], code="invalid_list" ) return [str(val) for val in value] def validate(self, value): """Validate that the input is a list or tuple.""" if self.required and not value: raise ValidationError(self.error_messages["required"], code="required") # Validate that each value in the value list is in self.choices. for val in value: if not self.valid_value(val): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": val}, ) def has_changed(self, initial, data): if self.disabled: return False if initial is None: initial = [] if data is None: data = [] if len(initial) != len(data): return True initial_set = {str(value) for value in initial} data_set = {str(value) for value in data} return data_set != initial_set class TypedMultipleChoiceField(MultipleChoiceField): def __init__(self, *, coerce=lambda val: val, **kwargs): self.coerce = coerce self.empty_value = kwargs.pop("empty_value", []) super().__init__(**kwargs) def _coerce(self, value): """ Validate that the values are in self.choices and can be coerced to the right type. """ if value == self.empty_value or value in self.empty_values: return self.empty_value new_value = [] for choice in value: try: new_value.append(self.coerce(choice)) except (ValueError, TypeError, ValidationError): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": choice}, ) return new_value def clean(self, value): value = super().clean(value) return self._coerce(value) def validate(self, value): if value != self.empty_value: super().validate(value) elif self.required: raise ValidationError(self.error_messages["required"], code="required") class ComboField(Field): """ A Field whose clean() method calls multiple Field clean() methods. """ def __init__(self, fields, **kwargs): super().__init__(**kwargs) # Set 'required' to False on the individual fields, because the # required validation will be handled by ComboField, not by those # individual fields. for f in fields: f.required = False self.fields = fields def clean(self, value): """ Validate the given value against all of self.fields, which is a list of Field instances. """ super().clean(value) for field in self.fields: value = field.clean(value) return value class MultiValueField(Field): """ Aggregate the logic of multiple Fields. Its clean() method takes a "decompressed" list of values, which are then cleaned into a single value according to self.fields. Each value in this list is cleaned by the corresponding field -- the first value is cleaned by the first field, the second value is cleaned by the second field, etc. Once all fields are cleaned, the list of clean values is "compressed" into a single value. Subclasses should not have to implement clean(). Instead, they must implement compress(), which takes a list of valid values and returns a "compressed" version of those values -- a single value. You'll probably want to use this with MultiWidget. """ default_error_messages = { "invalid": _("Enter a list of values."), "incomplete": _("Enter a complete value."), } def __init__(self, fields, *, require_all_fields=True, **kwargs): self.require_all_fields = require_all_fields super().__init__(**kwargs) for f in fields: f.error_messages.setdefault("incomplete", self.error_messages["incomplete"]) if self.disabled: f.disabled = True if self.require_all_fields: # Set 'required' to False on the individual fields, because the # required validation will be handled by MultiValueField, not # by those individual fields. f.required = False self.fields = fields def __deepcopy__(self, memo): result = super().__deepcopy__(memo) result.fields = tuple(x.__deepcopy__(memo) for x in self.fields) return result def validate(self, value): pass def clean(self, value): """ Validate every value in the given list. A value is validated against the corresponding Field in self.fields. For example, if this MultiValueField was instantiated with fields=(DateField(), TimeField()), clean() would call DateField.clean(value[0]) and TimeField.clean(value[1]). """ clean_data = [] errors = [] if self.disabled and not isinstance(value, list): value = self.widget.decompress(value) if not value or isinstance(value, (list, tuple)): if not value or not [v for v in value if v not in self.empty_values]: if self.required: raise ValidationError( self.error_messages["required"], code="required" ) else: return self.compress([]) else: raise ValidationError(self.error_messages["invalid"], code="invalid") for i, field in enumerate(self.fields): try: field_value = value[i] except IndexError: field_value = None if field_value in self.empty_values: if self.require_all_fields: # Raise a 'required' error if the MultiValueField is # required and any field is empty. if self.required: raise ValidationError( self.error_messages["required"], code="required" ) elif field.required: # Otherwise, add an 'incomplete' error to the list of # collected errors and skip field cleaning, if a required # field is empty. if field.error_messages["incomplete"] not in errors: errors.append(field.error_messages["incomplete"]) continue try: clean_data.append(field.clean(field_value)) except ValidationError as e: # Collect all validation errors in a single list, which we'll # raise at the end of clean(), rather than raising a single # exception for the first error we encounter. Skip duplicates. errors.extend(m for m in e.error_list if m not in errors) if errors: raise ValidationError(errors) out = self.compress(clean_data) self.validate(out) self.run_validators(out) return out def compress(self, data_list): """ Return a single value for the given list of values. The values can be assumed to be valid. For example, if this MultiValueField was instantiated with fields=(DateField(), TimeField()), this might return a datetime object created by combining the date and time in data_list. """ raise NotImplementedError("Subclasses must implement this method.") def has_changed(self, initial, data): if self.disabled: return False if initial is None: initial = ["" for x in range(0, len(data))] else: if not isinstance(initial, list): initial = self.widget.decompress(initial) for field, initial, data in zip(self.fields, initial, data): try: initial = field.to_python(initial) except ValidationError: return True if field.has_changed(initial, data): return True return False class FilePathField(ChoiceField): def __init__( self, path, *, match=None, recursive=False, allow_files=True, allow_folders=False, **kwargs, ): self.path, self.match, self.recursive = path, match, recursive self.allow_files, self.allow_folders = allow_files, allow_folders super().__init__(choices=(), **kwargs) if self.required: self.choices = [] else: self.choices = [("", "---------")] if self.match is not None: self.match_re = re.compile(self.match) if recursive: for root, dirs, files in sorted(os.walk(self.path)): if self.allow_files: for f in sorted(files): if self.match is None or self.match_re.search(f): f = os.path.join(root, f) self.choices.append((f, f.replace(path, "", 1))) if self.allow_folders: for f in sorted(dirs): if f == "__pycache__": continue if self.match is None or self.match_re.search(f): f = os.path.join(root, f) self.choices.append((f, f.replace(path, "", 1))) else: choices = [] with os.scandir(self.path) as entries: for f in entries: if f.name == "__pycache__": continue if ( (self.allow_files and f.is_file()) or (self.allow_folders and f.is_dir()) ) and (self.match is None or self.match_re.search(f.name)): choices.append((f.path, f.name)) choices.sort(key=operator.itemgetter(1)) self.choices.extend(choices) self.widget.choices = self.choices class SplitDateTimeField(MultiValueField): widget = SplitDateTimeWidget hidden_widget = SplitHiddenDateTimeWidget default_error_messages = { "invalid_date": _("Enter a valid date."), "invalid_time": _("Enter a valid time."), } def __init__(self, *, input_date_formats=None, input_time_formats=None, **kwargs): errors = self.default_error_messages.copy() if "error_messages" in kwargs: errors.update(kwargs["error_messages"]) localize = kwargs.get("localize", False) fields = ( DateField( input_formats=input_date_formats, error_messages={"invalid": errors["invalid_date"]}, localize=localize, ), TimeField( input_formats=input_time_formats, error_messages={"invalid": errors["invalid_time"]}, localize=localize, ), ) super().__init__(fields, **kwargs) def compress(self, data_list): if data_list: # Raise a validation error if time or date is empty # (possible if SplitDateTimeField has required=False). if data_list[0] in self.empty_values: raise ValidationError( self.error_messages["invalid_date"], code="invalid_date" ) if data_list[1] in self.empty_values: raise ValidationError( self.error_messages["invalid_time"], code="invalid_time" ) result = datetime.datetime.combine(*data_list) return from_current_timezone(result) return None class GenericIPAddressField(CharField): def __init__(self, *, protocol="both", unpack_ipv4=False, **kwargs): self.unpack_ipv4 = unpack_ipv4 self.default_validators = validators.ip_address_validators( protocol, unpack_ipv4 )[0] super().__init__(**kwargs) def to_python(self, value): if value in self.empty_values: return "" value = value.strip() if value and ":" in value: return clean_ipv6_address(value, self.unpack_ipv4) return value class SlugField(CharField): default_validators = [validators.validate_slug] def __init__(self, *, allow_unicode=False, **kwargs): self.allow_unicode = allow_unicode if self.allow_unicode: self.default_validators = [validators.validate_unicode_slug] super().__init__(**kwargs) class UUIDField(CharField): default_error_messages = { "invalid": _("Enter a valid UUID."), } def prepare_value(self, value): if isinstance(value, uuid.UUID): return str(value) return value def to_python(self, value): value = super().to_python(value) if value in self.empty_values: return None if not isinstance(value, uuid.UUID): try: value = uuid.UUID(value) except ValueError: raise ValidationError(self.error_messages["invalid"], code="invalid") return value class InvalidJSONInput(str): pass class JSONString(str): pass class JSONField(CharField): default_error_messages = { "invalid": _("Enter a valid JSON."), } widget = Textarea def __init__(self, encoder=None, decoder=None, **kwargs): self.encoder = encoder self.decoder = decoder super().__init__(**kwargs) def to_python(self, value): if self.disabled: return value if value in self.empty_values: return None elif isinstance(value, (list, dict, int, float, JSONString)): return value try: converted = json.loads(value, cls=self.decoder) except json.JSONDecodeError: raise ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) if isinstance(converted, str): return JSONString(converted) else: return converted def bound_data(self, data, initial): if self.disabled: return initial if data is None: return None try: return json.loads(data, cls=self.decoder) except json.JSONDecodeError: return InvalidJSONInput(data) def prepare_value(self, value): if isinstance(value, InvalidJSONInput): return value return json.dumps(value, ensure_ascii=False, cls=self.encoder) def has_changed(self, initial, data): if super().has_changed(initial, data): return True # For purposes of seeing whether something has changed, True isn't the # same as 1 and the order of keys doesn't matter. return json.dumps(initial, sort_keys=True, cls=self.encoder) != json.dumps( self.to_python(data), sort_keys=True, cls=self.encoder )
02a7754b3eb01e5ed26ae78dee1cc4d7e5ea847bf2f703825a7fd349196a2cc6
import json from collections import UserList from django.conf import settings from django.core.exceptions import ValidationError from django.forms.renderers import get_default_renderer from django.utils import timezone from django.utils.html import escape, format_html_join from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ def pretty_name(name): """Convert 'first_name' to 'First name'.""" if not name: return "" return name.replace("_", " ").capitalize() def flatatt(attrs): """ Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. In the case of a boolean value, the key will appear without a value. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. The result is passed through 'mark_safe' (by way of 'format_html_join'). """ key_value_attrs = [] boolean_attrs = [] for attr, value in attrs.items(): if isinstance(value, bool): if value: boolean_attrs.append((attr,)) elif value is not None: key_value_attrs.append((attr, value)) return format_html_join("", ' {}="{}"', sorted(key_value_attrs)) + format_html_join( "", " {}", sorted(boolean_attrs) ) class RenderableMixin: def get_context(self): raise NotImplementedError( "Subclasses of RenderableMixin must provide a get_context() method." ) def render(self, template_name=None, context=None, renderer=None): renderer = renderer or self.renderer template = template_name or self.template_name context = context or self.get_context() return mark_safe(renderer.render(template, context)) __str__ = render __html__ = render class RenderableFieldMixin(RenderableMixin): def as_field_group(self): return self.render() def as_hidden(self): raise NotImplementedError( "Subclasses of RenderableFieldMixin must provide an as_hidden() method." ) def as_widget(self): raise NotImplementedError( "Subclasses of RenderableFieldMixin must provide an as_widget() method." ) def __str__(self): """Render this field as an HTML widget.""" if self.field.show_hidden_initial: return self.as_widget() + self.as_hidden(only_initial=True) return self.as_widget() __html__ = __str__ class RenderableFormMixin(RenderableMixin): def as_p(self): """Render as <p> elements.""" return self.render(self.template_name_p) def as_table(self): """Render as <tr> elements excluding the surrounding <table> tag.""" return self.render(self.template_name_table) def as_ul(self): """Render as <li> elements excluding the surrounding <ul> tag.""" return self.render(self.template_name_ul) def as_div(self): """Render as <div> elements.""" return self.render(self.template_name_div) class RenderableErrorMixin(RenderableMixin): def as_json(self, escape_html=False): return json.dumps(self.get_json_data(escape_html)) def as_text(self): return self.render(self.template_name_text) def as_ul(self): return self.render(self.template_name_ul) class ErrorDict(dict, RenderableErrorMixin): """ A collection of errors that knows how to display itself in various formats. The dictionary keys are the field names, and the values are the errors. """ template_name = "django/forms/errors/dict/default.html" template_name_text = "django/forms/errors/dict/text.txt" template_name_ul = "django/forms/errors/dict/ul.html" def __init__(self, *args, renderer=None, **kwargs): super().__init__(*args, **kwargs) self.renderer = renderer or get_default_renderer() def as_data(self): return {f: e.as_data() for f, e in self.items()} def get_json_data(self, escape_html=False): return {f: e.get_json_data(escape_html) for f, e in self.items()} def get_context(self): return { "errors": self.items(), "error_class": "errorlist", } class ErrorList(UserList, list, RenderableErrorMixin): """ A collection of errors that knows how to display itself in various formats. """ template_name = "django/forms/errors/list/default.html" template_name_text = "django/forms/errors/list/text.txt" template_name_ul = "django/forms/errors/list/ul.html" def __init__(self, initlist=None, error_class=None, renderer=None): super().__init__(initlist) if error_class is None: self.error_class = "errorlist" else: self.error_class = "errorlist {}".format(error_class) self.renderer = renderer or get_default_renderer() def as_data(self): return ValidationError(self.data).error_list def copy(self): copy = super().copy() copy.error_class = self.error_class return copy def get_json_data(self, escape_html=False): errors = [] for error in self.as_data(): message = next(iter(error)) errors.append( { "message": escape(message) if escape_html else message, "code": error.code or "", } ) return errors def get_context(self): return { "errors": self, "error_class": self.error_class, } def __repr__(self): return repr(list(self)) def __contains__(self, item): return item in list(self) def __eq__(self, other): return list(self) == other def __getitem__(self, i): error = self.data[i] if isinstance(error, ValidationError): return next(iter(error)) return error def __reduce_ex__(self, *args, **kwargs): # The `list` reduce function returns an iterator as the fourth element # that is normally used for repopulating. Since we only inherit from # `list` for `isinstance` backward compatibility (Refs #17413) we # nullify this iterator as it would otherwise result in duplicate # entries. (Refs #23594) info = super(UserList, self).__reduce_ex__(*args, **kwargs) return info[:3] + (None, None) # Utilities for time zone support in DateTimeField et al. def from_current_timezone(value): """ When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes. """ if settings.USE_TZ and value is not None and timezone.is_naive(value): current_timezone = timezone.get_current_timezone() try: if timezone._datetime_ambiguous_or_imaginary(value, current_timezone): raise ValueError("Ambiguous or non-existent time.") return timezone.make_aware(value, current_timezone) except Exception as exc: raise ValidationError( _( "%(datetime)s couldn’t be interpreted " "in time zone %(current_timezone)s; it " "may be ambiguous or it may not exist." ), code="ambiguous_timezone", params={"datetime": value, "current_timezone": current_timezone}, ) from exc return value def to_current_timezone(value): """ When time zone support is enabled, convert aware datetimes to naive datetimes in the current time zone for display. """ if settings.USE_TZ and value is not None and timezone.is_aware(value): return timezone.make_naive(value) return value
246c8912eeb5ec8fafde8b993800e2eb79c9efca9d9d93a4e6af955a62f46fc7
import functools import warnings from pathlib import Path from django.conf import settings from django.template.backends.django import DjangoTemplates from django.template.loader import get_template from django.utils.deprecation import RemovedInDjango60Warning from django.utils.functional import cached_property from django.utils.module_loading import import_string @functools.lru_cache def get_default_renderer(): renderer_class = import_string(settings.FORM_RENDERER) return renderer_class() class BaseRenderer: form_template_name = "django/forms/div.html" formset_template_name = "django/forms/formsets/div.html" field_template_name = "django/forms/field.html" def get_template(self, template_name): raise NotImplementedError("subclasses must implement get_template()") def render(self, template_name, context, request=None): template = self.get_template(template_name) return template.render(context, request=request).strip() class EngineMixin: def get_template(self, template_name): return self.engine.get_template(template_name) @cached_property def engine(self): return self.backend( { "APP_DIRS": True, "DIRS": [Path(__file__).parent / self.backend.app_dirname], "NAME": "djangoforms", "OPTIONS": {}, } ) class DjangoTemplates(EngineMixin, BaseRenderer): """ Load Django templates from the built-in widget templates in django/forms/templates and from apps' 'templates' directory. """ backend = DjangoTemplates class Jinja2(EngineMixin, BaseRenderer): """ Load Jinja2 templates from the built-in widget templates in django/forms/jinja2 and from apps' 'jinja2' directory. """ @cached_property def backend(self): from django.template.backends.jinja2 import Jinja2 return Jinja2 # RemovedInDjango60Warning. class DjangoDivFormRenderer(DjangoTemplates): """ Load Django templates from django/forms/templates and from apps' 'templates' directory and use the 'div.html' template to render forms and formsets. """ def __init__(self, *args, **kwargs): warnings.warn( "The DjangoDivFormRenderer transitional form renderer is deprecated. Use " "DjangoTemplates instead.", RemovedInDjango60Warning, ) super.__init__(*args, **kwargs) # RemovedInDjango60Warning. class Jinja2DivFormRenderer(Jinja2): """ Load Jinja2 templates from the built-in widget templates in django/forms/jinja2 and from apps' 'jinja2' directory. """ def __init__(self, *args, **kwargs): warnings.warn( "The Jinja2DivFormRenderer transitional form renderer is deprecated. Use " "Jinja2 instead.", RemovedInDjango60Warning, ) super.__init__(*args, **kwargs) class TemplatesSetting(BaseRenderer): """ Load templates using template.loader.get_template() which is configured based on settings.TEMPLATES. """ def get_template(self, template_name): return get_template(template_name)
5acc328b335f1b11648d69dfad35141bfea771eecb9f6e68834a7b97da647c66
import datetime import io import json import mimetypes import os import re import sys import time import warnings from email.header import Header from http.client import responses from urllib.parse import urlparse from asgiref.sync import async_to_sync, sync_to_async from django.conf import settings from django.core import signals, signing from django.core.exceptions import DisallowedRedirect from django.core.serializers.json import DjangoJSONEncoder from django.http.cookie import SimpleCookie from django.utils import timezone from django.utils.datastructures import CaseInsensitiveMapping from django.utils.encoding import iri_to_uri from django.utils.http import content_disposition_header, http_date from django.utils.regex_helper import _lazy_re_compile _charset_from_content_type_re = _lazy_re_compile( r";\s*charset=(?P<charset>[^\s;]+)", re.I ) class ResponseHeaders(CaseInsensitiveMapping): def __init__(self, data): """ Populate the initial data using __setitem__ to ensure values are correctly encoded. """ self._store = {} if data: for header, value in self._unpack_items(data): self[header] = value def _convert_to_charset(self, value, charset, mime_encode=False): """ Convert headers key/value to ascii/latin-1 native strings. `charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and `value` can't be represented in the given charset, apply MIME-encoding. """ try: if isinstance(value, str): # Ensure string is valid in given charset value.encode(charset) elif isinstance(value, bytes): # Convert bytestring using given charset value = value.decode(charset) else: value = str(value) # Ensure string is valid in given charset. value.encode(charset) if "\n" in value or "\r" in value: raise BadHeaderError( f"Header values can't contain newlines (got {value!r})" ) except UnicodeError as e: # Encoding to a string of the specified charset failed, but we # don't know what type that value was, or if it contains newlines, # which we may need to check for before sending it to be # encoded for multiple character sets. if (isinstance(value, bytes) and (b"\n" in value or b"\r" in value)) or ( isinstance(value, str) and ("\n" in value or "\r" in value) ): raise BadHeaderError( f"Header values can't contain newlines (got {value!r})" ) from e if mime_encode: value = Header(value, "utf-8", maxlinelen=sys.maxsize).encode() else: e.reason += ", HTTP response headers must be in %s format" % charset raise return value def __delitem__(self, key): self.pop(key) def __setitem__(self, key, value): key = self._convert_to_charset(key, "ascii") value = self._convert_to_charset(value, "latin-1", mime_encode=True) self._store[key.lower()] = (key, value) def pop(self, key, default=None): return self._store.pop(key.lower(), default) def setdefault(self, key, value): if key not in self: self[key] = value class BadHeaderError(ValueError): pass class HttpResponseBase: """ An HTTP response base class with dictionary-accessed headers. This class doesn't handle content. It should not be used directly. Use the HttpResponse and StreamingHttpResponse subclasses instead. """ status_code = 200 def __init__( self, content_type=None, status=None, reason=None, charset=None, headers=None ): self.headers = ResponseHeaders(headers) self._charset = charset if "Content-Type" not in self.headers: if content_type is None: content_type = f"text/html; charset={self.charset}" self.headers["Content-Type"] = content_type elif content_type: raise ValueError( "'headers' must not contain 'Content-Type' when the " "'content_type' parameter is provided." ) self._resource_closers = [] # This parameter is set by the handler. It's necessary to preserve the # historical behavior of request_finished. self._handler_class = None self.cookies = SimpleCookie() self.closed = False if status is not None: try: self.status_code = int(status) except (ValueError, TypeError): raise TypeError("HTTP status code must be an integer.") if not 100 <= self.status_code <= 599: raise ValueError("HTTP status code must be an integer from 100 to 599.") self._reason_phrase = reason @property def reason_phrase(self): if self._reason_phrase is not None: return self._reason_phrase # Leave self._reason_phrase unset in order to use the default # reason phrase for status code. return responses.get(self.status_code, "Unknown Status Code") @reason_phrase.setter def reason_phrase(self, value): self._reason_phrase = value @property def charset(self): if self._charset is not None: return self._charset # The Content-Type header may not yet be set, because the charset is # being inserted *into* it. if content_type := self.headers.get("Content-Type"): if matched := _charset_from_content_type_re.search(content_type): # Extract the charset and strip its double quotes. # Note that having parsed it from the Content-Type, we don't # store it back into the _charset for later intentionally, to # allow for the Content-Type to be switched again later. return matched["charset"].replace('"', "") return settings.DEFAULT_CHARSET @charset.setter def charset(self, value): self._charset = value def serialize_headers(self): """HTTP headers as a bytestring.""" return b"\r\n".join( [ key.encode("ascii") + b": " + value.encode("latin-1") for key, value in self.headers.items() ] ) __bytes__ = serialize_headers @property def _content_type_for_repr(self): return ( ', "%s"' % self.headers["Content-Type"] if "Content-Type" in self.headers else "" ) def __setitem__(self, header, value): self.headers[header] = value def __delitem__(self, header): del self.headers[header] def __getitem__(self, header): return self.headers[header] def has_header(self, header): """Case-insensitive check for a header.""" return header in self.headers __contains__ = has_header def items(self): return self.headers.items() def get(self, header, alternate=None): return self.headers.get(header, alternate) def set_cookie( self, key, value="", max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite=None, ): """ Set a cookie. ``expires`` can be: - a string in the correct format, - a naive ``datetime.datetime`` object in UTC, - an aware ``datetime.datetime`` object in any time zone. If it is a ``datetime.datetime`` object then calculate ``max_age``. ``max_age`` can be: - int/float specifying seconds, - ``datetime.timedelta`` object. """ self.cookies[key] = value if expires is not None: if isinstance(expires, datetime.datetime): if timezone.is_naive(expires): expires = timezone.make_aware(expires, datetime.timezone.utc) delta = expires - datetime.datetime.now(tz=datetime.timezone.utc) # Add one second so the date matches exactly (a fraction of # time gets lost between converting to a timedelta and # then the date string). delta += datetime.timedelta(seconds=1) # Just set max_age - the max_age logic will set expires. expires = None if max_age is not None: raise ValueError("'expires' and 'max_age' can't be used together.") max_age = max(0, delta.days * 86400 + delta.seconds) else: self.cookies[key]["expires"] = expires else: self.cookies[key]["expires"] = "" if max_age is not None: if isinstance(max_age, datetime.timedelta): max_age = max_age.total_seconds() self.cookies[key]["max-age"] = int(max_age) # IE requires expires, so set it if hasn't been already. if not expires: self.cookies[key]["expires"] = http_date(time.time() + max_age) if path is not None: self.cookies[key]["path"] = path if domain is not None: self.cookies[key]["domain"] = domain if secure: self.cookies[key]["secure"] = True if httponly: self.cookies[key]["httponly"] = True if samesite: if samesite.lower() not in ("lax", "none", "strict"): raise ValueError('samesite must be "lax", "none", or "strict".') self.cookies[key]["samesite"] = samesite def setdefault(self, key, value): """Set a header unless it has already been set.""" self.headers.setdefault(key, value) def set_signed_cookie(self, key, value, salt="", **kwargs): value = signing.get_cookie_signer(salt=key + salt).sign(value) return self.set_cookie(key, value, **kwargs) def delete_cookie(self, key, path="/", domain=None, samesite=None): # Browsers can ignore the Set-Cookie header if the cookie doesn't use # the secure flag and: # - the cookie name starts with "__Host-" or "__Secure-", or # - the samesite is "none". secure = key.startswith(("__Secure-", "__Host-")) or ( samesite and samesite.lower() == "none" ) self.set_cookie( key, max_age=0, path=path, domain=domain, secure=secure, expires="Thu, 01 Jan 1970 00:00:00 GMT", samesite=samesite, ) # Common methods used by subclasses def make_bytes(self, value): """Turn a value into a bytestring encoded in the output charset.""" # Per PEP 3333, this response body must be bytes. To avoid returning # an instance of a subclass, this function returns `bytes(value)`. # This doesn't make a copy when `value` already contains bytes. # Handle string types -- we can't rely on force_bytes here because: # - Python attempts str conversion first # - when self._charset != 'utf-8' it re-encodes the content if isinstance(value, (bytes, memoryview)): return bytes(value) if isinstance(value, str): return bytes(value.encode(self.charset)) # Handle non-string types. return str(value).encode(self.charset) # These methods partially implement the file-like object interface. # See https://docs.python.org/library/io.html#io.IOBase # The WSGI server must call this method upon completion of the request. # See http://blog.dscpl.com.au/2012/10/obligations-for-calling-close-on.html def close(self): for closer in self._resource_closers: try: closer() except Exception: pass # Free resources that were still referenced. self._resource_closers.clear() self.closed = True signals.request_finished.send(sender=self._handler_class) def write(self, content): raise OSError("This %s instance is not writable" % self.__class__.__name__) def flush(self): pass def tell(self): raise OSError( "This %s instance cannot tell its position" % self.__class__.__name__ ) # These methods partially implement a stream-like object interface. # See https://docs.python.org/library/io.html#io.IOBase def readable(self): return False def seekable(self): return False def writable(self): return False def writelines(self, lines): raise OSError("This %s instance is not writable" % self.__class__.__name__) class HttpResponse(HttpResponseBase): """ An HTTP response class with a string as content. This content can be read, appended to, or replaced. """ streaming = False non_picklable_attrs = frozenset( [ "resolver_match", # Non-picklable attributes added by test clients. "client", "context", "json", "templates", ] ) def __init__(self, content=b"", *args, **kwargs): super().__init__(*args, **kwargs) # Content is a bytestring. See the `content` property methods. self.content = content def __getstate__(self): obj_dict = self.__dict__.copy() for attr in self.non_picklable_attrs: if attr in obj_dict: del obj_dict[attr] return obj_dict def __repr__(self): return "<%(cls)s status_code=%(status_code)d%(content_type)s>" % { "cls": self.__class__.__name__, "status_code": self.status_code, "content_type": self._content_type_for_repr, } def serialize(self): """Full HTTP message, including headers, as a bytestring.""" return self.serialize_headers() + b"\r\n\r\n" + self.content __bytes__ = serialize @property def content(self): return b"".join(self._container) @content.setter def content(self, value): # Consume iterators upon assignment to allow repeated iteration. if hasattr(value, "__iter__") and not isinstance( value, (bytes, memoryview, str) ): content = b"".join(self.make_bytes(chunk) for chunk in value) if hasattr(value, "close"): try: value.close() except Exception: pass else: content = self.make_bytes(value) # Create a list of properly encoded bytestrings to support write(). self._container = [content] def __iter__(self): return iter(self._container) def write(self, content): self._container.append(self.make_bytes(content)) def tell(self): return len(self.content) def getvalue(self): return self.content def writable(self): return True def writelines(self, lines): for line in lines: self.write(line) class StreamingHttpResponse(HttpResponseBase): """ A streaming HTTP response class with an iterator as content. This should only be iterated once, when the response is streamed to the client. However, it can be appended to or replaced with a new iterator that wraps the original content (or yields entirely new content). """ streaming = True def __init__(self, streaming_content=(), *args, **kwargs): super().__init__(*args, **kwargs) # `streaming_content` should be an iterable of bytestrings. # See the `streaming_content` property methods. self.streaming_content = streaming_content def __repr__(self): return "<%(cls)s status_code=%(status_code)d%(content_type)s>" % { "cls": self.__class__.__qualname__, "status_code": self.status_code, "content_type": self._content_type_for_repr, } @property def content(self): raise AttributeError( "This %s instance has no `content` attribute. Use " "`streaming_content` instead." % self.__class__.__name__ ) @property def streaming_content(self): if self.is_async: # pull to lexical scope to capture fixed reference in case # streaming_content is set again later. _iterator = self._iterator async def awrapper(): async for part in _iterator: yield self.make_bytes(part) return awrapper() else: return map(self.make_bytes, self._iterator) @streaming_content.setter def streaming_content(self, value): self._set_streaming_content(value) def _set_streaming_content(self, value): # Ensure we can never iterate on "value" more than once. try: self._iterator = iter(value) self.is_async = False except TypeError: self._iterator = aiter(value) self.is_async = True if hasattr(value, "close"): self._resource_closers.append(value.close) def __iter__(self): try: return iter(self.streaming_content) except TypeError: warnings.warn( "StreamingHttpResponse must consume asynchronous iterators in order to " "serve them synchronously. Use a synchronous iterator instead.", Warning, ) # async iterator. Consume in async_to_sync and map back. async def to_list(_iterator): as_list = [] async for chunk in _iterator: as_list.append(chunk) return as_list return map(self.make_bytes, iter(async_to_sync(to_list)(self._iterator))) async def __aiter__(self): try: async for part in self.streaming_content: yield part except TypeError: warnings.warn( "StreamingHttpResponse must consume synchronous iterators in order to " "serve them asynchronously. Use an asynchronous iterator instead.", Warning, ) # sync iterator. Consume via sync_to_async and yield via async # generator. for part in await sync_to_async(list)(self.streaming_content): yield part def getvalue(self): return b"".join(self.streaming_content) class FileResponse(StreamingHttpResponse): """ A streaming HTTP response class optimized for files. """ block_size = 4096 def __init__(self, *args, as_attachment=False, filename="", **kwargs): self.as_attachment = as_attachment self.filename = filename self._no_explicit_content_type = ( "content_type" not in kwargs or kwargs["content_type"] is None ) super().__init__(*args, **kwargs) def _set_streaming_content(self, value): if not hasattr(value, "read"): self.file_to_stream = None return super()._set_streaming_content(value) self.file_to_stream = filelike = value if hasattr(filelike, "close"): self._resource_closers.append(filelike.close) value = iter(lambda: filelike.read(self.block_size), b"") self.set_headers(filelike) super()._set_streaming_content(value) def set_headers(self, filelike): """ Set some common response headers (Content-Length, Content-Type, and Content-Disposition) based on the `filelike` response content. """ filename = getattr(filelike, "name", "") filename = filename if isinstance(filename, str) else "" seekable = hasattr(filelike, "seek") and ( not hasattr(filelike, "seekable") or filelike.seekable() ) if hasattr(filelike, "tell"): if seekable: initial_position = filelike.tell() filelike.seek(0, io.SEEK_END) self.headers["Content-Length"] = filelike.tell() - initial_position filelike.seek(initial_position) elif hasattr(filelike, "getbuffer"): self.headers["Content-Length"] = ( filelike.getbuffer().nbytes - filelike.tell() ) elif os.path.exists(filename): self.headers["Content-Length"] = ( os.path.getsize(filename) - filelike.tell() ) elif seekable: self.headers["Content-Length"] = sum( iter(lambda: len(filelike.read(self.block_size)), 0) ) filelike.seek(-int(self.headers["Content-Length"]), io.SEEK_END) filename = os.path.basename(self.filename or filename) if self._no_explicit_content_type: if filename: content_type, encoding = mimetypes.guess_type(filename) # Encoding isn't set to prevent browsers from automatically # uncompressing files. content_type = { "br": "application/x-brotli", "bzip2": "application/x-bzip", "compress": "application/x-compress", "gzip": "application/gzip", "xz": "application/x-xz", }.get(encoding, content_type) self.headers["Content-Type"] = ( content_type or "application/octet-stream" ) else: self.headers["Content-Type"] = "application/octet-stream" if content_disposition := content_disposition_header( self.as_attachment, filename ): self.headers["Content-Disposition"] = content_disposition class HttpResponseRedirectBase(HttpResponse): allowed_schemes = ["http", "https", "ftp"] def __init__(self, redirect_to, *args, **kwargs): super().__init__(*args, **kwargs) self["Location"] = iri_to_uri(redirect_to) parsed = urlparse(str(redirect_to)) if parsed.scheme and parsed.scheme not in self.allowed_schemes: raise DisallowedRedirect( "Unsafe redirect to URL with protocol '%s'" % parsed.scheme ) url = property(lambda self: self["Location"]) def __repr__(self): return ( '<%(cls)s status_code=%(status_code)d%(content_type)s, url="%(url)s">' % { "cls": self.__class__.__name__, "status_code": self.status_code, "content_type": self._content_type_for_repr, "url": self.url, } ) class HttpResponseRedirect(HttpResponseRedirectBase): status_code = 302 class HttpResponsePermanentRedirect(HttpResponseRedirectBase): status_code = 301 class HttpResponseNotModified(HttpResponse): status_code = 304 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self["content-type"] @HttpResponse.content.setter def content(self, value): if value: raise AttributeError( "You cannot set content to a 304 (Not Modified) response" ) self._container = [] class HttpResponseBadRequest(HttpResponse): status_code = 400 class HttpResponseNotFound(HttpResponse): status_code = 404 class HttpResponseForbidden(HttpResponse): status_code = 403 class HttpResponseNotAllowed(HttpResponse): status_code = 405 def __init__(self, permitted_methods, *args, **kwargs): super().__init__(*args, **kwargs) self["Allow"] = ", ".join(permitted_methods) def __repr__(self): return "<%(cls)s [%(methods)s] status_code=%(status_code)d%(content_type)s>" % { "cls": self.__class__.__name__, "status_code": self.status_code, "content_type": self._content_type_for_repr, "methods": self["Allow"], } class HttpResponseGone(HttpResponse): status_code = 410 class HttpResponseServerError(HttpResponse): status_code = 500 class Http404(Exception): pass class JsonResponse(HttpResponse): """ An HTTP response class that consumes data to be serialized to JSON. :param data: Data to be dumped into json. By default only ``dict`` objects are allowed to be passed due to a security flaw before ECMAScript 5. See the ``safe`` parameter for more information. :param encoder: Should be a json encoder class. Defaults to ``django.core.serializers.json.DjangoJSONEncoder``. :param safe: Controls if only ``dict`` objects may be serialized. Defaults to ``True``. :param json_dumps_params: A dictionary of kwargs passed to json.dumps(). """ def __init__( self, data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs, ): if safe and not isinstance(data, dict): raise TypeError( "In order to allow non-dict objects to be serialized set the " "safe parameter to False." ) if json_dumps_params is None: json_dumps_params = {} kwargs.setdefault("content_type", "application/json") data = json.dumps(data, cls=encoder, **json_dumps_params) super().__init__(content=data, **kwargs)
8ff75fda6d9073b5f53c3bb4a7689aa7fa168b733ec7f55c48d29f83db02c2ff
from functools import wraps from asgiref.sync import iscoroutinefunction from django.http import HttpRequest def sensitive_variables(*variables): """ Indicate which variables used in the decorated function are sensitive so that those variables can later be treated in a special way, for example by hiding them when logging unhandled exceptions. Accept two forms: * with specified variable names: @sensitive_variables('user', 'password', 'credit_card') def my_function(user): password = user.pass_word credit_card = user.credit_card_number ... * without any specified variable names, in which case consider all variables are sensitive: @sensitive_variables() def my_function() ... """ if len(variables) == 1 and callable(variables[0]): raise TypeError( "sensitive_variables() must be called to use it as a decorator, " "e.g., use @sensitive_variables(), not @sensitive_variables." ) def decorator(func): if iscoroutinefunction(func): @wraps(func) async def sensitive_variables_wrapper(*func_args, **func_kwargs): if variables: sensitive_variables_wrapper.sensitive_variables = variables else: sensitive_variables_wrapper.sensitive_variables = "__ALL__" return await func(*func_args, **func_kwargs) else: @wraps(func) def sensitive_variables_wrapper(*func_args, **func_kwargs): if variables: sensitive_variables_wrapper.sensitive_variables = variables else: sensitive_variables_wrapper.sensitive_variables = "__ALL__" return func(*func_args, **func_kwargs) return sensitive_variables_wrapper return decorator def sensitive_post_parameters(*parameters): """ Indicate which POST parameters used in the decorated view are sensitive, so that those parameters can later be treated in a special way, for example by hiding them when logging unhandled exceptions. Accept two forms: * with specified parameters: @sensitive_post_parameters('password', 'credit_card') def my_view(request): pw = request.POST['password'] cc = request.POST['credit_card'] ... * without any specified parameters, in which case consider all variables are sensitive: @sensitive_post_parameters() def my_view(request) ... """ if len(parameters) == 1 and callable(parameters[0]): raise TypeError( "sensitive_post_parameters() must be called to use it as a " "decorator, e.g., use @sensitive_post_parameters(), not " "@sensitive_post_parameters." ) def decorator(view): if iscoroutinefunction(view): @wraps(view) async def sensitive_post_parameters_wrapper(request, *args, **kwargs): if not isinstance(request, HttpRequest): raise TypeError( "sensitive_post_parameters didn't receive an HttpRequest " "object. If you are decorating a classmethod, make sure " "to use @method_decorator." ) if parameters: request.sensitive_post_parameters = parameters else: request.sensitive_post_parameters = "__ALL__" return await view(request, *args, **kwargs) else: @wraps(view) def sensitive_post_parameters_wrapper(request, *args, **kwargs): if not isinstance(request, HttpRequest): raise TypeError( "sensitive_post_parameters didn't receive an HttpRequest " "object. If you are decorating a classmethod, make sure " "to use @method_decorator." ) if parameters: request.sensitive_post_parameters = parameters else: request.sensitive_post_parameters = "__ALL__" return view(request, *args, **kwargs) return sensitive_post_parameters_wrapper return decorator
b1c32456f050e55fe093c6c3e1b72edfd0277bba65410a85de7a60b1d8400da6
import os import re from importlib import import_module from django import get_version from django.apps import apps # SettingsReference imported for backwards compatibility in Django 2.2. from django.conf import SettingsReference # NOQA from django.db import migrations from django.db.migrations.loader import MigrationLoader from django.db.migrations.serializer import Serializer, serializer_factory from django.utils.inspect import get_func_args from django.utils.module_loading import module_dir from django.utils.timezone import now class OperationWriter: def __init__(self, operation, indentation=2): self.operation = operation self.buff = [] self.indentation = indentation def serialize(self): def _write(_arg_name, _arg_value): if _arg_name in self.operation.serialization_expand_args and isinstance( _arg_value, (list, tuple, dict) ): if isinstance(_arg_value, dict): self.feed("%s={" % _arg_name) self.indent() for key, value in _arg_value.items(): key_string, key_imports = MigrationWriter.serialize(key) arg_string, arg_imports = MigrationWriter.serialize(value) args = arg_string.splitlines() if len(args) > 1: self.feed("%s: %s" % (key_string, args[0])) for arg in args[1:-1]: self.feed(arg) self.feed("%s," % args[-1]) else: self.feed("%s: %s," % (key_string, arg_string)) imports.update(key_imports) imports.update(arg_imports) self.unindent() self.feed("},") else: self.feed("%s=[" % _arg_name) self.indent() for item in _arg_value: arg_string, arg_imports = MigrationWriter.serialize(item) args = arg_string.splitlines() if len(args) > 1: for arg in args[:-1]: self.feed(arg) self.feed("%s," % args[-1]) else: self.feed("%s," % arg_string) imports.update(arg_imports) self.unindent() self.feed("],") else: arg_string, arg_imports = MigrationWriter.serialize(_arg_value) args = arg_string.splitlines() if len(args) > 1: self.feed("%s=%s" % (_arg_name, args[0])) for arg in args[1:-1]: self.feed(arg) self.feed("%s," % args[-1]) else: self.feed("%s=%s," % (_arg_name, arg_string)) imports.update(arg_imports) imports = set() name, args, kwargs = self.operation.deconstruct() operation_args = get_func_args(self.operation.__init__) # See if this operation is in django.db.migrations. If it is, # We can just use the fact we already have that imported, # otherwise, we need to add an import for the operation class. if getattr(migrations, name, None) == self.operation.__class__: self.feed("migrations.%s(" % name) else: imports.add("import %s" % (self.operation.__class__.__module__)) self.feed("%s.%s(" % (self.operation.__class__.__module__, name)) self.indent() for i, arg in enumerate(args): arg_value = arg arg_name = operation_args[i] _write(arg_name, arg_value) i = len(args) # Only iterate over remaining arguments for arg_name in operation_args[i:]: if arg_name in kwargs: # Don't sort to maintain signature order arg_value = kwargs[arg_name] _write(arg_name, arg_value) self.unindent() self.feed("),") return self.render(), imports def indent(self): self.indentation += 1 def unindent(self): self.indentation -= 1 def feed(self, line): self.buff.append(" " * (self.indentation * 4) + line) def render(self): return "\n".join(self.buff) class MigrationWriter: """ Take a Migration instance and is able to produce the contents of the migration file from it. """ def __init__(self, migration, include_header=True): self.migration = migration self.include_header = include_header self.needs_manual_porting = False def as_string(self): """Return a string of the file contents.""" items = { "replaces_str": "", "initial_str": "", } imports = set() # Deconstruct operations operations = [] for operation in self.migration.operations: operation_string, operation_imports = OperationWriter(operation).serialize() imports.update(operation_imports) operations.append(operation_string) items["operations"] = "\n".join(operations) + "\n" if operations else "" # Format dependencies and write out swappable dependencies right dependencies = [] for dependency in self.migration.dependencies: if dependency[0] == "__setting__": dependencies.append( " migrations.swappable_dependency(settings.%s)," % dependency[1] ) imports.add("from django.conf import settings") else: dependencies.append(" %s," % self.serialize(dependency)[0]) items["dependencies"] = "\n".join(dependencies) + "\n" if dependencies else "" # Format imports nicely, swapping imports of functions from migration files # for comments migration_imports = set() for line in list(imports): if re.match(r"^import (.*)\.\d+[^\s]*$", line): migration_imports.add(line.split("import")[1].strip()) imports.remove(line) self.needs_manual_porting = True # django.db.migrations is always used, but models import may not be. # If models import exists, merge it with migrations import. if "from django.db import models" in imports: imports.discard("from django.db import models") imports.add("from django.db import migrations, models") else: imports.add("from django.db import migrations") # Sort imports by the package / module to be imported (the part after # "from" in "from ... import ..." or after "import" in "import ..."). # First group the "import" statements, then "from ... import ...". sorted_imports = sorted( imports, key=lambda i: (i.split()[0] == "from", i.split()[1]) ) items["imports"] = "\n".join(sorted_imports) + "\n" if imports else "" if migration_imports: items["imports"] += ( "\n\n# Functions from the following migrations need manual " "copying.\n# Move them and any dependencies into this file, " "then update the\n# RunPython operations to refer to the local " "versions:\n# %s" ) % "\n# ".join(sorted(migration_imports)) # If there's a replaces, make a string for it if self.migration.replaces: items["replaces_str"] = ( "\n replaces = %s\n" % self.serialize(self.migration.replaces)[0] ) # Hinting that goes into comment if self.include_header: items["migration_header"] = MIGRATION_HEADER_TEMPLATE % { "version": get_version(), "timestamp": now().strftime("%Y-%m-%d %H:%M"), } else: items["migration_header"] = "" if self.migration.initial: items["initial_str"] = "\n initial = True\n" return MIGRATION_TEMPLATE % items @property def basedir(self): migrations_package_name, _ = MigrationLoader.migrations_module( self.migration.app_label ) if migrations_package_name is None: raise ValueError( "Django can't create migrations for app '%s' because " "migrations have been disabled via the MIGRATION_MODULES " "setting." % self.migration.app_label ) # See if we can import the migrations module directly try: migrations_module = import_module(migrations_package_name) except ImportError: pass else: try: return module_dir(migrations_module) except ValueError: pass # Alright, see if it's a direct submodule of the app app_config = apps.get_app_config(self.migration.app_label) ( maybe_app_name, _, migrations_package_basename, ) = migrations_package_name.rpartition(".") if app_config.name == maybe_app_name: return os.path.join(app_config.path, migrations_package_basename) # In case of using MIGRATION_MODULES setting and the custom package # doesn't exist, create one, starting from an existing package existing_dirs, missing_dirs = migrations_package_name.split("."), [] while existing_dirs: missing_dirs.insert(0, existing_dirs.pop(-1)) try: base_module = import_module(".".join(existing_dirs)) except (ImportError, ValueError): continue else: try: base_dir = module_dir(base_module) except ValueError: continue else: break else: raise ValueError( "Could not locate an appropriate location to create " "migrations package %s. Make sure the toplevel " "package exists and can be imported." % migrations_package_name ) final_dir = os.path.join(base_dir, *missing_dirs) os.makedirs(final_dir, exist_ok=True) for missing_dir in missing_dirs: base_dir = os.path.join(base_dir, missing_dir) with open(os.path.join(base_dir, "__init__.py"), "w"): pass return final_dir @property def filename(self): return "%s.py" % self.migration.name @property def path(self): return os.path.join(self.basedir, self.filename) @classmethod def serialize(cls, value): return serializer_factory(value).serialize() @classmethod def register_serializer(cls, type_, serializer): Serializer.register(type_, serializer) @classmethod def unregister_serializer(cls, type_): Serializer.unregister(type_) MIGRATION_HEADER_TEMPLATE = """\ # Generated by Django %(version)s on %(timestamp)s """ MIGRATION_TEMPLATE = """\ %(migration_header)s%(imports)s class Migration(migrations.Migration): %(replaces_str)s%(initial_str)s dependencies = [ %(dependencies)s\ ] operations = [ %(operations)s\ ] """
78131a4138f39a7697c243ccf7e376b353f14cc52e830830f9d52d77b1689882
""" The main QuerySet implementation. This provides the public API for the ORM. """ import copy import operator import warnings from itertools import chain, islice from asgiref.sync import sync_to_async import django from django.conf import settings from django.core import exceptions from django.db import ( DJANGO_VERSION_PICKLE_KEY, IntegrityError, NotSupportedError, connections, router, transaction, ) from django.db.models import AutoField, DateField, DateTimeField, Field, sql from django.db.models.constants import LOOKUP_SEP, OnConflict from django.db.models.deletion import Collector from django.db.models.expressions import Case, F, Value, When from django.db.models.functions import Cast, Trunc from django.db.models.query_utils import FilteredRelation, Q from django.db.models.sql.constants import CURSOR, GET_ITERATOR_CHUNK_SIZE from django.db.models.utils import ( AltersData, create_namedtuple_class, resolve_callables, ) from django.utils import timezone from django.utils.functional import cached_property, partition # The maximum number of results to fetch in a get() query. MAX_GET_RESULTS = 21 # The maximum number of items to display in a QuerySet.__repr__ REPR_OUTPUT_SIZE = 20 class BaseIterable: def __init__( self, queryset, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE ): self.queryset = queryset self.chunked_fetch = chunked_fetch self.chunk_size = chunk_size async def _async_generator(self): # Generators don't actually start running until the first time you call # next() on them, so make the generator object in the async thread and # then repeatedly dispatch to it in a sync thread. sync_generator = self.__iter__() def next_slice(gen): return list(islice(gen, self.chunk_size)) while True: chunk = await sync_to_async(next_slice)(sync_generator) for item in chunk: yield item if len(chunk) < self.chunk_size: break # __aiter__() is a *synchronous* method that has to then return an # *asynchronous* iterator/generator. Thus, nest an async generator inside # it. # This is a generic iterable converter for now, and is going to suffer a # performance penalty on large sets of items due to the cost of crossing # over the sync barrier for each chunk. Custom __aiter__() methods should # be added to each Iterable subclass, but that needs some work in the # Compiler first. def __aiter__(self): return self._async_generator() class ModelIterable(BaseIterable): """Iterable that yields a model instance for each row.""" def __iter__(self): queryset = self.queryset db = queryset.db compiler = queryset.query.get_compiler(using=db) # Execute the query. This will also fill compiler.select, klass_info, # and annotations. results = compiler.execute_sql( chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size ) select, klass_info, annotation_col_map = ( compiler.select, compiler.klass_info, compiler.annotation_col_map, ) model_cls = klass_info["model"] select_fields = klass_info["select_fields"] model_fields_start, model_fields_end = select_fields[0], select_fields[-1] + 1 init_list = [ f[0].target.attname for f in select[model_fields_start:model_fields_end] ] related_populators = get_related_populators(klass_info, select, db) known_related_objects = [ ( field, related_objs, operator.attrgetter( *[ field.attname if from_field == "self" else queryset.model._meta.get_field(from_field).attname for from_field in field.from_fields ] ), ) for field, related_objs in queryset._known_related_objects.items() ] for row in compiler.results_iter(results): obj = model_cls.from_db( db, init_list, row[model_fields_start:model_fields_end] ) for rel_populator in related_populators: rel_populator.populate(row, obj) if annotation_col_map: for attr_name, col_pos in annotation_col_map.items(): setattr(obj, attr_name, row[col_pos]) # Add the known related objects to the model. for field, rel_objs, rel_getter in known_related_objects: # Avoid overwriting objects loaded by, e.g., select_related(). if field.is_cached(obj): continue rel_obj_id = rel_getter(obj) try: rel_obj = rel_objs[rel_obj_id] except KeyError: pass # May happen in qs1 | qs2 scenarios. else: setattr(obj, field.name, rel_obj) yield obj class RawModelIterable(BaseIterable): """ Iterable that yields a model instance for each row from a raw queryset. """ def __iter__(self): # Cache some things for performance reasons outside the loop. db = self.queryset.db query = self.queryset.query connection = connections[db] compiler = connection.ops.compiler("SQLCompiler")(query, connection, db) query_iterator = iter(query) try: ( model_init_names, model_init_pos, annotation_fields, ) = self.queryset.resolve_model_init_order() model_cls = self.queryset.model if model_cls._meta.pk.attname not in model_init_names: raise exceptions.FieldDoesNotExist( "Raw query must include the primary key" ) fields = [self.queryset.model_fields.get(c) for c in self.queryset.columns] converters = compiler.get_converters( [f.get_col(f.model._meta.db_table) if f else None for f in fields] ) if converters: query_iterator = compiler.apply_converters(query_iterator, converters) for values in query_iterator: # Associate fields to values model_init_values = [values[pos] for pos in model_init_pos] instance = model_cls.from_db(db, model_init_names, model_init_values) if annotation_fields: for column, pos in annotation_fields: setattr(instance, column, values[pos]) yield instance finally: # Done iterating the Query. If it has its own cursor, close it. if hasattr(query, "cursor") and query.cursor: query.cursor.close() class ValuesIterable(BaseIterable): """ Iterable returned by QuerySet.values() that yields a dict for each row. """ def __iter__(self): queryset = self.queryset query = queryset.query compiler = query.get_compiler(queryset.db) # extra(select=...) cols are always at the start of the row. names = [ *query.extra_select, *query.values_select, *query.annotation_select, ] indexes = range(len(names)) for row in compiler.results_iter( chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size ): yield {names[i]: row[i] for i in indexes} class ValuesListIterable(BaseIterable): """ Iterable returned by QuerySet.values_list(flat=False) that yields a tuple for each row. """ def __iter__(self): queryset = self.queryset query = queryset.query compiler = query.get_compiler(queryset.db) if queryset._fields: # extra(select=...) cols are always at the start of the row. names = [ *query.extra_select, *query.values_select, *query.annotation_select, ] fields = [ *queryset._fields, *(f for f in query.annotation_select if f not in queryset._fields), ] if fields != names: # Reorder according to fields. index_map = {name: idx for idx, name in enumerate(names)} rowfactory = operator.itemgetter(*[index_map[f] for f in fields]) return map( rowfactory, compiler.results_iter( chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size ), ) return compiler.results_iter( tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size, ) class NamedValuesListIterable(ValuesListIterable): """ Iterable returned by QuerySet.values_list(named=True) that yields a namedtuple for each row. """ def __iter__(self): queryset = self.queryset if queryset._fields: names = queryset._fields else: query = queryset.query names = [ *query.extra_select, *query.values_select, *query.annotation_select, ] tuple_class = create_namedtuple_class(*names) new = tuple.__new__ for row in super().__iter__(): yield new(tuple_class, row) class FlatValuesListIterable(BaseIterable): """ Iterable returned by QuerySet.values_list(flat=True) that yields single values. """ def __iter__(self): queryset = self.queryset compiler = queryset.query.get_compiler(queryset.db) for row in compiler.results_iter( chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size ): yield row[0] class QuerySet(AltersData): """Represent a lazy database lookup for a set of objects.""" def __init__(self, model=None, query=None, using=None, hints=None): self.model = model self._db = using self._hints = hints or {} self._query = query or sql.Query(self.model) self._result_cache = None self._sticky_filter = False self._for_write = False self._prefetch_related_lookups = () self._prefetch_done = False self._known_related_objects = {} # {rel_field: {pk: rel_obj}} self._iterable_class = ModelIterable self._fields = None self._defer_next_filter = False self._deferred_filter = None @property def query(self): if self._deferred_filter: negate, args, kwargs = self._deferred_filter self._filter_or_exclude_inplace(negate, args, kwargs) self._deferred_filter = None return self._query @query.setter def query(self, value): if value.values_select: self._iterable_class = ValuesIterable self._query = value def as_manager(cls): # Address the circular dependency between `Queryset` and `Manager`. from django.db.models.manager import Manager manager = Manager.from_queryset(cls)() manager._built_with_as_manager = True return manager as_manager.queryset_only = True as_manager = classmethod(as_manager) ######################## # PYTHON MAGIC METHODS # ######################## def __deepcopy__(self, memo): """Don't populate the QuerySet's cache.""" obj = self.__class__() for k, v in self.__dict__.items(): if k == "_result_cache": obj.__dict__[k] = None else: obj.__dict__[k] = copy.deepcopy(v, memo) return obj def __getstate__(self): # Force the cache to be fully populated. self._fetch_all() return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__} def __setstate__(self, state): pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY) if pickled_version: if pickled_version != django.__version__: warnings.warn( "Pickled queryset instance's Django version %s does not " "match the current version %s." % (pickled_version, django.__version__), RuntimeWarning, stacklevel=2, ) else: warnings.warn( "Pickled queryset instance's Django version is not specified.", RuntimeWarning, stacklevel=2, ) self.__dict__.update(state) def __repr__(self): data = list(self[: REPR_OUTPUT_SIZE + 1]) if len(data) > REPR_OUTPUT_SIZE: data[-1] = "...(remaining elements truncated)..." return "<%s %r>" % (self.__class__.__name__, data) def __len__(self): self._fetch_all() return len(self._result_cache) def __iter__(self): """ The queryset iterator protocol uses three nested iterators in the default case: 1. sql.compiler.execute_sql() - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE) using cursor.fetchmany(). This part is responsible for doing some column masking, and returning the rows in chunks. 2. sql.compiler.results_iter() - Returns one row at time. At this point the rows are still just tuples. In some cases the return values are converted to Python values at this location. 3. self.iterator() - Responsible for turning the rows into model objects. """ self._fetch_all() return iter(self._result_cache) def __aiter__(self): # Remember, __aiter__ itself is synchronous, it's the thing it returns # that is async! async def generator(): await sync_to_async(self._fetch_all)() for item in self._result_cache: yield item return generator() def __bool__(self): self._fetch_all() return bool(self._result_cache) def __getitem__(self, k): """Retrieve an item or slice from the set of results.""" if not isinstance(k, (int, slice)): raise TypeError( "QuerySet indices must be integers or slices, not %s." % type(k).__name__ ) if (isinstance(k, int) and k < 0) or ( isinstance(k, slice) and ( (k.start is not None and k.start < 0) or (k.stop is not None and k.stop < 0) ) ): raise ValueError("Negative indexing is not supported.") if self._result_cache is not None: return self._result_cache[k] if isinstance(k, slice): qs = self._chain() if k.start is not None: start = int(k.start) else: start = None if k.stop is not None: stop = int(k.stop) else: stop = None qs.query.set_limits(start, stop) return list(qs)[:: k.step] if k.step else qs qs = self._chain() qs.query.set_limits(k, k + 1) qs._fetch_all() return qs._result_cache[0] def __class_getitem__(cls, *args, **kwargs): return cls def __and__(self, other): self._check_operator_queryset(other, "&") self._merge_sanity_check(other) if isinstance(other, EmptyQuerySet): return other if isinstance(self, EmptyQuerySet): return self combined = self._chain() combined._merge_known_related_objects(other) combined.query.combine(other.query, sql.AND) return combined def __or__(self, other): self._check_operator_queryset(other, "|") self._merge_sanity_check(other) if isinstance(self, EmptyQuerySet): return other if isinstance(other, EmptyQuerySet): return self query = ( self if self.query.can_filter() else self.model._base_manager.filter(pk__in=self.values("pk")) ) combined = query._chain() combined._merge_known_related_objects(other) if not other.query.can_filter(): other = other.model._base_manager.filter(pk__in=other.values("pk")) combined.query.combine(other.query, sql.OR) return combined def __xor__(self, other): self._check_operator_queryset(other, "^") self._merge_sanity_check(other) if isinstance(self, EmptyQuerySet): return other if isinstance(other, EmptyQuerySet): return self query = ( self if self.query.can_filter() else self.model._base_manager.filter(pk__in=self.values("pk")) ) combined = query._chain() combined._merge_known_related_objects(other) if not other.query.can_filter(): other = other.model._base_manager.filter(pk__in=other.values("pk")) combined.query.combine(other.query, sql.XOR) return combined #################################### # METHODS THAT DO DATABASE QUERIES # #################################### def _iterator(self, use_chunked_fetch, chunk_size): iterable = self._iterable_class( self, chunked_fetch=use_chunked_fetch, chunk_size=chunk_size or 2000, ) if not self._prefetch_related_lookups or chunk_size is None: yield from iterable return iterator = iter(iterable) while results := list(islice(iterator, chunk_size)): prefetch_related_objects(results, *self._prefetch_related_lookups) yield from results def iterator(self, chunk_size=None): """ An iterator over the results from applying this QuerySet to the database. chunk_size must be provided for QuerySets that prefetch related objects. Otherwise, a default chunk_size of 2000 is supplied. """ if chunk_size is None: if self._prefetch_related_lookups: raise ValueError( "chunk_size must be provided when using QuerySet.iterator() after " "prefetch_related()." ) elif chunk_size <= 0: raise ValueError("Chunk size must be strictly positive.") use_chunked_fetch = not connections[self.db].settings_dict.get( "DISABLE_SERVER_SIDE_CURSORS" ) return self._iterator(use_chunked_fetch, chunk_size) async def aiterator(self, chunk_size=2000): """ An asynchronous iterator over the results from applying this QuerySet to the database. """ if self._prefetch_related_lookups: raise NotSupportedError( "Using QuerySet.aiterator() after prefetch_related() is not supported." ) if chunk_size <= 0: raise ValueError("Chunk size must be strictly positive.") use_chunked_fetch = not connections[self.db].settings_dict.get( "DISABLE_SERVER_SIDE_CURSORS" ) async for item in self._iterable_class( self, chunked_fetch=use_chunked_fetch, chunk_size=chunk_size ): yield item def aggregate(self, *args, **kwargs): """ Return a dictionary containing the calculations (aggregation) over the current queryset. If args is present the expression is passed as a kwarg using the Aggregate object's default alias. """ if self.query.distinct_fields: raise NotImplementedError("aggregate() + distinct(fields) not implemented.") self._validate_values_are_expressions( (*args, *kwargs.values()), method_name="aggregate" ) for arg in args: # The default_alias property raises TypeError if default_alias # can't be set automatically or AttributeError if it isn't an # attribute. try: arg.default_alias except (AttributeError, TypeError): raise TypeError("Complex aggregates require an alias") kwargs[arg.default_alias] = arg return self.query.chain().get_aggregation(self.db, kwargs) async def aaggregate(self, *args, **kwargs): return await sync_to_async(self.aggregate)(*args, **kwargs) def count(self): """ Perform a SELECT COUNT() and return the number of records as an integer. If the QuerySet is already fully cached, return the length of the cached results set to avoid multiple SELECT COUNT(*) calls. """ if self._result_cache is not None: return len(self._result_cache) return self.query.get_count(using=self.db) async def acount(self): return await sync_to_async(self.count)() def get(self, *args, **kwargs): """ Perform the query and return a single object matching the given keyword arguments. """ if self.query.combinator and (args or kwargs): raise NotSupportedError( "Calling QuerySet.get(...) with filters after %s() is not " "supported." % self.query.combinator ) clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) if self.query.can_filter() and not self.query.distinct_fields: clone = clone.order_by() limit = None if ( not clone.query.select_for_update or connections[clone.db].features.supports_select_for_update_with_limit ): limit = MAX_GET_RESULTS clone.query.set_limits(high=limit) num = len(clone) if num == 1: return clone._result_cache[0] if not num: raise self.model.DoesNotExist( "%s matching query does not exist." % self.model._meta.object_name ) raise self.model.MultipleObjectsReturned( "get() returned more than one %s -- it returned %s!" % ( self.model._meta.object_name, num if not limit or num < limit else "more than %s" % (limit - 1), ) ) async def aget(self, *args, **kwargs): return await sync_to_async(self.get)(*args, **kwargs) def create(self, **kwargs): """ Create a new object with the given kwargs, saving it to the database and returning the created object. """ obj = self.model(**kwargs) self._for_write = True obj.save(force_insert=True, using=self.db) return obj async def acreate(self, **kwargs): return await sync_to_async(self.create)(**kwargs) def _prepare_for_bulk_create(self, objs): for obj in objs: if obj.pk is None: # Populate new PK values. obj.pk = obj._meta.pk.get_pk_value_on_save(obj) obj._prepare_related_fields_for_save(operation_name="bulk_create") def _check_bulk_create_options( self, ignore_conflicts, update_conflicts, update_fields, unique_fields ): if ignore_conflicts and update_conflicts: raise ValueError( "ignore_conflicts and update_conflicts are mutually exclusive." ) db_features = connections[self.db].features if ignore_conflicts: if not db_features.supports_ignore_conflicts: raise NotSupportedError( "This database backend does not support ignoring conflicts." ) return OnConflict.IGNORE elif update_conflicts: if not db_features.supports_update_conflicts: raise NotSupportedError( "This database backend does not support updating conflicts." ) if not update_fields: raise ValueError( "Fields that will be updated when a row insertion fails " "on conflicts must be provided." ) if unique_fields and not db_features.supports_update_conflicts_with_target: raise NotSupportedError( "This database backend does not support updating " "conflicts with specifying unique fields that can trigger " "the upsert." ) if not unique_fields and db_features.supports_update_conflicts_with_target: raise ValueError( "Unique fields that can trigger the upsert must be provided." ) # Updating primary keys and non-concrete fields is forbidden. if any(not f.concrete or f.many_to_many for f in update_fields): raise ValueError( "bulk_create() can only be used with concrete fields in " "update_fields." ) if any(f.primary_key for f in update_fields): raise ValueError( "bulk_create() cannot be used with primary keys in " "update_fields." ) if unique_fields: if any(not f.concrete or f.many_to_many for f in unique_fields): raise ValueError( "bulk_create() can only be used with concrete fields " "in unique_fields." ) return OnConflict.UPDATE return None def bulk_create( self, objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None, ): """ Insert each of the instances into the database. Do *not* call save() on each of the instances, do not send any pre/post_save signals, and do not set the primary key attribute if it is an autoincrement field (except if features.can_return_rows_from_bulk_insert=True). Multi-table models are not supported. """ # When you bulk insert you don't get the primary keys back (if it's an # autoincrement, except if can_return_rows_from_bulk_insert=True), so # you can't insert into the child tables which references this. There # are two workarounds: # 1) This could be implemented if you didn't have an autoincrement pk # 2) You could do it by doing O(n) normal inserts into the parent # tables to get the primary keys back and then doing a single bulk # insert into the childmost table. # We currently set the primary keys on the objects when using # PostgreSQL via the RETURNING ID clause. It should be possible for # Oracle as well, but the semantics for extracting the primary keys is # trickier so it's not done yet. if batch_size is not None and batch_size <= 0: raise ValueError("Batch size must be a positive integer.") # Check that the parents share the same concrete model with the our # model to detect the inheritance pattern ConcreteGrandParent -> # MultiTableParent -> ProxyChild. Simply checking self.model._meta.proxy # would not identify that case as involving multiple tables. for parent in self.model._meta.get_parent_list(): if parent._meta.concrete_model is not self.model._meta.concrete_model: raise ValueError("Can't bulk create a multi-table inherited model") if not objs: return objs opts = self.model._meta if unique_fields: # Primary key is allowed in unique_fields. unique_fields = [ self.model._meta.get_field(opts.pk.name if name == "pk" else name) for name in unique_fields ] if update_fields: update_fields = [self.model._meta.get_field(name) for name in update_fields] on_conflict = self._check_bulk_create_options( ignore_conflicts, update_conflicts, update_fields, unique_fields, ) self._for_write = True fields = opts.concrete_fields objs = list(objs) self._prepare_for_bulk_create(objs) with transaction.atomic(using=self.db, savepoint=False): objs_with_pk, objs_without_pk = partition(lambda o: o.pk is None, objs) if objs_with_pk: returned_columns = self._batched_insert( objs_with_pk, fields, batch_size, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) for obj_with_pk, results in zip(objs_with_pk, returned_columns): for result, field in zip(results, opts.db_returning_fields): if field != opts.pk: setattr(obj_with_pk, field.attname, result) for obj_with_pk in objs_with_pk: obj_with_pk._state.adding = False obj_with_pk._state.db = self.db if objs_without_pk: fields = [f for f in fields if not isinstance(f, AutoField)] returned_columns = self._batched_insert( objs_without_pk, fields, batch_size, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) connection = connections[self.db] if ( connection.features.can_return_rows_from_bulk_insert and on_conflict is None ): assert len(returned_columns) == len(objs_without_pk) for obj_without_pk, results in zip(objs_without_pk, returned_columns): for result, field in zip(results, opts.db_returning_fields): setattr(obj_without_pk, field.attname, result) obj_without_pk._state.adding = False obj_without_pk._state.db = self.db return objs async def abulk_create( self, objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None, ): return await sync_to_async(self.bulk_create)( objs=objs, batch_size=batch_size, ignore_conflicts=ignore_conflicts, update_conflicts=update_conflicts, update_fields=update_fields, unique_fields=unique_fields, ) def bulk_update(self, objs, fields, batch_size=None): """ Update the given fields in each of the given objects in the database. """ if batch_size is not None and batch_size <= 0: raise ValueError("Batch size must be a positive integer.") if not fields: raise ValueError("Field names must be given to bulk_update().") objs = tuple(objs) if any(obj.pk is None for obj in objs): raise ValueError("All bulk_update() objects must have a primary key set.") fields = [self.model._meta.get_field(name) for name in fields] if any(not f.concrete or f.many_to_many for f in fields): raise ValueError("bulk_update() can only be used with concrete fields.") if any(f.primary_key for f in fields): raise ValueError("bulk_update() cannot be used with primary key fields.") if not objs: return 0 for obj in objs: obj._prepare_related_fields_for_save( operation_name="bulk_update", fields=fields ) # PK is used twice in the resulting update query, once in the filter # and once in the WHEN. Each field will also have one CAST. self._for_write = True connection = connections[self.db] max_batch_size = connection.ops.bulk_batch_size(["pk", "pk"] + fields, objs) batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size requires_casting = connection.features.requires_casted_case_in_updates batches = (objs[i : i + batch_size] for i in range(0, len(objs), batch_size)) updates = [] for batch_objs in batches: update_kwargs = {} for field in fields: when_statements = [] for obj in batch_objs: attr = getattr(obj, field.attname) if not hasattr(attr, "resolve_expression"): attr = Value(attr, output_field=field) when_statements.append(When(pk=obj.pk, then=attr)) case_statement = Case(*when_statements, output_field=field) if requires_casting: case_statement = Cast(case_statement, output_field=field) update_kwargs[field.attname] = case_statement updates.append(([obj.pk for obj in batch_objs], update_kwargs)) rows_updated = 0 queryset = self.using(self.db) with transaction.atomic(using=self.db, savepoint=False): for pks, update_kwargs in updates: rows_updated += queryset.filter(pk__in=pks).update(**update_kwargs) return rows_updated bulk_update.alters_data = True async def abulk_update(self, objs, fields, batch_size=None): return await sync_to_async(self.bulk_update)( objs=objs, fields=fields, batch_size=batch_size, ) abulk_update.alters_data = True def get_or_create(self, defaults=None, **kwargs): """ Look up an object with the given kwargs, creating one if necessary. Return a tuple of (object, created), where created is a boolean specifying whether an object was created. """ # The get() needs to be targeted at the write database in order # to avoid potential transaction consistency problems. self._for_write = True try: return self.get(**kwargs), False except self.model.DoesNotExist: params = self._extract_model_params(defaults, **kwargs) # Try to create an object using passed params. try: with transaction.atomic(using=self.db): params = dict(resolve_callables(params)) return self.create(**params), True except IntegrityError: try: return self.get(**kwargs), False except self.model.DoesNotExist: pass raise async def aget_or_create(self, defaults=None, **kwargs): return await sync_to_async(self.get_or_create)( defaults=defaults, **kwargs, ) def update_or_create(self, defaults=None, create_defaults=None, **kwargs): """ Look up an object with the given kwargs, updating one with defaults if it exists, otherwise create a new one. Optionally, an object can be created with different values than defaults by using create_defaults. Return a tuple (object, created), where created is a boolean specifying whether an object was created. """ if create_defaults is None: update_defaults = create_defaults = defaults or {} else: update_defaults = defaults or {} self._for_write = True with transaction.atomic(using=self.db): # Lock the row so that a concurrent update is blocked until # update_or_create() has performed its save. obj, created = self.select_for_update().get_or_create( create_defaults, **kwargs ) if created: return obj, created for k, v in resolve_callables(update_defaults): setattr(obj, k, v) update_fields = set(update_defaults) concrete_field_names = self.model._meta._non_pk_concrete_field_names # update_fields does not support non-concrete fields. if concrete_field_names.issuperset(update_fields): # Add fields which are set on pre_save(), e.g. auto_now fields. # This is to maintain backward compatibility as these fields # are not updated unless explicitly specified in the # update_fields list. for field in self.model._meta.local_concrete_fields: if not ( field.primary_key or field.__class__.pre_save is Field.pre_save ): update_fields.add(field.name) if field.name != field.attname: update_fields.add(field.attname) obj.save(using=self.db, update_fields=update_fields) else: obj.save(using=self.db) return obj, False async def aupdate_or_create(self, defaults=None, create_defaults=None, **kwargs): return await sync_to_async(self.update_or_create)( defaults=defaults, create_defaults=create_defaults, **kwargs, ) def _extract_model_params(self, defaults, **kwargs): """ Prepare `params` for creating a model instance based on the given kwargs; for use by get_or_create(). """ defaults = defaults or {} params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k} params.update(defaults) property_names = self.model._meta._property_names invalid_params = [] for param in params: try: self.model._meta.get_field(param) except exceptions.FieldDoesNotExist: # It's okay to use a model's property if it has a setter. if not (param in property_names and getattr(self.model, param).fset): invalid_params.append(param) if invalid_params: raise exceptions.FieldError( "Invalid field name(s) for model %s: '%s'." % ( self.model._meta.object_name, "', '".join(sorted(invalid_params)), ) ) return params def _earliest(self, *fields): """ Return the earliest object according to fields (if given) or by the model's Meta.get_latest_by. """ if fields: order_by = fields else: order_by = getattr(self.model._meta, "get_latest_by") if order_by and not isinstance(order_by, (tuple, list)): order_by = (order_by,) if order_by is None: raise ValueError( "earliest() and latest() require either fields as positional " "arguments or 'get_latest_by' in the model's Meta." ) obj = self._chain() obj.query.set_limits(high=1) obj.query.clear_ordering(force=True) obj.query.add_ordering(*order_by) return obj.get() def earliest(self, *fields): if self.query.is_sliced: raise TypeError("Cannot change a query once a slice has been taken.") return self._earliest(*fields) async def aearliest(self, *fields): return await sync_to_async(self.earliest)(*fields) def latest(self, *fields): """ Return the latest object according to fields (if given) or by the model's Meta.get_latest_by. """ if self.query.is_sliced: raise TypeError("Cannot change a query once a slice has been taken.") return self.reverse()._earliest(*fields) async def alatest(self, *fields): return await sync_to_async(self.latest)(*fields) def first(self): """Return the first object of a query or None if no match is found.""" if self.ordered: queryset = self else: self._check_ordering_first_last_queryset_aggregation(method="first") queryset = self.order_by("pk") for obj in queryset[:1]: return obj async def afirst(self): return await sync_to_async(self.first)() def last(self): """Return the last object of a query or None if no match is found.""" if self.ordered: queryset = self.reverse() else: self._check_ordering_first_last_queryset_aggregation(method="last") queryset = self.order_by("-pk") for obj in queryset[:1]: return obj async def alast(self): return await sync_to_async(self.last)() def in_bulk(self, id_list=None, *, field_name="pk"): """ Return a dictionary mapping each of the given IDs to the object with that ID. If `id_list` isn't provided, evaluate the entire QuerySet. """ if self.query.is_sliced: raise TypeError("Cannot use 'limit' or 'offset' with in_bulk().") opts = self.model._meta unique_fields = [ constraint.fields[0] for constraint in opts.total_unique_constraints if len(constraint.fields) == 1 ] if ( field_name != "pk" and not opts.get_field(field_name).unique and field_name not in unique_fields and self.query.distinct_fields != (field_name,) ): raise ValueError( "in_bulk()'s field_name must be a unique field but %r isn't." % field_name ) if id_list is not None: if not id_list: return {} filter_key = "{}__in".format(field_name) batch_size = connections[self.db].features.max_query_params id_list = tuple(id_list) # If the database has a limit on the number of query parameters # (e.g. SQLite), retrieve objects in batches if necessary. if batch_size and batch_size < len(id_list): qs = () for offset in range(0, len(id_list), batch_size): batch = id_list[offset : offset + batch_size] qs += tuple(self.filter(**{filter_key: batch})) else: qs = self.filter(**{filter_key: id_list}) else: qs = self._chain() return {getattr(obj, field_name): obj for obj in qs} async def ain_bulk(self, id_list=None, *, field_name="pk"): return await sync_to_async(self.in_bulk)( id_list=id_list, field_name=field_name, ) def delete(self): """Delete the records in the current QuerySet.""" self._not_support_combined_queries("delete") if self.query.is_sliced: raise TypeError("Cannot use 'limit' or 'offset' with delete().") if self.query.distinct or self.query.distinct_fields: raise TypeError("Cannot call delete() after .distinct().") if self._fields is not None: raise TypeError("Cannot call delete() after .values() or .values_list()") del_query = self._chain() # The delete is actually 2 queries - one to find related objects, # and one to delete. Make sure that the discovery of related # objects is performed on the same database as the deletion. del_query._for_write = True # Disable non-supported fields. del_query.query.select_for_update = False del_query.query.select_related = False del_query.query.clear_ordering(force=True) collector = Collector(using=del_query.db, origin=self) collector.collect(del_query) deleted, _rows_count = collector.delete() # Clear the result cache, in case this QuerySet gets reused. self._result_cache = None return deleted, _rows_count delete.alters_data = True delete.queryset_only = True async def adelete(self): return await sync_to_async(self.delete)() adelete.alters_data = True adelete.queryset_only = True def _raw_delete(self, using): """ Delete objects found from the given queryset in single direct SQL query. No signals are sent and there is no protection for cascades. """ query = self.query.clone() query.__class__ = sql.DeleteQuery cursor = query.get_compiler(using).execute_sql(CURSOR) if cursor: with cursor: return cursor.rowcount return 0 _raw_delete.alters_data = True def update(self, **kwargs): """ Update all elements in the current QuerySet, setting all the given fields to the appropriate values. """ self._not_support_combined_queries("update") if self.query.is_sliced: raise TypeError("Cannot update a query once a slice has been taken.") self._for_write = True query = self.query.chain(sql.UpdateQuery) query.add_update_values(kwargs) # Inline annotations in order_by(), if possible. new_order_by = [] for col in query.order_by: alias = col descending = False if isinstance(alias, str) and alias.startswith("-"): alias = alias.removeprefix("-") descending = True if annotation := query.annotations.get(alias): if getattr(annotation, "contains_aggregate", False): raise exceptions.FieldError( f"Cannot update when ordering by an aggregate: {annotation}" ) if descending: annotation = annotation.desc() new_order_by.append(annotation) else: new_order_by.append(col) query.order_by = tuple(new_order_by) # Clear any annotations so that they won't be present in subqueries. query.annotations = {} with transaction.mark_for_rollback_on_error(using=self.db): rows = query.get_compiler(self.db).execute_sql(CURSOR) self._result_cache = None return rows update.alters_data = True async def aupdate(self, **kwargs): return await sync_to_async(self.update)(**kwargs) aupdate.alters_data = True def _update(self, values): """ A version of update() that accepts field objects instead of field names. Used primarily for model saving and not intended for use by general code (it requires too much poking around at model internals to be useful at that level). """ if self.query.is_sliced: raise TypeError("Cannot update a query once a slice has been taken.") query = self.query.chain(sql.UpdateQuery) query.add_update_fields(values) # Clear any annotations so that they won't be present in subqueries. query.annotations = {} self._result_cache = None return query.get_compiler(self.db).execute_sql(CURSOR) _update.alters_data = True _update.queryset_only = False def exists(self): """ Return True if the QuerySet would have any results, False otherwise. """ if self._result_cache is None: return self.query.has_results(using=self.db) return bool(self._result_cache) async def aexists(self): return await sync_to_async(self.exists)() def contains(self, obj): """ Return True if the QuerySet contains the provided obj, False otherwise. """ self._not_support_combined_queries("contains") if self._fields is not None: raise TypeError( "Cannot call QuerySet.contains() after .values() or .values_list()." ) try: if obj._meta.concrete_model != self.model._meta.concrete_model: return False except AttributeError: raise TypeError("'obj' must be a model instance.") if obj.pk is None: raise ValueError("QuerySet.contains() cannot be used on unsaved objects.") if self._result_cache is not None: return obj in self._result_cache return self.filter(pk=obj.pk).exists() async def acontains(self, obj): return await sync_to_async(self.contains)(obj=obj) def _prefetch_related_objects(self): # This method can only be called once the result cache has been filled. prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups) self._prefetch_done = True def explain(self, *, format=None, **options): """ Runs an EXPLAIN on the SQL query this QuerySet would perform, and returns the results. """ return self.query.explain(using=self.db, format=format, **options) async def aexplain(self, *, format=None, **options): return await sync_to_async(self.explain)(format=format, **options) ################################################## # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS # ################################################## def raw(self, raw_query, params=(), translations=None, using=None): if using is None: using = self.db qs = RawQuerySet( raw_query, model=self.model, params=params, translations=translations, using=using, ) qs._prefetch_related_lookups = self._prefetch_related_lookups[:] return qs def _values(self, *fields, **expressions): clone = self._chain() if expressions: clone = clone.annotate(**expressions) clone._fields = fields clone.query.set_values(fields) return clone def values(self, *fields, **expressions): fields += tuple(expressions) clone = self._values(*fields, **expressions) clone._iterable_class = ValuesIterable return clone def values_list(self, *fields, flat=False, named=False): if flat and named: raise TypeError("'flat' and 'named' can't be used together.") if flat and len(fields) > 1: raise TypeError( "'flat' is not valid when values_list is called with more than one " "field." ) field_names = {f for f in fields if not hasattr(f, "resolve_expression")} _fields = [] expressions = {} counter = 1 for field in fields: if hasattr(field, "resolve_expression"): field_id_prefix = getattr( field, "default_alias", field.__class__.__name__.lower() ) while True: field_id = field_id_prefix + str(counter) counter += 1 if field_id not in field_names: break expressions[field_id] = field _fields.append(field_id) else: _fields.append(field) clone = self._values(*_fields, **expressions) clone._iterable_class = ( NamedValuesListIterable if named else FlatValuesListIterable if flat else ValuesListIterable ) return clone def dates(self, field_name, kind, order="ASC"): """ Return a list of date objects representing all available dates for the given field_name, scoped to 'kind'. """ if kind not in ("year", "month", "week", "day"): raise ValueError("'kind' must be one of 'year', 'month', 'week', or 'day'.") if order not in ("ASC", "DESC"): raise ValueError("'order' must be either 'ASC' or 'DESC'.") return ( self.annotate( datefield=Trunc(field_name, kind, output_field=DateField()), plain_field=F(field_name), ) .values_list("datefield", flat=True) .distinct() .filter(plain_field__isnull=False) .order_by(("-" if order == "DESC" else "") + "datefield") ) def datetimes(self, field_name, kind, order="ASC", tzinfo=None): """ Return a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'. """ if kind not in ("year", "month", "week", "day", "hour", "minute", "second"): raise ValueError( "'kind' must be one of 'year', 'month', 'week', 'day', " "'hour', 'minute', or 'second'." ) if order not in ("ASC", "DESC"): raise ValueError("'order' must be either 'ASC' or 'DESC'.") if settings.USE_TZ: if tzinfo is None: tzinfo = timezone.get_current_timezone() else: tzinfo = None return ( self.annotate( datetimefield=Trunc( field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo, ), plain_field=F(field_name), ) .values_list("datetimefield", flat=True) .distinct() .filter(plain_field__isnull=False) .order_by(("-" if order == "DESC" else "") + "datetimefield") ) def none(self): """Return an empty QuerySet.""" clone = self._chain() clone.query.set_empty() return clone ################################################################## # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET # ################################################################## def all(self): """ Return a new QuerySet that is a copy of the current one. This allows a QuerySet to proxy for a model manager in some cases. """ return self._chain() def filter(self, *args, **kwargs): """ Return a new QuerySet instance with the args ANDed to the existing set. """ self._not_support_combined_queries("filter") return self._filter_or_exclude(False, args, kwargs) def exclude(self, *args, **kwargs): """ Return a new QuerySet instance with NOT (args) ANDed to the existing set. """ self._not_support_combined_queries("exclude") return self._filter_or_exclude(True, args, kwargs) def _filter_or_exclude(self, negate, args, kwargs): if (args or kwargs) and self.query.is_sliced: raise TypeError("Cannot filter a query once a slice has been taken.") clone = self._chain() if self._defer_next_filter: self._defer_next_filter = False clone._deferred_filter = negate, args, kwargs else: clone._filter_or_exclude_inplace(negate, args, kwargs) return clone def _filter_or_exclude_inplace(self, negate, args, kwargs): if negate: self._query.add_q(~Q(*args, **kwargs)) else: self._query.add_q(Q(*args, **kwargs)) def complex_filter(self, filter_obj): """ Return a new QuerySet instance with filter_obj added to the filters. filter_obj can be a Q object or a dictionary of keyword lookup arguments. This exists to support framework features such as 'limit_choices_to', and usually it will be more natural to use other methods. """ if isinstance(filter_obj, Q): clone = self._chain() clone.query.add_q(filter_obj) return clone else: return self._filter_or_exclude(False, args=(), kwargs=filter_obj) def _combinator_query(self, combinator, *other_qs, all=False): # Clone the query to inherit the select list and everything clone = self._chain() # Clear limits and ordering so they can be reapplied clone.query.clear_ordering(force=True) clone.query.clear_limits() clone.query.combined_queries = (self.query,) + tuple( qs.query for qs in other_qs ) clone.query.combinator = combinator clone.query.combinator_all = all return clone def union(self, *other_qs, all=False): # If the query is an EmptyQuerySet, combine all nonempty querysets. if isinstance(self, EmptyQuerySet): qs = [q for q in other_qs if not isinstance(q, EmptyQuerySet)] if not qs: return self if len(qs) == 1: return qs[0] return qs[0]._combinator_query("union", *qs[1:], all=all) return self._combinator_query("union", *other_qs, all=all) def intersection(self, *other_qs): # If any query is an EmptyQuerySet, return it. if isinstance(self, EmptyQuerySet): return self for other in other_qs: if isinstance(other, EmptyQuerySet): return other return self._combinator_query("intersection", *other_qs) def difference(self, *other_qs): # If the query is an EmptyQuerySet, return it. if isinstance(self, EmptyQuerySet): return self return self._combinator_query("difference", *other_qs) def select_for_update(self, nowait=False, skip_locked=False, of=(), no_key=False): """ Return a new QuerySet instance that will select objects with a FOR UPDATE lock. """ if nowait and skip_locked: raise ValueError("The nowait option cannot be used with skip_locked.") obj = self._chain() obj._for_write = True obj.query.select_for_update = True obj.query.select_for_update_nowait = nowait obj.query.select_for_update_skip_locked = skip_locked obj.query.select_for_update_of = of obj.query.select_for_no_key_update = no_key return obj def select_related(self, *fields): """ Return a new QuerySet instance that will select related objects. If fields are specified, they must be ForeignKey fields and only those related objects are included in the selection. If select_related(None) is called, clear the list. """ self._not_support_combined_queries("select_related") if self._fields is not None: raise TypeError( "Cannot call select_related() after .values() or .values_list()" ) obj = self._chain() if fields == (None,): obj.query.select_related = False elif fields: obj.query.add_select_related(fields) else: obj.query.select_related = True return obj def prefetch_related(self, *lookups): """ Return a new QuerySet instance that will prefetch the specified Many-To-One and Many-To-Many related objects when the QuerySet is evaluated. When prefetch_related() is called more than once, append to the list of prefetch lookups. If prefetch_related(None) is called, clear the list. """ self._not_support_combined_queries("prefetch_related") clone = self._chain() if lookups == (None,): clone._prefetch_related_lookups = () else: for lookup in lookups: if isinstance(lookup, Prefetch): lookup = lookup.prefetch_to lookup = lookup.split(LOOKUP_SEP, 1)[0] if lookup in self.query._filtered_relations: raise ValueError( "prefetch_related() is not supported with FilteredRelation." ) clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups return clone def annotate(self, *args, **kwargs): """ Return a query set in which the returned objects have been annotated with extra data or aggregations. """ self._not_support_combined_queries("annotate") return self._annotate(args, kwargs, select=True) def alias(self, *args, **kwargs): """ Return a query set with added aliases for extra data or aggregations. """ self._not_support_combined_queries("alias") return self._annotate(args, kwargs, select=False) def _annotate(self, args, kwargs, select=True): self._validate_values_are_expressions( args + tuple(kwargs.values()), method_name="annotate" ) annotations = {} for arg in args: # The default_alias property may raise a TypeError. try: if arg.default_alias in kwargs: raise ValueError( "The named annotation '%s' conflicts with the " "default name for another annotation." % arg.default_alias ) except TypeError: raise TypeError("Complex annotations require an alias") annotations[arg.default_alias] = arg annotations.update(kwargs) clone = self._chain() names = self._fields if names is None: names = set( chain.from_iterable( (field.name, field.attname) if hasattr(field, "attname") else (field.name,) for field in self.model._meta.get_fields() ) ) for alias, annotation in annotations.items(): if alias in names: raise ValueError( "The annotation '%s' conflicts with a field on " "the model." % alias ) if isinstance(annotation, FilteredRelation): clone.query.add_filtered_relation(annotation, alias) else: clone.query.add_annotation( annotation, alias, select=select, ) for alias, annotation in clone.query.annotations.items(): if alias in annotations and annotation.contains_aggregate: if clone._fields is None: clone.query.group_by = True else: clone.query.set_group_by() break return clone def order_by(self, *field_names): """Return a new QuerySet instance with the ordering changed.""" if self.query.is_sliced: raise TypeError("Cannot reorder a query once a slice has been taken.") obj = self._chain() obj.query.clear_ordering(force=True, clear_default=False) obj.query.add_ordering(*field_names) return obj def distinct(self, *field_names): """ Return a new QuerySet instance that will select only distinct results. """ self._not_support_combined_queries("distinct") if self.query.is_sliced: raise TypeError( "Cannot create distinct fields once a slice has been taken." ) obj = self._chain() obj.query.add_distinct_fields(*field_names) return obj def extra( self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None, ): """Add extra SQL fragments to the query.""" self._not_support_combined_queries("extra") if self.query.is_sliced: raise TypeError("Cannot change a query once a slice has been taken.") clone = self._chain() clone.query.add_extra(select, select_params, where, params, tables, order_by) return clone def reverse(self): """Reverse the ordering of the QuerySet.""" if self.query.is_sliced: raise TypeError("Cannot reverse a query once a slice has been taken.") clone = self._chain() clone.query.standard_ordering = not clone.query.standard_ordering return clone def defer(self, *fields): """ Defer the loading of data for certain fields until they are accessed. Add the set of deferred fields to any existing set of deferred fields. The only exception to this is if None is passed in as the only parameter, in which case removal all deferrals. """ self._not_support_combined_queries("defer") if self._fields is not None: raise TypeError("Cannot call defer() after .values() or .values_list()") clone = self._chain() if fields == (None,): clone.query.clear_deferred_loading() else: clone.query.add_deferred_loading(fields) return clone def only(self, *fields): """ Essentially, the opposite of defer(). Only the fields passed into this method and that are not already specified as deferred are loaded immediately when the queryset is evaluated. """ self._not_support_combined_queries("only") if self._fields is not None: raise TypeError("Cannot call only() after .values() or .values_list()") if fields == (None,): # Can only pass None to defer(), not only(), as the rest option. # That won't stop people trying to do this, so let's be explicit. raise TypeError("Cannot pass None as an argument to only().") for field in fields: field = field.split(LOOKUP_SEP, 1)[0] if field in self.query._filtered_relations: raise ValueError("only() is not supported with FilteredRelation.") clone = self._chain() clone.query.add_immediate_loading(fields) return clone def using(self, alias): """Select which database this QuerySet should execute against.""" clone = self._chain() clone._db = alias return clone ################################### # PUBLIC INTROSPECTION ATTRIBUTES # ################################### @property def ordered(self): """ Return True if the QuerySet is ordered -- i.e. has an order_by() clause or a default ordering on the model (or is empty). """ if isinstance(self, EmptyQuerySet): return True if self.query.extra_order_by or self.query.order_by: return True elif ( self.query.default_ordering and self.query.get_meta().ordering and # A default ordering doesn't affect GROUP BY queries. not self.query.group_by ): return True else: return False @property def db(self): """Return the database used if this query is executed now.""" if self._for_write: return self._db or router.db_for_write(self.model, **self._hints) return self._db or router.db_for_read(self.model, **self._hints) ################### # PRIVATE METHODS # ################### def _insert( self, objs, fields, returning_fields=None, raw=False, using=None, on_conflict=None, update_fields=None, unique_fields=None, ): """ Insert a new record for the given model. This provides an interface to the InsertQuery class and is how Model.save() is implemented. """ self._for_write = True if using is None: using = self.db query = sql.InsertQuery( self.model, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) query.insert_values(fields, objs, raw=raw) return query.get_compiler(using=using).execute_sql(returning_fields) _insert.alters_data = True _insert.queryset_only = False def _batched_insert( self, objs, fields, batch_size, on_conflict=None, update_fields=None, unique_fields=None, ): """ Helper method for bulk_create() to insert objs one batch at a time. """ connection = connections[self.db] ops = connection.ops max_batch_size = max(ops.bulk_batch_size(fields, objs), 1) batch_size = min(batch_size, max_batch_size) if batch_size else max_batch_size inserted_rows = [] bulk_return = connection.features.can_return_rows_from_bulk_insert for item in [objs[i : i + batch_size] for i in range(0, len(objs), batch_size)]: if bulk_return and on_conflict is None: inserted_rows.extend( self._insert( item, fields=fields, using=self.db, returning_fields=self.model._meta.db_returning_fields, ) ) else: self._insert( item, fields=fields, using=self.db, on_conflict=on_conflict, update_fields=update_fields, unique_fields=unique_fields, ) return inserted_rows def _chain(self): """ Return a copy of the current QuerySet that's ready for another operation. """ obj = self._clone() if obj._sticky_filter: obj.query.filter_is_sticky = True obj._sticky_filter = False return obj def _clone(self): """ Return a copy of the current QuerySet. A lightweight alternative to deepcopy(). """ c = self.__class__( model=self.model, query=self.query.chain(), using=self._db, hints=self._hints, ) c._sticky_filter = self._sticky_filter c._for_write = self._for_write c._prefetch_related_lookups = self._prefetch_related_lookups[:] c._known_related_objects = self._known_related_objects c._iterable_class = self._iterable_class c._fields = self._fields return c def _fetch_all(self): if self._result_cache is None: self._result_cache = list(self._iterable_class(self)) if self._prefetch_related_lookups and not self._prefetch_done: self._prefetch_related_objects() def _next_is_sticky(self): """ Indicate that the next filter call and the one following that should be treated as a single filter. This is only important when it comes to determining when to reuse tables for many-to-many filters. Required so that we can filter naturally on the results of related managers. This doesn't return a clone of the current QuerySet (it returns "self"). The method is only used internally and should be immediately followed by a filter() that does create a clone. """ self._sticky_filter = True return self def _merge_sanity_check(self, other): """Check that two QuerySet classes may be merged.""" if self._fields is not None and ( set(self.query.values_select) != set(other.query.values_select) or set(self.query.extra_select) != set(other.query.extra_select) or set(self.query.annotation_select) != set(other.query.annotation_select) ): raise TypeError( "Merging '%s' classes must involve the same values in each case." % self.__class__.__name__ ) def _merge_known_related_objects(self, other): """ Keep track of all known related objects from either QuerySet instance. """ for field, objects in other._known_related_objects.items(): self._known_related_objects.setdefault(field, {}).update(objects) def resolve_expression(self, *args, **kwargs): if self._fields and len(self._fields) > 1: # values() queryset can only be used as nested queries # if they are set up to select only a single field. raise TypeError("Cannot use multi-field values as a filter value.") query = self.query.resolve_expression(*args, **kwargs) query._db = self._db return query resolve_expression.queryset_only = True def _add_hints(self, **hints): """ Update hinting information for use by routers. Add new key/values or overwrite existing key/values. """ self._hints.update(hints) def _has_filters(self): """ Check if this QuerySet has any filtering going on. This isn't equivalent with checking if all objects are present in results, for example, qs[1:]._has_filters() -> False. """ return self.query.has_filters() @staticmethod def _validate_values_are_expressions(values, method_name): invalid_args = sorted( str(arg) for arg in values if not hasattr(arg, "resolve_expression") ) if invalid_args: raise TypeError( "QuerySet.%s() received non-expression(s): %s." % ( method_name, ", ".join(invalid_args), ) ) def _not_support_combined_queries(self, operation_name): if self.query.combinator: raise NotSupportedError( "Calling QuerySet.%s() after %s() is not supported." % (operation_name, self.query.combinator) ) def _check_operator_queryset(self, other, operator_): if self.query.combinator or other.query.combinator: raise TypeError(f"Cannot use {operator_} operator with combined queryset.") def _check_ordering_first_last_queryset_aggregation(self, method): if isinstance(self.query.group_by, tuple) and not any( col.output_field is self.model._meta.pk for col in self.query.group_by ): raise TypeError( f"Cannot use QuerySet.{method}() on an unordered queryset performing " f"aggregation. Add an ordering with order_by()." ) class InstanceCheckMeta(type): def __instancecheck__(self, instance): return isinstance(instance, QuerySet) and instance.query.is_empty() class EmptyQuerySet(metaclass=InstanceCheckMeta): """ Marker class to checking if a queryset is empty by .none(): isinstance(qs.none(), EmptyQuerySet) -> True """ def __init__(self, *args, **kwargs): raise TypeError("EmptyQuerySet can't be instantiated") class RawQuerySet: """ Provide an iterator which converts the results of raw SQL queries into annotated model instances. """ def __init__( self, raw_query, model=None, query=None, params=(), translations=None, using=None, hints=None, ): self.raw_query = raw_query self.model = model self._db = using self._hints = hints or {} self.query = query or sql.RawQuery(sql=raw_query, using=self.db, params=params) self.params = params self.translations = translations or {} self._result_cache = None self._prefetch_related_lookups = () self._prefetch_done = False def resolve_model_init_order(self): """Resolve the init field names and value positions.""" converter = connections[self.db].introspection.identifier_converter model_init_fields = [ f for f in self.model._meta.fields if converter(f.column) in self.columns ] annotation_fields = [ (column, pos) for pos, column in enumerate(self.columns) if column not in self.model_fields ] model_init_order = [ self.columns.index(converter(f.column)) for f in model_init_fields ] model_init_names = [f.attname for f in model_init_fields] return model_init_names, model_init_order, annotation_fields def prefetch_related(self, *lookups): """Same as QuerySet.prefetch_related()""" clone = self._clone() if lookups == (None,): clone._prefetch_related_lookups = () else: clone._prefetch_related_lookups = clone._prefetch_related_lookups + lookups return clone def _prefetch_related_objects(self): prefetch_related_objects(self._result_cache, *self._prefetch_related_lookups) self._prefetch_done = True def _clone(self): """Same as QuerySet._clone()""" c = self.__class__( self.raw_query, model=self.model, query=self.query, params=self.params, translations=self.translations, using=self._db, hints=self._hints, ) c._prefetch_related_lookups = self._prefetch_related_lookups[:] return c def _fetch_all(self): if self._result_cache is None: self._result_cache = list(self.iterator()) if self._prefetch_related_lookups and not self._prefetch_done: self._prefetch_related_objects() def __len__(self): self._fetch_all() return len(self._result_cache) def __bool__(self): self._fetch_all() return bool(self._result_cache) def __iter__(self): self._fetch_all() return iter(self._result_cache) def __aiter__(self): # Remember, __aiter__ itself is synchronous, it's the thing it returns # that is async! async def generator(): await sync_to_async(self._fetch_all)() for item in self._result_cache: yield item return generator() def iterator(self): yield from RawModelIterable(self) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self.query) def __getitem__(self, k): return list(self)[k] @property def db(self): """Return the database used if this query is executed now.""" return self._db or router.db_for_read(self.model, **self._hints) def using(self, alias): """Select the database this RawQuerySet should execute against.""" return RawQuerySet( self.raw_query, model=self.model, query=self.query.chain(using=alias), params=self.params, translations=self.translations, using=alias, ) @cached_property def columns(self): """ A list of model field names in the order they'll appear in the query results. """ columns = self.query.get_columns() # Adjust any column names which don't match field names for query_name, model_name in self.translations.items(): # Ignore translations for nonexistent column names try: index = columns.index(query_name) except ValueError: pass else: columns[index] = model_name return columns @cached_property def model_fields(self): """A dict mapping column names to model field names.""" converter = connections[self.db].introspection.identifier_converter model_fields = {} for field in self.model._meta.fields: name, column = field.get_attname_column() model_fields[converter(column)] = field return model_fields class Prefetch: def __init__(self, lookup, queryset=None, to_attr=None): # `prefetch_through` is the path we traverse to perform the prefetch. self.prefetch_through = lookup # `prefetch_to` is the path to the attribute that stores the result. self.prefetch_to = lookup if queryset is not None and ( isinstance(queryset, RawQuerySet) or ( hasattr(queryset, "_iterable_class") and not issubclass(queryset._iterable_class, ModelIterable) ) ): raise ValueError( "Prefetch querysets cannot use raw(), values(), and values_list()." ) if to_attr: self.prefetch_to = LOOKUP_SEP.join( lookup.split(LOOKUP_SEP)[:-1] + [to_attr] ) self.queryset = queryset self.to_attr = to_attr def __getstate__(self): obj_dict = self.__dict__.copy() if self.queryset is not None: queryset = self.queryset._chain() # Prevent the QuerySet from being evaluated queryset._result_cache = [] queryset._prefetch_done = True obj_dict["queryset"] = queryset return obj_dict def add_prefix(self, prefix): self.prefetch_through = prefix + LOOKUP_SEP + self.prefetch_through self.prefetch_to = prefix + LOOKUP_SEP + self.prefetch_to def get_current_prefetch_to(self, level): return LOOKUP_SEP.join(self.prefetch_to.split(LOOKUP_SEP)[: level + 1]) def get_current_to_attr(self, level): parts = self.prefetch_to.split(LOOKUP_SEP) to_attr = parts[level] as_attr = self.to_attr and level == len(parts) - 1 return to_attr, as_attr def get_current_queryset(self, level): if self.get_current_prefetch_to(level) == self.prefetch_to: return self.queryset return None def __eq__(self, other): if not isinstance(other, Prefetch): return NotImplemented return self.prefetch_to == other.prefetch_to def __hash__(self): return hash((self.__class__, self.prefetch_to)) def normalize_prefetch_lookups(lookups, prefix=None): """Normalize lookups into Prefetch objects.""" ret = [] for lookup in lookups: if not isinstance(lookup, Prefetch): lookup = Prefetch(lookup) if prefix: lookup.add_prefix(prefix) ret.append(lookup) return ret def prefetch_related_objects(model_instances, *related_lookups): """ Populate prefetched object caches for a list of model instances based on the lookups/Prefetch instances given. """ if not model_instances: return # nothing to do # We need to be able to dynamically add to the list of prefetch_related # lookups that we look up (see below). So we need some book keeping to # ensure we don't do duplicate work. done_queries = {} # dictionary of things like 'foo__bar': [results] auto_lookups = set() # we add to this as we go through. followed_descriptors = set() # recursion protection all_lookups = normalize_prefetch_lookups(reversed(related_lookups)) while all_lookups: lookup = all_lookups.pop() if lookup.prefetch_to in done_queries: if lookup.queryset is not None: raise ValueError( "'%s' lookup was already seen with a different queryset. " "You may need to adjust the ordering of your lookups." % lookup.prefetch_to ) continue # Top level, the list of objects to decorate is the result cache # from the primary QuerySet. It won't be for deeper levels. obj_list = model_instances through_attrs = lookup.prefetch_through.split(LOOKUP_SEP) for level, through_attr in enumerate(through_attrs): # Prepare main instances if not obj_list: break prefetch_to = lookup.get_current_prefetch_to(level) if prefetch_to in done_queries: # Skip any prefetching, and any object preparation obj_list = done_queries[prefetch_to] continue # Prepare objects: good_objects = True for obj in obj_list: # Since prefetching can re-use instances, it is possible to have # the same instance multiple times in obj_list, so obj might # already be prepared. if not hasattr(obj, "_prefetched_objects_cache"): try: obj._prefetched_objects_cache = {} except (AttributeError, TypeError): # Must be an immutable object from # values_list(flat=True), for example (TypeError) or # a QuerySet subclass that isn't returning Model # instances (AttributeError), either in Django or a 3rd # party. prefetch_related() doesn't make sense, so quit. good_objects = False break if not good_objects: break # Descend down tree # We assume that objects retrieved are homogeneous (which is the premise # of prefetch_related), so what applies to first object applies to all. first_obj = obj_list[0] to_attr = lookup.get_current_to_attr(level)[0] prefetcher, descriptor, attr_found, is_fetched = get_prefetcher( first_obj, through_attr, to_attr ) if not attr_found: raise AttributeError( "Cannot find '%s' on %s object, '%s' is an invalid " "parameter to prefetch_related()" % ( through_attr, first_obj.__class__.__name__, lookup.prefetch_through, ) ) if level == len(through_attrs) - 1 and prefetcher is None: # Last one, this *must* resolve to something that supports # prefetching, otherwise there is no point adding it and the # developer asking for it has made a mistake. raise ValueError( "'%s' does not resolve to an item that supports " "prefetching - this is an invalid parameter to " "prefetch_related()." % lookup.prefetch_through ) obj_to_fetch = None if prefetcher is not None: obj_to_fetch = [obj for obj in obj_list if not is_fetched(obj)] if obj_to_fetch: obj_list, additional_lookups = prefetch_one_level( obj_to_fetch, prefetcher, lookup, level, ) # We need to ensure we don't keep adding lookups from the # same relationships to stop infinite recursion. So, if we # are already on an automatically added lookup, don't add # the new lookups from relationships we've seen already. if not ( prefetch_to in done_queries and lookup in auto_lookups and descriptor in followed_descriptors ): done_queries[prefetch_to] = obj_list new_lookups = normalize_prefetch_lookups( reversed(additional_lookups), prefetch_to ) auto_lookups.update(new_lookups) all_lookups.extend(new_lookups) followed_descriptors.add(descriptor) else: # Either a singly related object that has already been fetched # (e.g. via select_related), or hopefully some other property # that doesn't support prefetching but needs to be traversed. # We replace the current list of parent objects with the list # of related objects, filtering out empty or missing values so # that we can continue with nullable or reverse relations. new_obj_list = [] for obj in obj_list: if through_attr in getattr(obj, "_prefetched_objects_cache", ()): # If related objects have been prefetched, use the # cache rather than the object's through_attr. new_obj = list(obj._prefetched_objects_cache.get(through_attr)) else: try: new_obj = getattr(obj, through_attr) except exceptions.ObjectDoesNotExist: continue if new_obj is None: continue # We special-case `list` rather than something more generic # like `Iterable` because we don't want to accidentally match # user models that define __iter__. if isinstance(new_obj, list): new_obj_list.extend(new_obj) else: new_obj_list.append(new_obj) obj_list = new_obj_list def get_prefetcher(instance, through_attr, to_attr): """ For the attribute 'through_attr' on the given instance, find an object that has a get_prefetch_queryset(). Return a 4 tuple containing: (the object with get_prefetch_queryset (or None), the descriptor object representing this relationship (or None), a boolean that is False if the attribute was not found at all, a function that takes an instance and returns a boolean that is True if the attribute has already been fetched for that instance) """ def has_to_attr_attribute(instance): return hasattr(instance, to_attr) prefetcher = None is_fetched = has_to_attr_attribute # For singly related objects, we have to avoid getting the attribute # from the object, as this will trigger the query. So we first try # on the class, in order to get the descriptor object. rel_obj_descriptor = getattr(instance.__class__, through_attr, None) if rel_obj_descriptor is None: attr_found = hasattr(instance, through_attr) else: attr_found = True if rel_obj_descriptor: # singly related object, descriptor object has the # get_prefetch_queryset() method. if hasattr(rel_obj_descriptor, "get_prefetch_queryset"): prefetcher = rel_obj_descriptor is_fetched = rel_obj_descriptor.is_cached else: # descriptor doesn't support prefetching, so we go ahead and get # the attribute on the instance rather than the class to # support many related managers rel_obj = getattr(instance, through_attr) if hasattr(rel_obj, "get_prefetch_queryset"): prefetcher = rel_obj if through_attr != to_attr: # Special case cached_property instances because hasattr # triggers attribute computation and assignment. if isinstance( getattr(instance.__class__, to_attr, None), cached_property ): def has_cached_property(instance): return to_attr in instance.__dict__ is_fetched = has_cached_property else: def in_prefetched_cache(instance): return through_attr in instance._prefetched_objects_cache is_fetched = in_prefetched_cache return prefetcher, rel_obj_descriptor, attr_found, is_fetched def prefetch_one_level(instances, prefetcher, lookup, level): """ Helper function for prefetch_related_objects(). Run prefetches on all instances using the prefetcher object, assigning results to relevant caches in instance. Return the prefetched objects along with any additional prefetches that must be done due to prefetch_related lookups found from default managers. """ # prefetcher must have a method get_prefetch_queryset() which takes a list # of instances, and returns a tuple: # (queryset of instances of self.model that are related to passed in instances, # callable that gets value to be matched for returned instances, # callable that gets value to be matched for passed in instances, # boolean that is True for singly related objects, # cache or field name to assign to, # boolean that is True when the previous argument is a cache name vs a field name). # The 'values to be matched' must be hashable as they will be used # in a dictionary. ( rel_qs, rel_obj_attr, instance_attr, single, cache_name, is_descriptor, ) = prefetcher.get_prefetch_queryset(instances, lookup.get_current_queryset(level)) # We have to handle the possibility that the QuerySet we just got back # contains some prefetch_related lookups. We don't want to trigger the # prefetch_related functionality by evaluating the query. Rather, we need # to merge in the prefetch_related lookups. # Copy the lookups in case it is a Prefetch object which could be reused # later (happens in nested prefetch_related). additional_lookups = [ copy.copy(additional_lookup) for additional_lookup in getattr(rel_qs, "_prefetch_related_lookups", ()) ] if additional_lookups: # Don't need to clone because the manager should have given us a fresh # instance, so we access an internal instead of using public interface # for performance reasons. rel_qs._prefetch_related_lookups = () all_related_objects = list(rel_qs) rel_obj_cache = {} for rel_obj in all_related_objects: rel_attr_val = rel_obj_attr(rel_obj) rel_obj_cache.setdefault(rel_attr_val, []).append(rel_obj) to_attr, as_attr = lookup.get_current_to_attr(level) # Make sure `to_attr` does not conflict with a field. if as_attr and instances: # We assume that objects retrieved are homogeneous (which is the premise # of prefetch_related), so what applies to first object applies to all. model = instances[0].__class__ try: model._meta.get_field(to_attr) except exceptions.FieldDoesNotExist: pass else: msg = "to_attr={} conflicts with a field on the {} model." raise ValueError(msg.format(to_attr, model.__name__)) # Whether or not we're prefetching the last part of the lookup. leaf = len(lookup.prefetch_through.split(LOOKUP_SEP)) - 1 == level for obj in instances: instance_attr_val = instance_attr(obj) vals = rel_obj_cache.get(instance_attr_val, []) if single: val = vals[0] if vals else None if as_attr: # A to_attr has been given for the prefetch. setattr(obj, to_attr, val) elif is_descriptor: # cache_name points to a field name in obj. # This field is a descriptor for a related object. setattr(obj, cache_name, val) else: # No to_attr has been given for this prefetch operation and the # cache_name does not point to a descriptor. Store the value of # the field in the object's field cache. obj._state.fields_cache[cache_name] = val else: if as_attr: setattr(obj, to_attr, vals) else: manager = getattr(obj, to_attr) if leaf and lookup.queryset is not None: qs = manager._apply_rel_filters(lookup.queryset) else: qs = manager.get_queryset() qs._result_cache = vals # We don't want the individual qs doing prefetch_related now, # since we have merged this into the current work. qs._prefetch_done = True obj._prefetched_objects_cache[cache_name] = qs return all_related_objects, additional_lookups class RelatedPopulator: """ RelatedPopulator is used for select_related() object instantiation. The idea is that each select_related() model will be populated by a different RelatedPopulator instance. The RelatedPopulator instances get klass_info and select (computed in SQLCompiler) plus the used db as input for initialization. That data is used to compute which columns to use, how to instantiate the model, and how to populate the links between the objects. The actual creation of the objects is done in populate() method. This method gets row and from_obj as input and populates the select_related() model instance. """ def __init__(self, klass_info, select, db): self.db = db # Pre-compute needed attributes. The attributes are: # - model_cls: the possibly deferred model class to instantiate # - either: # - cols_start, cols_end: usually the columns in the row are # in the same order model_cls.__init__ expects them, so we # can instantiate by model_cls(*row[cols_start:cols_end]) # - reorder_for_init: When select_related descends to a child # class, then we want to reuse the already selected parent # data. However, in this case the parent data isn't necessarily # in the same order that Model.__init__ expects it to be, so # we have to reorder the parent data. The reorder_for_init # attribute contains a function used to reorder the field data # in the order __init__ expects it. # - pk_idx: the index of the primary key field in the reordered # model data. Used to check if a related object exists at all. # - init_list: the field attnames fetched from the database. For # deferred models this isn't the same as all attnames of the # model's fields. # - related_populators: a list of RelatedPopulator instances if # select_related() descends to related models from this model. # - local_setter, remote_setter: Methods to set cached values on # the object being populated and on the remote object. Usually # these are Field.set_cached_value() methods. select_fields = klass_info["select_fields"] from_parent = klass_info["from_parent"] if not from_parent: self.cols_start = select_fields[0] self.cols_end = select_fields[-1] + 1 self.init_list = [ f[0].target.attname for f in select[self.cols_start : self.cols_end] ] self.reorder_for_init = None else: attname_indexes = { select[idx][0].target.attname: idx for idx in select_fields } model_init_attnames = ( f.attname for f in klass_info["model"]._meta.concrete_fields ) self.init_list = [ attname for attname in model_init_attnames if attname in attname_indexes ] self.reorder_for_init = operator.itemgetter( *[attname_indexes[attname] for attname in self.init_list] ) self.model_cls = klass_info["model"] self.pk_idx = self.init_list.index(self.model_cls._meta.pk.attname) self.related_populators = get_related_populators(klass_info, select, self.db) self.local_setter = klass_info["local_setter"] self.remote_setter = klass_info["remote_setter"] def populate(self, row, from_obj): if self.reorder_for_init: obj_data = self.reorder_for_init(row) else: obj_data = row[self.cols_start : self.cols_end] if obj_data[self.pk_idx] is None: obj = None else: obj = self.model_cls.from_db(self.db, self.init_list, obj_data) for rel_iter in self.related_populators: rel_iter.populate(row, obj) self.local_setter(from_obj, obj) if obj is not None: self.remote_setter(obj, from_obj) def get_related_populators(klass_info, select, db): iterators = [] related_klass_infos = klass_info.get("related_klass_infos", []) for rel_klass_info in related_klass_infos: rel_cls = RelatedPopulator(rel_klass_info, select, db) iterators.append(rel_cls) return iterators
d390df02913101f7519be5663919289012fd44c07e6eef0cf9fb6cc5231aaea1
import collections.abc import copy import datetime import decimal import operator import uuid import warnings from base64 import b64decode, b64encode from functools import partialmethod, total_ordering from django import forms from django.apps import apps from django.conf import settings from django.core import checks, exceptions, validators from django.db import connection, connections, router from django.db.models.constants import LOOKUP_SEP from django.db.models.enums import ChoicesMeta from django.db.models.query_utils import DeferredAttribute, RegisterLookupMixin from django.utils import timezone from django.utils.datastructures import DictWrapper from django.utils.dateparse import ( parse_date, parse_datetime, parse_duration, parse_time, ) from django.utils.duration import duration_microseconds, duration_string from django.utils.functional import Promise, cached_property from django.utils.ipv6 import clean_ipv6_address from django.utils.itercompat import is_iterable from django.utils.text import capfirst from django.utils.translation import gettext_lazy as _ __all__ = [ "AutoField", "BLANK_CHOICE_DASH", "BigAutoField", "BigIntegerField", "BinaryField", "BooleanField", "CharField", "CommaSeparatedIntegerField", "DateField", "DateTimeField", "DecimalField", "DurationField", "EmailField", "Empty", "Field", "FilePathField", "FloatField", "GenericIPAddressField", "IPAddressField", "IntegerField", "NOT_PROVIDED", "NullBooleanField", "PositiveBigIntegerField", "PositiveIntegerField", "PositiveSmallIntegerField", "SlugField", "SmallAutoField", "SmallIntegerField", "TextField", "TimeField", "URLField", "UUIDField", ] class Empty: pass class NOT_PROVIDED: pass # The values to use for "blank" in SelectFields. Will be appended to the start # of most "choices" lists. BLANK_CHOICE_DASH = [("", "---------")] def _load_field(app_label, model_name, field_name): return apps.get_model(app_label, model_name)._meta.get_field(field_name) # A guide to Field parameters: # # * name: The name of the field specified in the model. # * attname: The attribute to use on the model object. This is the same as # "name", except in the case of ForeignKeys, where "_id" is # appended. # * db_column: The db_column specified in the model (or None). # * column: The database column for this field. This is the same as # "attname", except if db_column is specified. # # Code that introspects values, or does other dynamic things, should use # attname. For example, this gets the primary key value of object "obj": # # getattr(obj, opts.pk.attname) def _empty(of_cls): new = Empty() new.__class__ = of_cls return new def return_None(): return None @total_ordering class Field(RegisterLookupMixin): """Base class for all field types""" # Designates whether empty strings fundamentally are allowed at the # database level. empty_strings_allowed = True empty_values = list(validators.EMPTY_VALUES) # These track each time a Field instance is created. Used to retain order. # The auto_creation_counter is used for fields that Django implicitly # creates, creation_counter is used for all user-specified fields. creation_counter = 0 auto_creation_counter = -1 default_validators = [] # Default set of validators default_error_messages = { "invalid_choice": _("Value %(value)r is not a valid choice."), "null": _("This field cannot be null."), "blank": _("This field cannot be blank."), "unique": _("%(model_name)s with this %(field_label)s already exists."), "unique_for_date": _( # Translators: The 'lookup_type' is one of 'date', 'year' or # 'month'. Eg: "Title must be unique for pub_date year" "%(field_label)s must be unique for " "%(date_field_label)s %(lookup_type)s." ), } system_check_deprecated_details = None system_check_removed_details = None # Attributes that don't affect a column definition. # These attributes are ignored when altering the field. non_db_attrs = ( "blank", "choices", "db_column", "editable", "error_messages", "help_text", "limit_choices_to", # Database-level options are not supported, see #21961. "on_delete", "related_name", "related_query_name", "validators", "verbose_name", ) # Field flags hidden = False many_to_many = None many_to_one = None one_to_many = None one_to_one = None related_model = None descriptor_class = DeferredAttribute # Generic field type description, usually overridden by subclasses def _description(self): return _("Field of type: %(field_type)s") % { "field_type": self.__class__.__name__ } description = property(_description) def __init__( self, verbose_name=None, name=None, primary_key=False, max_length=None, unique=False, blank=False, null=False, db_index=False, rel=None, default=NOT_PROVIDED, editable=True, serialize=True, unique_for_date=None, unique_for_month=None, unique_for_year=None, choices=None, help_text="", db_column=None, db_tablespace=None, auto_created=False, validators=(), error_messages=None, db_comment=None, ): self.name = name self.verbose_name = verbose_name # May be set by set_attributes_from_name self._verbose_name = verbose_name # Store original for deconstruction self.primary_key = primary_key self.max_length, self._unique = max_length, unique self.blank, self.null = blank, null self.remote_field = rel self.is_relation = self.remote_field is not None self.default = default self.editable = editable self.serialize = serialize self.unique_for_date = unique_for_date self.unique_for_month = unique_for_month self.unique_for_year = unique_for_year if isinstance(choices, ChoicesMeta): choices = choices.choices if isinstance(choices, collections.abc.Iterator): choices = list(choices) self.choices = choices self.help_text = help_text self.db_index = db_index self.db_column = db_column self.db_comment = db_comment self._db_tablespace = db_tablespace self.auto_created = auto_created # Adjust the appropriate creation counter, and save our local copy. if auto_created: self.creation_counter = Field.auto_creation_counter Field.auto_creation_counter -= 1 else: self.creation_counter = Field.creation_counter Field.creation_counter += 1 self._validators = list(validators) # Store for deconstruction later self._error_messages = error_messages # Store for deconstruction later def __str__(self): """ Return "app_label.model_label.field_name" for fields attached to models. """ if not hasattr(self, "model"): return super().__str__() model = self.model return "%s.%s" % (model._meta.label, self.name) def __repr__(self): """Display the module, class, and name of the field.""" path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__) name = getattr(self, "name", None) if name is not None: return "<%s: %s>" % (path, name) return "<%s>" % path def check(self, **kwargs): return [ *self._check_field_name(), *self._check_choices(), *self._check_db_index(), *self._check_db_comment(**kwargs), *self._check_null_allowed_for_primary_keys(), *self._check_backend_specific_checks(**kwargs), *self._check_validators(), *self._check_deprecation_details(), ] def _check_field_name(self): """ Check if field name is valid, i.e. 1) does not end with an underscore, 2) does not contain "__" and 3) is not "pk". """ if self.name.endswith("_"): return [ checks.Error( "Field names must not end with an underscore.", obj=self, id="fields.E001", ) ] elif LOOKUP_SEP in self.name: return [ checks.Error( 'Field names must not contain "%s".' % LOOKUP_SEP, obj=self, id="fields.E002", ) ] elif self.name == "pk": return [ checks.Error( "'pk' is a reserved word that cannot be used as a field name.", obj=self, id="fields.E003", ) ] else: return [] @classmethod def _choices_is_value(cls, value): return isinstance(value, (str, Promise)) or not is_iterable(value) def _check_choices(self): if not self.choices: return [] if not is_iterable(self.choices) or isinstance(self.choices, str): return [ checks.Error( "'choices' must be an iterable (e.g., a list or tuple).", obj=self, id="fields.E004", ) ] choice_max_length = 0 # Expect [group_name, [value, display]] for choices_group in self.choices: try: group_name, group_choices = choices_group except (TypeError, ValueError): # Containing non-pairs break try: if not all( self._choices_is_value(value) and self._choices_is_value(human_name) 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 self._choices_is_value(value) or not self._choices_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 [ checks.Error( "'choices' must be an iterable containing " "(actual value, human readable name) tuples.", obj=self, id="fields.E005", ) ] def _check_db_index(self): if self.db_index not in (None, True, False): return [ checks.Error( "'db_index' must be None, True or False.", obj=self, id="fields.E006", ) ] else: return [] def _check_db_comment(self, databases=None, **kwargs): if not self.db_comment or not databases: return [] errors = [] for db in databases: if not router.allow_migrate_model(db, self.model): continue connection = connections[db] if not ( connection.features.supports_comments or "supports_comments" in self.model._meta.required_db_features ): errors.append( checks.Warning( f"{connection.display_name} does not support comments on " f"columns (db_comment).", obj=self, id="fields.W163", ) ) return errors def _check_null_allowed_for_primary_keys(self): if ( self.primary_key and self.null and not connection.features.interprets_empty_strings_as_nulls ): # We cannot reliably check this for backends like Oracle which # consider NULL and '' to be equal (and thus set up # character-based fields a little differently). return [ checks.Error( "Primary keys must not have null=True.", hint=( "Set null=False on the field, or " "remove primary_key=True argument." ), obj=self, id="fields.E007", ) ] else: return [] def _check_backend_specific_checks(self, databases=None, **kwargs): if databases is None: return [] errors = [] for alias in databases: if router.allow_migrate_model(alias, self.model): errors.extend(connections[alias].validation.check_field(self, **kwargs)) return errors def _check_validators(self): errors = [] for i, validator in enumerate(self.validators): if not callable(validator): errors.append( checks.Error( "All 'validators' must be callable.", hint=( "validators[{i}] ({repr}) isn't a function or " "instance of a validator class.".format( i=i, repr=repr(validator), ) ), obj=self, id="fields.E008", ) ) return errors def _check_deprecation_details(self): if self.system_check_removed_details is not None: return [ checks.Error( self.system_check_removed_details.get( "msg", "%s has been removed except for support in historical " "migrations." % self.__class__.__name__, ), hint=self.system_check_removed_details.get("hint"), obj=self, id=self.system_check_removed_details.get("id", "fields.EXXX"), ) ] elif self.system_check_deprecated_details is not None: return [ checks.Warning( self.system_check_deprecated_details.get( "msg", "%s has been deprecated." % self.__class__.__name__ ), hint=self.system_check_deprecated_details.get("hint"), obj=self, id=self.system_check_deprecated_details.get("id", "fields.WXXX"), ) ] return [] def get_col(self, alias, output_field=None): if alias == self.model._meta.db_table and ( output_field is None or output_field == self ): return self.cached_col from django.db.models.expressions import Col return Col(alias, self, output_field) @cached_property def cached_col(self): from django.db.models.expressions import Col return Col(self.model._meta.db_table, self) def select_format(self, compiler, sql, params): """ Custom format for select clauses. For example, GIS columns need to be selected as AsText(table.col) on MySQL as the table.col data can't be used by Django. """ return sql, params def deconstruct(self): """ Return enough information to recreate the field as a 4-tuple: * The name of the field on the model, if contribute_to_class() has been run. * The import path of the field, including the class, e.g. django.db.models.IntegerField. This should be the most portable version, so less specific may be better. * A list of positional arguments. * A dict of keyword arguments. Note that the positional or keyword arguments must contain values of the following types (including inner values of collection types): * None, bool, str, int, float, complex, set, frozenset, list, tuple, dict * UUID * datetime.datetime (naive), datetime.date * top-level classes, top-level functions - will be referenced by their full import path * Storage instances - these have their own deconstruct() method This is because the values here must be serialized into a text format (possibly new Python code, possibly JSON) and these are the only types with encoding handlers defined. There's no need to return the exact way the field was instantiated this time, just ensure that the resulting field is the same - prefer keyword arguments over positional ones, and omit parameters with their default values. """ # Short-form way of fetching all the default parameters keywords = {} possibles = { "verbose_name": None, "primary_key": False, "max_length": None, "unique": False, "blank": False, "null": False, "db_index": False, "default": NOT_PROVIDED, "editable": True, "serialize": True, "unique_for_date": None, "unique_for_month": None, "unique_for_year": None, "choices": None, "help_text": "", "db_column": None, "db_comment": None, "db_tablespace": None, "auto_created": False, "validators": [], "error_messages": None, } attr_overrides = { "unique": "_unique", "error_messages": "_error_messages", "validators": "_validators", "verbose_name": "_verbose_name", "db_tablespace": "_db_tablespace", } equals_comparison = {"choices", "validators"} for name, default in possibles.items(): value = getattr(self, attr_overrides.get(name, name)) # Unroll anything iterable for choices into a concrete list if name == "choices" and isinstance(value, collections.abc.Iterable): value = list(value) # Do correct kind of comparison if name in equals_comparison: if value != default: keywords[name] = value else: if value is not default: keywords[name] = value # Work out path - we shorten it for known Django core fields path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__) if path.startswith("django.db.models.fields.related"): path = path.replace("django.db.models.fields.related", "django.db.models") elif path.startswith("django.db.models.fields.files"): path = path.replace("django.db.models.fields.files", "django.db.models") elif path.startswith("django.db.models.fields.json"): path = path.replace("django.db.models.fields.json", "django.db.models") elif path.startswith("django.db.models.fields.proxy"): path = path.replace("django.db.models.fields.proxy", "django.db.models") elif path.startswith("django.db.models.fields"): path = path.replace("django.db.models.fields", "django.db.models") # Return basic info - other fields should override this. return (self.name, path, [], keywords) def clone(self): """ Uses deconstruct() to clone a new copy of this Field. Will not preserve any class attachments/attribute names. """ name, path, args, kwargs = self.deconstruct() return self.__class__(*args, **kwargs) def __eq__(self, other): # Needed for @total_ordering if isinstance(other, Field): return self.creation_counter == other.creation_counter and getattr( self, "model", None ) == getattr(other, "model", None) return NotImplemented def __lt__(self, other): # This is needed because bisect does not take a comparison function. # Order by creation_counter first for backward compatibility. if isinstance(other, Field): if ( self.creation_counter != other.creation_counter or not hasattr(self, "model") and not hasattr(other, "model") ): return self.creation_counter < other.creation_counter elif hasattr(self, "model") != hasattr(other, "model"): return not hasattr(self, "model") # Order no-model fields first else: # creation_counter's are equal, compare only models. return (self.model._meta.app_label, self.model._meta.model_name) < ( other.model._meta.app_label, other.model._meta.model_name, ) return NotImplemented def __hash__(self): return hash(self.creation_counter) def __deepcopy__(self, memodict): # We don't have to deepcopy very much here, since most things are not # intended to be altered after initial creation. obj = copy.copy(self) if self.remote_field: obj.remote_field = copy.copy(self.remote_field) if hasattr(self.remote_field, "field") and self.remote_field.field is self: obj.remote_field.field = obj memodict[id(self)] = obj return obj def __copy__(self): # We need to avoid hitting __reduce__, so define this # slightly weird copy construct. obj = Empty() obj.__class__ = self.__class__ obj.__dict__ = self.__dict__.copy() return obj def __reduce__(self): """ Pickling should return the model._meta.fields instance of the field, not a new copy of that field. So, use the app registry to load the model and then the field back. """ if not hasattr(self, "model"): # Fields are sometimes used without attaching them to models (for # example in aggregation). In this case give back a plain field # instance. The code below will create a new empty instance of # class self.__class__, then update its dict with self.__dict__ # values - so, this is very close to normal pickle. state = self.__dict__.copy() # The _get_default cached_property can't be pickled due to lambda # usage. state.pop("_get_default", None) return _empty, (self.__class__,), state return _load_field, ( self.model._meta.app_label, self.model._meta.object_name, self.name, ) def get_pk_value_on_save(self, instance): """ Hook to generate new PK values on save. This method is called when saving instances with no primary key value set. If this method returns something else than None, then the returned value is used when saving the new instance. """ if self.default: return self.get_default() return None def to_python(self, value): """ Convert the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Return the converted value. Subclasses should override this. """ return value @cached_property def error_messages(self): messages = {} for c in reversed(self.__class__.__mro__): messages.update(getattr(c, "default_error_messages", {})) messages.update(self._error_messages or {}) return messages @cached_property def validators(self): """ Some validators can't be created at field initialization time. This method provides a way to delay their creation until required. """ return [*self.default_validators, *self._validators] def run_validators(self, value): if value in self.empty_values: return errors = [] for v in self.validators: try: v(value) except exceptions.ValidationError as e: if hasattr(e, "code") and e.code in self.error_messages: e.message = self.error_messages[e.code] errors.extend(e.error_list) if errors: raise exceptions.ValidationError(errors) def validate(self, value, model_instance): """ Validate value and raise ValidationError if necessary. Subclasses should override this to provide validation logic. """ if not self.editable: # Skip validation for non-editable fields. return if self.choices is not None and value not in self.empty_values: for option_key, option_value in self.choices: if isinstance(option_value, (list, tuple)): # This is an optgroup, so look inside the group for # options. for optgroup_key, optgroup_value in option_value: if value == optgroup_key: return elif value == option_key: return raise exceptions.ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}, ) if value is None and not self.null: raise exceptions.ValidationError(self.error_messages["null"], code="null") if not self.blank and value in self.empty_values: raise exceptions.ValidationError(self.error_messages["blank"], code="blank") def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ value = self.to_python(value) self.validate(value, model_instance) self.run_validators(value) return value def db_type_parameters(self, connection): return DictWrapper(self.__dict__, connection.ops.quote_name, "qn_") def db_check(self, connection): """ Return the database column check constraint for this field, for the provided connection. Works the same way as db_type() for the case that get_internal_type() does not map to a preexisting model field. """ data = self.db_type_parameters(connection) try: return ( connection.data_type_check_constraints[self.get_internal_type()] % data ) except KeyError: return None def db_type(self, connection): """ Return the database column data type for this field, for the provided connection. """ # The default implementation of this method looks at the # backend-specific data_types dictionary, looking up the field by its # "internal type". # # A Field class can implement the get_internal_type() method to specify # which *preexisting* Django Field class it's most similar to -- i.e., # a custom field might be represented by a TEXT column type, which is # the same as the TextField Django field type, which means the custom # field's get_internal_type() returns 'TextField'. # # But the limitation of the get_internal_type() / data_types approach # is that it cannot handle database column types that aren't already # mapped to one of the built-in Django field types. In this case, you # can implement db_type() instead of get_internal_type() to specify # exactly which wacky database column type you want to use. data = self.db_type_parameters(connection) try: column_type = connection.data_types[self.get_internal_type()] except KeyError: return None else: # column_type is either a single-parameter function or a string. if callable(column_type): return column_type(data) return column_type % data def rel_db_type(self, connection): """ Return the data type that a related field pointing to this field should use. For example, this method is called by ForeignKey and OneToOneField to determine its data type. """ return self.db_type(connection) def cast_db_type(self, connection): """Return the data type to use in the Cast() function.""" db_type = connection.ops.cast_data_types.get(self.get_internal_type()) if db_type: return db_type % self.db_type_parameters(connection) return self.db_type(connection) def db_parameters(self, connection): """ Extension of db_type(), providing a range of different return values (type, checks). This will look at db_type(), allowing custom model fields to override it. """ type_string = self.db_type(connection) check_string = self.db_check(connection) return { "type": type_string, "check": check_string, } def db_type_suffix(self, connection): return connection.data_types_suffix.get(self.get_internal_type()) def get_db_converters(self, connection): if hasattr(self, "from_db_value"): return [self.from_db_value] return [] @property def unique(self): return self._unique or self.primary_key @property def db_tablespace(self): return self._db_tablespace or settings.DEFAULT_INDEX_TABLESPACE @property def db_returning(self): """ Private API intended only to be used by Django itself. Currently only the PostgreSQL backend supports returning multiple fields on a model. """ return False def set_attributes_from_name(self, name): self.name = self.name or name self.attname, self.column = self.get_attname_column() self.concrete = self.column is not None if self.verbose_name is None and self.name: self.verbose_name = self.name.replace("_", " ") def contribute_to_class(self, cls, name, private_only=False): """ Register the field with the model class it belongs to. If private_only is True, create a separate instance of this field for every subclass of cls, even if cls is not an abstract model. """ self.set_attributes_from_name(name) self.model = cls cls._meta.add_field(self, private=private_only) if self.column: setattr(cls, self.attname, self.descriptor_class(self)) if self.choices is not None: # Don't override a get_FOO_display() method defined explicitly on # this class, but don't check methods derived from inheritance, to # allow overriding inherited choices. For more complex inheritance # structures users should override contribute_to_class(). if "get_%s_display" % self.name not in cls.__dict__: setattr( cls, "get_%s_display" % self.name, partialmethod(cls._get_FIELD_display, field=self), ) def get_filter_kwargs_for_object(self, obj): """ Return a dict that when passed as kwargs to self.model.filter(), would yield all instances having the same value for this field as obj has. """ return {self.name: getattr(obj, self.attname)} def get_attname(self): return self.name def get_attname_column(self): attname = self.get_attname() column = self.db_column or attname return attname, column def get_internal_type(self): return self.__class__.__name__ def pre_save(self, model_instance, add): """Return field's value just before saving.""" return getattr(model_instance, self.attname) def get_prep_value(self, value): """Perform preliminary non-db specific value checks and conversions.""" if isinstance(value, Promise): value = value._proxy____cast() return value def get_db_prep_value(self, value, connection, prepared=False): """ Return field's value prepared for interacting with the database backend. Used by the default implementations of get_db_prep_save(). """ if not prepared: value = self.get_prep_value(value) return value def get_db_prep_save(self, value, connection): """Return field's value prepared for saving into a database.""" if hasattr(value, "as_sql"): return value return self.get_db_prep_value(value, connection=connection, prepared=False) def has_default(self): """Return a boolean of whether this field has a default value.""" return self.default is not NOT_PROVIDED def get_default(self): """Return the default value for this field.""" return self._get_default() @cached_property def _get_default(self): if self.has_default(): if callable(self.default): return self.default return lambda: self.default if ( not self.empty_strings_allowed or self.null and not connection.features.interprets_empty_strings_as_nulls ): return return_None return str # return empty string def get_choices( self, include_blank=True, blank_choice=BLANK_CHOICE_DASH, limit_choices_to=None, ordering=(), ): """ Return choices with a default blank choices included, for use as <select> choices for this field. """ if self.choices is not None: choices = list(self.choices) if include_blank: blank_defined = any( choice in ("", None) for choice, _ in self.flatchoices ) if not blank_defined: choices = blank_choice + choices return choices rel_model = self.remote_field.model limit_choices_to = limit_choices_to or self.get_limit_choices_to() choice_func = operator.attrgetter( self.remote_field.get_related_field().attname if hasattr(self.remote_field, "get_related_field") else "pk" ) qs = rel_model._default_manager.complex_filter(limit_choices_to) if ordering: qs = qs.order_by(*ordering) return (blank_choice if include_blank else []) + [ (choice_func(x), str(x)) for x in qs ] def value_to_string(self, obj): """ Return a string value of this field from the passed obj. This is used by the serialization framework. """ return str(self.value_from_object(obj)) def _get_flatchoices(self): """Flattened version of choices tuple.""" if self.choices is None: return [] flat = [] for choice, value in self.choices: if isinstance(value, (list, tuple)): flat.extend(value) else: flat.append((choice, value)) return flat flatchoices = property(_get_flatchoices) def save_form_data(self, instance, data): setattr(instance, self.name, data) def formfield(self, form_class=None, choices_form_class=None, **kwargs): """Return a django.forms.Field instance for this field.""" defaults = { "required": not self.blank, "label": capfirst(self.verbose_name), "help_text": self.help_text, } if self.has_default(): if callable(self.default): defaults["initial"] = self.default defaults["show_hidden_initial"] = True else: defaults["initial"] = self.get_default() if self.choices is not None: # Fields with choices get special treatment. include_blank = self.blank or not ( self.has_default() or "initial" in kwargs ) defaults["choices"] = self.get_choices(include_blank=include_blank) defaults["coerce"] = self.to_python if self.null: defaults["empty_value"] = None if choices_form_class is not None: form_class = choices_form_class else: form_class = forms.TypedChoiceField # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that TypedChoiceField will understand. for k in list(kwargs): if k not in ( "coerce", "empty_value", "choices", "required", "widget", "label", "initial", "help_text", "error_messages", "show_hidden_initial", "disabled", ): del kwargs[k] defaults.update(kwargs) if form_class is None: form_class = forms.CharField return form_class(**defaults) def value_from_object(self, obj): """Return the value of this field in the given model instance.""" return getattr(obj, self.attname) class BooleanField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be either True or False."), "invalid_nullable": _("“%(value)s” value must be either True, False, or None."), } description = _("Boolean (Either True or False)") def get_internal_type(self): return "BooleanField" def to_python(self, value): if self.null and value in self.empty_values: return None if value in (True, False): # 1/0 are equal to True/False. bool() converts former to latter. return bool(value) if value in ("t", "True", "1"): return True if value in ("f", "False", "0"): return False raise exceptions.ValidationError( self.error_messages["invalid_nullable" if self.null else "invalid"], code="invalid", params={"value": value}, ) def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return self.to_python(value) def formfield(self, **kwargs): if self.choices is not None: include_blank = not (self.has_default() or "initial" in kwargs) defaults = {"choices": self.get_choices(include_blank=include_blank)} else: form_class = forms.NullBooleanField if self.null else forms.BooleanField # In HTML checkboxes, 'required' means "must be checked" which is # different from the choices case ("must select some value"). # required=False allows unchecked checkboxes. defaults = {"form_class": form_class, "required": False} return super().formfield(**{**defaults, **kwargs}) class CharField(Field): def __init__(self, *args, db_collation=None, **kwargs): super().__init__(*args, **kwargs) self.db_collation = db_collation if self.max_length is not None: self.validators.append(validators.MaxLengthValidator(self.max_length)) @property def description(self): if self.max_length is not None: return _("String (up to %(max_length)s)") else: return _("String (unlimited)") def check(self, **kwargs): databases = kwargs.get("databases") or [] return [ *super().check(**kwargs), *self._check_db_collation(databases), *self._check_max_length_attribute(**kwargs), ] def _check_max_length_attribute(self, **kwargs): if self.max_length is None: if ( connection.features.supports_unlimited_charfield or "supports_unlimited_charfield" in self.model._meta.required_db_features ): return [] return [ checks.Error( "CharFields must define a 'max_length' attribute.", obj=self, id="fields.E120", ) ] elif ( not isinstance(self.max_length, int) or isinstance(self.max_length, bool) or self.max_length <= 0 ): return [ checks.Error( "'max_length' must be a positive integer.", obj=self, id="fields.E121", ) ] else: return [] def _check_db_collation(self, databases): errors = [] for db in databases: if not router.allow_migrate_model(db, self.model): continue connection = connections[db] if not ( self.db_collation is None or "supports_collation_on_charfield" in self.model._meta.required_db_features or connection.features.supports_collation_on_charfield ): errors.append( checks.Error( "%s does not support a database collation on " "CharFields." % connection.display_name, obj=self, id="fields.E190", ), ) return errors def cast_db_type(self, connection): if self.max_length is None: return connection.ops.cast_char_field_without_max_length return super().cast_db_type(connection) def db_parameters(self, connection): db_params = super().db_parameters(connection) db_params["collation"] = self.db_collation return db_params def get_internal_type(self): return "CharField" def to_python(self, value): if isinstance(value, str) or value is None: return value return str(value) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): # Passing max_length to forms.CharField means that the value's length # will be validated twice. This is considered acceptable since we want # the value in the form field (to pass into widget for example). defaults = {"max_length": self.max_length} # TODO: Handle multiple backends with different feature flags. if self.null and not connection.features.interprets_empty_strings_as_nulls: defaults["empty_value"] = None defaults.update(kwargs) return super().formfield(**defaults) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.db_collation: kwargs["db_collation"] = self.db_collation return name, path, args, kwargs class CommaSeparatedIntegerField(CharField): default_validators = [validators.validate_comma_separated_integer_list] description = _("Comma-separated integers") system_check_removed_details = { "msg": ( "CommaSeparatedIntegerField is removed except for support in " "historical migrations." ), "hint": ( "Use CharField(validators=[validate_comma_separated_integer_list]) " "instead." ), "id": "fields.E901", } def _to_naive(value): if timezone.is_aware(value): value = timezone.make_naive(value, datetime.timezone.utc) return value def _get_naive_now(): return _to_naive(timezone.now()) class DateTimeCheckMixin: def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_mutually_exclusive_options(), *self._check_fix_default_value(), ] def _check_mutually_exclusive_options(self): # auto_now, auto_now_add, and default are mutually exclusive # options. The use of more than one of these options together # will trigger an Error mutually_exclusive_options = [ self.auto_now_add, self.auto_now, self.has_default(), ] enabled_options = [ option not in (None, False) for option in mutually_exclusive_options ].count(True) if enabled_options > 1: return [ checks.Error( "The options auto_now, auto_now_add, and default " "are mutually exclusive. Only one of these options " "may be present.", obj=self, id="fields.E160", ) ] else: return [] def _check_fix_default_value(self): return [] # Concrete subclasses use this in their implementations of # _check_fix_default_value(). def _check_if_value_fixed(self, value, now=None): """ Check if the given value appears to have been provided as a "fixed" time value, and include a warning in the returned list if it does. The value argument must be a date object or aware/naive datetime object. If now is provided, it must be a naive datetime object. """ if now is None: now = _get_naive_now() offset = datetime.timedelta(seconds=10) lower = now - offset upper = now + offset if isinstance(value, datetime.datetime): value = _to_naive(value) else: assert isinstance(value, datetime.date) lower = lower.date() upper = upper.date() if lower <= value <= upper: return [ checks.Warning( "Fixed default value provided.", hint=( "It seems you set a fixed date / time / datetime " "value as default for this field. This may not be " "what you want. If you want to have the current date " "as default, use `django.utils.timezone.now`" ), obj=self, id="fields.W161", ) ] return [] class DateField(DateTimeCheckMixin, Field): empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid date format. It must be " "in YYYY-MM-DD format." ), "invalid_date": _( "“%(value)s” value has the correct format (YYYY-MM-DD) " "but it is an invalid date." ), } description = _("Date (without time)") def __init__( self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs ): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs["editable"] = False kwargs["blank"] = True super().__init__(verbose_name, name, **kwargs) def _check_fix_default_value(self): """ Warn that using an actual date or datetime value is probably wrong; it's only evaluated on server startup. """ if not self.has_default(): return [] value = self.default if isinstance(value, datetime.datetime): value = _to_naive(value).date() elif isinstance(value, datetime.date): pass else: # No explicit date / datetime value -- no checks necessary return [] # At this point, value is a date object. return self._check_if_value_fixed(value) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.auto_now: kwargs["auto_now"] = True if self.auto_now_add: kwargs["auto_now_add"] = True if self.auto_now or self.auto_now_add: del kwargs["editable"] del kwargs["blank"] return name, path, args, kwargs def get_internal_type(self): return "DateField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): if settings.USE_TZ and timezone.is_aware(value): # Convert aware datetimes to the default time zone # before casting them to dates (#17742). default_timezone = timezone.get_default_timezone() value = timezone.make_naive(value, default_timezone) return value.date() if isinstance(value, datetime.date): return value try: parsed = parse_date(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_date"], code="invalid_date", params={"value": value}, ) raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.date.today() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) def contribute_to_class(self, cls, name, **kwargs): super().contribute_to_class(cls, name, **kwargs) if not self.null: setattr( cls, "get_next_by_%s" % self.name, partialmethod( cls._get_next_or_previous_by_FIELD, field=self, is_next=True ), ) setattr( cls, "get_previous_by_%s" % self.name, partialmethod( cls._get_next_or_previous_by_FIELD, field=self, is_next=False ), ) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts dates into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_datefield_value(value) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else val.isoformat() def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.DateField, **kwargs, } ) class DateTimeField(DateField): empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid format. It must be in " "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format." ), "invalid_date": _( "“%(value)s” value has the correct format " "(YYYY-MM-DD) but it is an invalid date." ), "invalid_datetime": _( "“%(value)s” value has the correct format " "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) " "but it is an invalid date/time." ), } description = _("Date (with time)") # __init__ is inherited from DateField def _check_fix_default_value(self): """ Warn that using an actual date or datetime value is probably wrong; it's only evaluated on server startup. """ if not self.has_default(): return [] value = self.default if isinstance(value, (datetime.datetime, datetime.date)): return self._check_if_value_fixed(value) # No explicit date / datetime value -- no checks necessary. return [] def get_internal_type(self): return "DateTimeField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): value = datetime.datetime(value.year, value.month, value.day) if settings.USE_TZ: # For backwards compatibility, interpret naive datetimes in # local time. This won't work during DST change, but we can't # do much about it, so we let the exceptions percolate up the # call stack. warnings.warn( "DateTimeField %s.%s received a naive datetime " "(%s) while time zone support is active." % (self.model.__name__, self.name, value), RuntimeWarning, ) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value try: parsed = parse_datetime(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_datetime"], code="invalid_datetime", params={"value": value}, ) try: parsed = parse_date(value) if parsed is not None: return datetime.datetime(parsed.year, parsed.month, parsed.day) except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_date"], code="invalid_date", params={"value": value}, ) raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = timezone.now() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) # contribute_to_class is inherited from DateField, it registers # get_next_by_FOO and get_prev_by_FOO def get_prep_value(self, value): value = super().get_prep_value(value) value = self.to_python(value) if value is not None and settings.USE_TZ and timezone.is_naive(value): # For backwards compatibility, interpret naive datetimes in local # time. This won't work during DST change, but we can't do much # about it, so we let the exceptions percolate up the call stack. try: name = "%s.%s" % (self.model.__name__, self.name) except AttributeError: name = "(unbound)" warnings.warn( "DateTimeField %s received a naive datetime (%s)" " while time zone support is active." % (name, value), RuntimeWarning, ) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value def get_db_prep_value(self, value, connection, prepared=False): # Casts datetimes into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_datetimefield_value(value) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else val.isoformat() def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.DateTimeField, **kwargs, } ) class DecimalField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be a decimal number."), } description = _("Decimal number") def __init__( self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs, ): self.max_digits, self.decimal_places = max_digits, decimal_places super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): errors = super().check(**kwargs) digits_errors = [ *self._check_decimal_places(), *self._check_max_digits(), ] if not digits_errors: errors.extend(self._check_decimal_places_and_max_digits(**kwargs)) else: errors.extend(digits_errors) return errors def _check_decimal_places(self): try: decimal_places = int(self.decimal_places) if decimal_places < 0: raise ValueError() except TypeError: return [ checks.Error( "DecimalFields must define a 'decimal_places' attribute.", obj=self, id="fields.E130", ) ] except ValueError: return [ checks.Error( "'decimal_places' must be a non-negative integer.", obj=self, id="fields.E131", ) ] else: return [] def _check_max_digits(self): try: max_digits = int(self.max_digits) if max_digits <= 0: raise ValueError() except TypeError: return [ checks.Error( "DecimalFields must define a 'max_digits' attribute.", obj=self, id="fields.E132", ) ] except ValueError: return [ checks.Error( "'max_digits' must be a positive integer.", obj=self, id="fields.E133", ) ] else: return [] def _check_decimal_places_and_max_digits(self, **kwargs): if int(self.decimal_places) > int(self.max_digits): return [ checks.Error( "'max_digits' must be greater or equal to 'decimal_places'.", obj=self, id="fields.E134", ) ] return [] @cached_property def validators(self): return super().validators + [ validators.DecimalValidator(self.max_digits, self.decimal_places) ] @cached_property def context(self): return decimal.Context(prec=self.max_digits) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.max_digits is not None: kwargs["max_digits"] = self.max_digits if self.decimal_places is not None: kwargs["decimal_places"] = self.decimal_places return name, path, args, kwargs def get_internal_type(self): return "DecimalField" def to_python(self, value): if value is None: return value try: if isinstance(value, float): decimal_value = self.context.create_decimal_from_float(value) else: decimal_value = decimal.Decimal(value) except (decimal.InvalidOperation, TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) if not decimal_value.is_finite(): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) return decimal_value def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) if hasattr(value, "as_sql"): return value return connection.ops.adapt_decimalfield_value( value, self.max_digits, self.decimal_places ) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): return super().formfield( **{ "max_digits": self.max_digits, "decimal_places": self.decimal_places, "form_class": forms.DecimalField, **kwargs, } ) class DurationField(Field): """ Store timedelta objects. Use interval on PostgreSQL, INTERVAL DAY TO SECOND on Oracle, and bigint of microseconds on other databases. """ empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid format. It must be in " "[DD] [[HH:]MM:]ss[.uuuuuu] format." ) } description = _("Duration") def get_internal_type(self): return "DurationField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.timedelta): return value try: parsed = parse_duration(value) except ValueError: pass else: if parsed is not None: return parsed raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def get_db_prep_value(self, value, connection, prepared=False): if connection.features.has_native_duration_field: return value if value is None: return None return duration_microseconds(value) def get_db_converters(self, connection): converters = [] if not connection.features.has_native_duration_field: converters.append(connection.ops.convert_durationfield_value) return converters + super().get_db_converters(connection) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else duration_string(val) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.DurationField, **kwargs, } ) class EmailField(CharField): default_validators = [validators.validate_email] description = _("Email address") def __init__(self, *args, **kwargs): # max_length=254 to be compliant with RFCs 3696 and 5321 kwargs.setdefault("max_length", 254) super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() # We do not exclude max_length if it matches default as we want to change # the default in future. return name, path, args, kwargs def formfield(self, **kwargs): # As with CharField, this will cause email validation to be performed # twice. return super().formfield( **{ "form_class": forms.EmailField, **kwargs, } ) class FilePathField(Field): description = _("File path") def __init__( self, verbose_name=None, name=None, path="", match=None, recursive=False, allow_files=True, allow_folders=False, **kwargs, ): self.path, self.match, self.recursive = path, match, recursive self.allow_files, self.allow_folders = allow_files, allow_folders kwargs.setdefault("max_length", 100) super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_allowing_files_or_folders(**kwargs), ] def _check_allowing_files_or_folders(self, **kwargs): if not self.allow_files and not self.allow_folders: return [ checks.Error( "FilePathFields must have either 'allow_files' or 'allow_folders' " "set to True.", obj=self, id="fields.E140", ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.path != "": kwargs["path"] = self.path if self.match is not None: kwargs["match"] = self.match if self.recursive is not False: kwargs["recursive"] = self.recursive if self.allow_files is not True: kwargs["allow_files"] = self.allow_files if self.allow_folders is not False: kwargs["allow_folders"] = self.allow_folders if kwargs.get("max_length") == 100: del kwargs["max_length"] return name, path, args, kwargs def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return str(value) def formfield(self, **kwargs): return super().formfield( **{ "path": self.path() if callable(self.path) else self.path, "match": self.match, "recursive": self.recursive, "form_class": forms.FilePathField, "allow_files": self.allow_files, "allow_folders": self.allow_folders, **kwargs, } ) def get_internal_type(self): return "FilePathField" class FloatField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be a float."), } description = _("Floating point number") def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None try: return float(value) except (TypeError, ValueError) as e: raise e.__class__( "Field '%s' expected a number but got %r." % (self.name, value), ) from e def get_internal_type(self): return "FloatField" def to_python(self, value): if value is None: return value try: return float(value) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.FloatField, **kwargs, } ) class IntegerField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be an integer."), } description = _("Integer") def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_max_length_warning(), ] def _check_max_length_warning(self): if self.max_length is not None: return [ checks.Warning( "'max_length' is ignored when used with %s." % self.__class__.__name__, hint="Remove 'max_length' from field", obj=self, id="fields.W122", ) ] return [] @cached_property def validators(self): # These validators can't be added at field initialization time since # they're based on values retrieved from `connection`. validators_ = super().validators internal_type = self.get_internal_type() min_value, max_value = connection.ops.integer_field_range(internal_type) if min_value is not None and not any( ( isinstance(validator, validators.MinValueValidator) and ( validator.limit_value() if callable(validator.limit_value) else validator.limit_value ) >= min_value ) for validator in validators_ ): validators_.append(validators.MinValueValidator(min_value)) if max_value is not None and not any( ( isinstance(validator, validators.MaxValueValidator) and ( validator.limit_value() if callable(validator.limit_value) else validator.limit_value ) <= max_value ) for validator in validators_ ): validators_.append(validators.MaxValueValidator(max_value)) return validators_ def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None try: return int(value) except (TypeError, ValueError) as e: raise e.__class__( "Field '%s' expected a number but got %r." % (self.name, value), ) from e def get_db_prep_value(self, value, connection, prepared=False): value = super().get_db_prep_value(value, connection, prepared) return connection.ops.adapt_integerfield_value(value, self.get_internal_type()) def get_internal_type(self): return "IntegerField" def to_python(self, value): if value is None: return value try: return int(value) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.IntegerField, **kwargs, } ) class BigIntegerField(IntegerField): description = _("Big (8 byte) integer") MAX_BIGINT = 9223372036854775807 def get_internal_type(self): return "BigIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": -BigIntegerField.MAX_BIGINT - 1, "max_value": BigIntegerField.MAX_BIGINT, **kwargs, } ) class SmallIntegerField(IntegerField): description = _("Small integer") def get_internal_type(self): return "SmallIntegerField" class IPAddressField(Field): empty_strings_allowed = False description = _("IPv4 address") system_check_removed_details = { "msg": ( "IPAddressField has been removed except for support in " "historical migrations." ), "hint": "Use GenericIPAddressField instead.", "id": "fields.E900", } def __init__(self, *args, **kwargs): kwargs["max_length"] = 15 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return str(value) def get_internal_type(self): return "IPAddressField" class GenericIPAddressField(Field): empty_strings_allowed = False description = _("IP address") default_error_messages = {} def __init__( self, verbose_name=None, name=None, protocol="both", unpack_ipv4=False, *args, **kwargs, ): self.unpack_ipv4 = unpack_ipv4 self.protocol = protocol ( self.default_validators, invalid_error_message, ) = validators.ip_address_validators(protocol, unpack_ipv4) self.default_error_messages["invalid"] = invalid_error_message kwargs["max_length"] = 39 super().__init__(verbose_name, name, *args, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_blank_and_null_values(**kwargs), ] def _check_blank_and_null_values(self, **kwargs): if not getattr(self, "null", False) and getattr(self, "blank", False): return [ checks.Error( "GenericIPAddressFields cannot have blank=True if null=False, " "as blank values are stored as nulls.", obj=self, id="fields.E150", ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.unpack_ipv4 is not False: kwargs["unpack_ipv4"] = self.unpack_ipv4 if self.protocol != "both": kwargs["protocol"] = self.protocol if kwargs.get("max_length") == 39: del kwargs["max_length"] return name, path, args, kwargs def get_internal_type(self): return "GenericIPAddressField" def to_python(self, value): if value is None: return None if not isinstance(value, str): value = str(value) value = value.strip() if ":" in value: return clean_ipv6_address( value, self.unpack_ipv4, self.error_messages["invalid"] ) return value def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_ipaddressfield_value(value) def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None if value and ":" in value: try: return clean_ipv6_address(value, self.unpack_ipv4) except exceptions.ValidationError: pass return str(value) def formfield(self, **kwargs): return super().formfield( **{ "protocol": self.protocol, "form_class": forms.GenericIPAddressField, **kwargs, } ) class NullBooleanField(BooleanField): default_error_messages = { "invalid": _("“%(value)s” value must be either None, True or False."), "invalid_nullable": _("“%(value)s” value must be either None, True or False."), } description = _("Boolean (Either True, False or None)") system_check_removed_details = { "msg": ( "NullBooleanField is removed except for support in historical " "migrations." ), "hint": "Use BooleanField(null=True) instead.", "id": "fields.E903", } def __init__(self, *args, **kwargs): kwargs["null"] = True kwargs["blank"] = True super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["null"] del kwargs["blank"] return name, path, args, kwargs class PositiveIntegerRelDbTypeMixin: def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) if not hasattr(cls, "integer_field_class"): cls.integer_field_class = next( ( parent for parent in cls.__mro__[1:] if issubclass(parent, IntegerField) ), None, ) def rel_db_type(self, connection): """ Return the data type that a related field pointing to this field should use. In most cases, a foreign key pointing to a positive integer primary key will have an integer column data type but some databases (e.g. MySQL) have an unsigned integer type. In that case (related_fields_match_type=True), the primary key should return its db_type. """ if connection.features.related_fields_match_type: return self.db_type(connection) else: return self.integer_field_class().db_type(connection=connection) class PositiveBigIntegerField(PositiveIntegerRelDbTypeMixin, BigIntegerField): description = _("Positive big integer") def get_internal_type(self): return "PositiveBigIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": 0, **kwargs, } ) class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField): description = _("Positive integer") def get_internal_type(self): return "PositiveIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": 0, **kwargs, } ) class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, SmallIntegerField): description = _("Positive small integer") def get_internal_type(self): return "PositiveSmallIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": 0, **kwargs, } ) class SlugField(CharField): default_validators = [validators.validate_slug] description = _("Slug (up to %(max_length)s)") def __init__( self, *args, max_length=50, db_index=True, allow_unicode=False, **kwargs ): self.allow_unicode = allow_unicode if self.allow_unicode: self.default_validators = [validators.validate_unicode_slug] super().__init__(*args, max_length=max_length, db_index=db_index, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 50: del kwargs["max_length"] if self.db_index is False: kwargs["db_index"] = False else: del kwargs["db_index"] if self.allow_unicode is not False: kwargs["allow_unicode"] = self.allow_unicode return name, path, args, kwargs def get_internal_type(self): return "SlugField" def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.SlugField, "allow_unicode": self.allow_unicode, **kwargs, } ) class TextField(Field): description = _("Text") def __init__(self, *args, db_collation=None, **kwargs): super().__init__(*args, **kwargs) self.db_collation = db_collation def check(self, **kwargs): databases = kwargs.get("databases") or [] return [ *super().check(**kwargs), *self._check_db_collation(databases), ] def _check_db_collation(self, databases): errors = [] for db in databases: if not router.allow_migrate_model(db, self.model): continue connection = connections[db] if not ( self.db_collation is None or "supports_collation_on_textfield" in self.model._meta.required_db_features or connection.features.supports_collation_on_textfield ): errors.append( checks.Error( "%s does not support a database collation on " "TextFields." % connection.display_name, obj=self, id="fields.E190", ), ) return errors def db_parameters(self, connection): db_params = super().db_parameters(connection) db_params["collation"] = self.db_collation return db_params def get_internal_type(self): return "TextField" def to_python(self, value): if isinstance(value, str) or value is None: return value return str(value) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): # Passing max_length to forms.CharField means that the value's length # will be validated twice. This is considered acceptable since we want # the value in the form field (to pass into widget for example). return super().formfield( **{ "max_length": self.max_length, **({} if self.choices is not None else {"widget": forms.Textarea}), **kwargs, } ) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.db_collation: kwargs["db_collation"] = self.db_collation return name, path, args, kwargs class TimeField(DateTimeCheckMixin, Field): empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid format. It must be in " "HH:MM[:ss[.uuuuuu]] format." ), "invalid_time": _( "“%(value)s” value has the correct format " "(HH:MM[:ss[.uuuuuu]]) but it is an invalid time." ), } description = _("Time") def __init__( self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs ): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs["editable"] = False kwargs["blank"] = True super().__init__(verbose_name, name, **kwargs) def _check_fix_default_value(self): """ Warn that using an actual date or datetime value is probably wrong; it's only evaluated on server startup. """ if not self.has_default(): return [] value = self.default if isinstance(value, datetime.datetime): now = None elif isinstance(value, datetime.time): now = _get_naive_now() # This will not use the right date in the race condition where now # is just before the date change and value is just past 0:00. value = datetime.datetime.combine(now.date(), value) else: # No explicit time / datetime value -- no checks necessary return [] # At this point, value is a datetime object. return self._check_if_value_fixed(value, now=now) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.auto_now is not False: kwargs["auto_now"] = self.auto_now if self.auto_now_add is not False: kwargs["auto_now_add"] = self.auto_now_add if self.auto_now or self.auto_now_add: del kwargs["blank"] del kwargs["editable"] return name, path, args, kwargs def get_internal_type(self): return "TimeField" def to_python(self, value): if value is None: return None if isinstance(value, datetime.time): return value if isinstance(value, datetime.datetime): # Not usually a good idea to pass in a datetime here (it loses # information), but this can be a side-effect of interacting with a # database backend (e.g. Oracle), so we'll be accommodating. return value.time() try: parsed = parse_time(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_time"], code="invalid_time", params={"value": value}, ) raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.datetime.now().time() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts times into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_timefield_value(value) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else val.isoformat() def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.TimeField, **kwargs, } ) class URLField(CharField): default_validators = [validators.URLValidator()] description = _("URL") def __init__(self, verbose_name=None, name=None, **kwargs): kwargs.setdefault("max_length", 200) super().__init__(verbose_name, name, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 200: del kwargs["max_length"] return name, path, args, kwargs def formfield(self, **kwargs): # As with CharField, this will cause URL validation to be performed # twice. return super().formfield( **{ "form_class": forms.URLField, **kwargs, } ) class BinaryField(Field): description = _("Raw binary data") empty_values = [None, b""] def __init__(self, *args, **kwargs): kwargs.setdefault("editable", False) super().__init__(*args, **kwargs) if self.max_length is not None: self.validators.append(validators.MaxLengthValidator(self.max_length)) def check(self, **kwargs): return [*super().check(**kwargs), *self._check_str_default_value()] def _check_str_default_value(self): if self.has_default() and isinstance(self.default, str): return [ checks.Error( "BinaryField's default cannot be a string. Use bytes " "content instead.", obj=self, id="fields.E170", ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.editable: kwargs["editable"] = True else: del kwargs["editable"] return name, path, args, kwargs def get_internal_type(self): return "BinaryField" def get_placeholder(self, value, compiler, connection): return connection.ops.binary_placeholder_sql(value) def get_default(self): if self.has_default() and not callable(self.default): return self.default default = super().get_default() if default == "": return b"" return default def get_db_prep_value(self, value, connection, prepared=False): value = super().get_db_prep_value(value, connection, prepared) if value is not None: return connection.Database.Binary(value) return value def value_to_string(self, obj): """Binary data is serialized as base64""" return b64encode(self.value_from_object(obj)).decode("ascii") def to_python(self, value): # If it's a string, it should be base64-encoded data if isinstance(value, str): return memoryview(b64decode(value.encode("ascii"))) return value class UUIDField(Field): default_error_messages = { "invalid": _("“%(value)s” is not a valid UUID."), } description = _("Universally unique identifier") empty_strings_allowed = False def __init__(self, verbose_name=None, **kwargs): kwargs["max_length"] = 32 super().__init__(verbose_name, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs def get_internal_type(self): return "UUIDField" def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): if value is None: return None if not isinstance(value, uuid.UUID): value = self.to_python(value) if connection.features.has_native_uuid_field: return value return value.hex def to_python(self, value): if value is not None and not isinstance(value, uuid.UUID): input_form = "int" if isinstance(value, int) else "hex" try: return uuid.UUID(**{input_form: value}) except (AttributeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) return value def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.UUIDField, **kwargs, } ) class AutoFieldMixin: db_returning = True def __init__(self, *args, **kwargs): kwargs["blank"] = True super().__init__(*args, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_primary_key(), ] def _check_primary_key(self): if not self.primary_key: return [ checks.Error( "AutoFields must set primary_key=True.", obj=self, id="fields.E100", ), ] else: return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["blank"] kwargs["primary_key"] = True return name, path, args, kwargs def validate(self, value, model_instance): pass def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) value = connection.ops.validate_autopk_value(value) return value def contribute_to_class(self, cls, name, **kwargs): if cls._meta.auto_field: raise ValueError( "Model %s can't have more than one auto-generated field." % cls._meta.label ) super().contribute_to_class(cls, name, **kwargs) cls._meta.auto_field = self def formfield(self, **kwargs): return None class AutoFieldMeta(type): """ Metaclass to maintain backward inheritance compatibility for AutoField. It is intended that AutoFieldMixin become public API when it is possible to create a non-integer automatically-generated field using column defaults stored in the database. In many areas Django also relies on using isinstance() to check for an automatically-generated field as a subclass of AutoField. A new flag needs to be implemented on Field to be used instead. When these issues have been addressed, this metaclass could be used to deprecate inheritance from AutoField and use of isinstance() with AutoField for detecting automatically-generated fields. """ @property def _subclasses(self): return (BigAutoField, SmallAutoField) def __instancecheck__(self, instance): return isinstance(instance, self._subclasses) or super().__instancecheck__( instance ) def __subclasscheck__(self, subclass): return issubclass(subclass, self._subclasses) or super().__subclasscheck__( subclass ) class AutoField(AutoFieldMixin, IntegerField, metaclass=AutoFieldMeta): def get_internal_type(self): return "AutoField" def rel_db_type(self, connection): return IntegerField().db_type(connection=connection) class BigAutoField(AutoFieldMixin, BigIntegerField): def get_internal_type(self): return "BigAutoField" def rel_db_type(self, connection): return BigIntegerField().db_type(connection=connection) class SmallAutoField(AutoFieldMixin, SmallIntegerField): def get_internal_type(self): return "SmallAutoField" def rel_db_type(self, connection): return SmallIntegerField().db_type(connection=connection)
4d5a28d3ec8109bd1748cd6e21cec52249e4b3671977c26b787ed264c4db3ecf
import functools import inspect from functools import partial from django import forms from django.apps import apps from django.conf import SettingsReference, settings from django.core import checks, exceptions from django.db import connection, router from django.db.backends import utils from django.db.models import Q from django.db.models.constants import LOOKUP_SEP from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL from django.db.models.query_utils import PathInfo from django.db.models.utils import make_model_tuple from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _ from . import Field from .mixins import FieldCacheMixin from .related_descriptors import ( ForeignKeyDeferredAttribute, ForwardManyToOneDescriptor, ForwardOneToOneDescriptor, ManyToManyDescriptor, ReverseManyToOneDescriptor, ReverseOneToOneDescriptor, ) from .related_lookups import ( RelatedExact, RelatedGreaterThan, RelatedGreaterThanOrEqual, RelatedIn, RelatedIsNull, RelatedLessThan, RelatedLessThanOrEqual, ) from .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel RECURSIVE_RELATIONSHIP_CONSTANT = "self" def resolve_relation(scope_model, relation): """ Transform relation into a model or fully-qualified model string of the form "app_label.ModelName", relative to scope_model. The relation argument can be: * RECURSIVE_RELATIONSHIP_CONSTANT, i.e. the string "self", in which case the model argument will be returned. * A bare model name without an app_label, in which case scope_model's app_label will be prepended. * An "app_label.ModelName" string. * A model class, which will be returned unchanged. """ # Check for recursive relations if relation == RECURSIVE_RELATIONSHIP_CONSTANT: relation = scope_model # Look for an "app.Model" relation if isinstance(relation, str): if "." not in relation: relation = "%s.%s" % (scope_model._meta.app_label, relation) return relation def lazy_related_operation(function, model, *related_models, **kwargs): """ Schedule `function` to be called once `model` and all `related_models` have been imported and registered with the app registry. `function` will be called with the newly-loaded model classes as its positional arguments, plus any optional keyword arguments. The `model` argument must be a model class. Each subsequent positional argument is another model, or a reference to another model - see `resolve_relation()` for the various forms these may take. Any relative references will be resolved relative to `model`. This is a convenience wrapper for `Apps.lazy_model_operation` - the app registry model used is the one found in `model._meta.apps`. """ models = [model] + [resolve_relation(model, rel) for rel in related_models] model_keys = (make_model_tuple(m) for m in models) apps = model._meta.apps return apps.lazy_model_operation(partial(function, **kwargs), *model_keys) class RelatedField(FieldCacheMixin, Field): """Base class that all relational fields inherit from.""" # Field flags one_to_many = False one_to_one = False many_to_many = False many_to_one = False def __init__( self, related_name=None, related_query_name=None, limit_choices_to=None, **kwargs, ): self._related_name = related_name self._related_query_name = related_query_name self._limit_choices_to = limit_choices_to super().__init__(**kwargs) @cached_property def related_model(self): # Can't cache this property until all the models are loaded. apps.check_models_ready() return self.remote_field.model def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_related_name_is_valid(), *self._check_related_query_name_is_valid(), *self._check_relation_model_exists(), *self._check_referencing_to_swapped_model(), *self._check_clashes(), ] def _check_related_name_is_valid(self): import keyword related_name = self.remote_field.related_name if related_name is None: return [] is_valid_id = ( not keyword.iskeyword(related_name) and related_name.isidentifier() ) if not (is_valid_id or related_name.endswith("+")): return [ checks.Error( "The name '%s' is invalid related_name for field %s.%s" % ( self.remote_field.related_name, self.model._meta.object_name, self.name, ), hint=( "Related name must be a valid Python identifier or end with a " "'+'" ), obj=self, id="fields.E306", ) ] return [] def _check_related_query_name_is_valid(self): if self.remote_field.is_hidden(): return [] rel_query_name = self.related_query_name() errors = [] if rel_query_name.endswith("_"): errors.append( checks.Error( "Reverse query name '%s' must not end with an underscore." % rel_query_name, hint=( "Add or change a related_name or related_query_name " "argument for this field." ), obj=self, id="fields.E308", ) ) if LOOKUP_SEP in rel_query_name: errors.append( checks.Error( "Reverse query name '%s' must not contain '%s'." % (rel_query_name, LOOKUP_SEP), hint=( "Add or change a related_name or related_query_name " "argument for this field." ), obj=self, id="fields.E309", ) ) return errors def _check_relation_model_exists(self): rel_is_missing = self.remote_field.model not in self.opts.apps.get_models() rel_is_string = isinstance(self.remote_field.model, str) model_name = ( self.remote_field.model if rel_is_string else self.remote_field.model._meta.object_name ) if rel_is_missing and ( rel_is_string or not self.remote_field.model._meta.swapped ): return [ checks.Error( "Field defines a relation with model '%s', which is either " "not installed, or is abstract." % model_name, obj=self, id="fields.E300", ) ] return [] def _check_referencing_to_swapped_model(self): if ( self.remote_field.model not in self.opts.apps.get_models() and not isinstance(self.remote_field.model, str) and self.remote_field.model._meta.swapped ): return [ checks.Error( "Field defines a relation with the model '%s', which has " "been swapped out." % self.remote_field.model._meta.label, hint="Update the relation to point at 'settings.%s'." % self.remote_field.model._meta.swappable, obj=self, id="fields.E301", ) ] return [] def _check_clashes(self): """Check accessor and reverse query name clashes.""" from django.db.models.base import ModelBase errors = [] opts = self.model._meta # f.remote_field.model may be a string instead of a model. Skip if # model name is not resolved. if not isinstance(self.remote_field.model, ModelBase): return [] # Consider that we are checking field `Model.foreign` and the models # are: # # class Target(models.Model): # model = models.IntegerField() # model_set = models.IntegerField() # # class Model(models.Model): # foreign = models.ForeignKey(Target) # m2m = models.ManyToManyField(Target) # rel_opts.object_name == "Target" rel_opts = self.remote_field.model._meta # If the field doesn't install a backward relation on the target model # (so `is_hidden` returns True), then there are no clashes to check # and we can skip these fields. rel_is_hidden = self.remote_field.is_hidden() rel_name = self.remote_field.get_accessor_name() # i. e. "model_set" rel_query_name = self.related_query_name() # i. e. "model" # i.e. "app_label.Model.field". field_name = "%s.%s" % (opts.label, self.name) # Check clashes between accessor or reverse query name of `field` # and any other field name -- i.e. accessor for Model.foreign is # model_set and it clashes with Target.model_set. potential_clashes = rel_opts.fields + rel_opts.many_to_many for clash_field in potential_clashes: # i.e. "app_label.Target.model_set". clash_name = "%s.%s" % (rel_opts.label, clash_field.name) if not rel_is_hidden and clash_field.name == rel_name: errors.append( checks.Error( f"Reverse accessor '{rel_opts.object_name}.{rel_name}' " f"for '{field_name}' clashes with field name " f"'{clash_name}'.", hint=( "Rename field '%s', or add/change a related_name " "argument to the definition for field '%s'." ) % (clash_name, field_name), obj=self, id="fields.E302", ) ) if clash_field.name == rel_query_name: errors.append( checks.Error( "Reverse query name for '%s' clashes with field name '%s'." % (field_name, clash_name), hint=( "Rename field '%s', or add/change a related_name " "argument to the definition for field '%s'." ) % (clash_name, field_name), obj=self, id="fields.E303", ) ) # Check clashes between accessors/reverse query names of `field` and # any other field accessor -- i. e. Model.foreign accessor clashes with # Model.m2m accessor. potential_clashes = (r for r in rel_opts.related_objects if r.field is not self) for clash_field in potential_clashes: # i.e. "app_label.Model.m2m". clash_name = "%s.%s" % ( clash_field.related_model._meta.label, clash_field.field.name, ) if not rel_is_hidden and clash_field.get_accessor_name() == rel_name: errors.append( checks.Error( f"Reverse accessor '{rel_opts.object_name}.{rel_name}' " f"for '{field_name}' clashes with reverse accessor for " f"'{clash_name}'.", hint=( "Add or change a related_name argument " "to the definition for '%s' or '%s'." ) % (field_name, clash_name), obj=self, id="fields.E304", ) ) if clash_field.get_accessor_name() == rel_query_name: errors.append( checks.Error( "Reverse query name for '%s' clashes with reverse query name " "for '%s'." % (field_name, clash_name), hint=( "Add or change a related_name argument " "to the definition for '%s' or '%s'." ) % (field_name, clash_name), obj=self, id="fields.E305", ) ) return errors def db_type(self, connection): # By default related field will not have a column as it relates to # columns from another table. return None def contribute_to_class(self, cls, name, private_only=False, **kwargs): super().contribute_to_class(cls, name, private_only=private_only, **kwargs) self.opts = cls._meta if not cls._meta.abstract: if self.remote_field.related_name: related_name = self.remote_field.related_name else: related_name = self.opts.default_related_name if related_name: related_name %= { "class": cls.__name__.lower(), "model_name": cls._meta.model_name.lower(), "app_label": cls._meta.app_label.lower(), } self.remote_field.related_name = related_name if self.remote_field.related_query_name: related_query_name = self.remote_field.related_query_name % { "class": cls.__name__.lower(), "app_label": cls._meta.app_label.lower(), } self.remote_field.related_query_name = related_query_name def resolve_related_class(model, related, field): field.remote_field.model = related field.do_related_class(related, model) lazy_related_operation( resolve_related_class, cls, self.remote_field.model, field=self ) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self._limit_choices_to: kwargs["limit_choices_to"] = self._limit_choices_to if self._related_name is not None: kwargs["related_name"] = self._related_name if self._related_query_name is not None: kwargs["related_query_name"] = self._related_query_name return name, path, args, kwargs def get_forward_related_filter(self, obj): """ Return the keyword arguments that when supplied to self.model.object.filter(), would select all instances related through this field to the remote obj. This is used to build the querysets returned by related descriptors. obj is an instance of self.related_field.model. """ return { "%s__%s" % (self.name, rh_field.name): getattr(obj, rh_field.attname) for _, rh_field in self.related_fields } def get_reverse_related_filter(self, obj): """ Complement to get_forward_related_filter(). Return the keyword arguments that when passed to self.related_field.model.object.filter() select all instances of self.related_field.model related through this field to obj. obj is an instance of self.model. """ base_q = Q.create( [ (rh_field.attname, getattr(obj, lh_field.attname)) for lh_field, rh_field in self.related_fields ] ) descriptor_filter = self.get_extra_descriptor_filter(obj) if isinstance(descriptor_filter, dict): return base_q & Q(**descriptor_filter) elif descriptor_filter: return base_q & descriptor_filter return base_q @property def swappable_setting(self): """ Get the setting that this is powered from for swapping, or None if it's not swapped in / marked with swappable=False. """ if self.swappable: # Work out string form of "to" if isinstance(self.remote_field.model, str): to_string = self.remote_field.model else: to_string = self.remote_field.model._meta.label return apps.get_swappable_settings_name(to_string) return None def set_attributes_from_rel(self): self.name = self.name or ( self.remote_field.model._meta.model_name + "_" + self.remote_field.model._meta.pk.name ) if self.verbose_name is None: self.verbose_name = self.remote_field.model._meta.verbose_name self.remote_field.set_field_name() def do_related_class(self, other, cls): self.set_attributes_from_rel() self.contribute_to_related_class(other, self.remote_field) def get_limit_choices_to(self): """ Return ``limit_choices_to`` for this model field. If it is a callable, it will be invoked and the result will be returned. """ if callable(self.remote_field.limit_choices_to): return self.remote_field.limit_choices_to() return self.remote_field.limit_choices_to def formfield(self, **kwargs): """ Pass ``limit_choices_to`` to the field being constructed. Only passes it if there is a type that supports related fields. This is a similar strategy used to pass the ``queryset`` to the field being constructed. """ defaults = {} if hasattr(self.remote_field, "get_related_field"): # If this is a callable, do not invoke it here. Just pass # it in the defaults for when the form class will later be # instantiated. limit_choices_to = self.remote_field.limit_choices_to defaults.update( { "limit_choices_to": limit_choices_to, } ) defaults.update(kwargs) return super().formfield(**defaults) def related_query_name(self): """ Define the name that can be used to identify this related object in a table-spanning query. """ return ( self.remote_field.related_query_name or self.remote_field.related_name or self.opts.model_name ) @property def target_field(self): """ When filtering against this relation, return the field on the remote model against which the filtering should happen. """ target_fields = self.path_infos[-1].target_fields if len(target_fields) > 1: raise exceptions.FieldError( "The relation has multiple target fields, but only single target field " "was asked for" ) return target_fields[0] def get_cache_name(self): return self.name class ForeignObject(RelatedField): """ Abstraction of the ForeignKey relation to support multi-column relations. """ # Field flags many_to_many = False many_to_one = True one_to_many = False one_to_one = False requires_unique_target = True related_accessor_class = ReverseManyToOneDescriptor forward_related_accessor_class = ForwardManyToOneDescriptor rel_class = ForeignObjectRel def __init__( self, to, on_delete, from_fields, to_fields, rel=None, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, swappable=True, **kwargs, ): if rel is None: rel = self.rel_class( self, to, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, parent_link=parent_link, on_delete=on_delete, ) super().__init__( rel=rel, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, **kwargs, ) self.from_fields = from_fields self.to_fields = to_fields self.swappable = swappable def __copy__(self): obj = super().__copy__() # Remove any cached PathInfo values. obj.__dict__.pop("path_infos", None) obj.__dict__.pop("reverse_path_infos", None) return obj def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_to_fields_exist(), *self._check_unique_target(), ] def _check_to_fields_exist(self): # Skip nonexistent models. if isinstance(self.remote_field.model, str): return [] errors = [] for to_field in self.to_fields: if to_field: try: self.remote_field.model._meta.get_field(to_field) except exceptions.FieldDoesNotExist: errors.append( checks.Error( "The to_field '%s' doesn't exist on the related " "model '%s'." % (to_field, self.remote_field.model._meta.label), obj=self, id="fields.E312", ) ) return errors def _check_unique_target(self): rel_is_string = isinstance(self.remote_field.model, str) if rel_is_string or not self.requires_unique_target: return [] try: self.foreign_related_fields except exceptions.FieldDoesNotExist: return [] if not self.foreign_related_fields: return [] unique_foreign_fields = { frozenset([f.name]) for f in self.remote_field.model._meta.get_fields() if getattr(f, "unique", False) } unique_foreign_fields.update( {frozenset(ut) for ut in self.remote_field.model._meta.unique_together} ) unique_foreign_fields.update( { frozenset(uc.fields) for uc in self.remote_field.model._meta.total_unique_constraints } ) foreign_fields = {f.name for f in self.foreign_related_fields} has_unique_constraint = any(u <= foreign_fields for u in unique_foreign_fields) if not has_unique_constraint and len(self.foreign_related_fields) > 1: field_combination = ", ".join( "'%s'" % rel_field.name for rel_field in self.foreign_related_fields ) model_name = self.remote_field.model.__name__ return [ checks.Error( "No subset of the fields %s on model '%s' is unique." % (field_combination, model_name), hint=( "Mark a single field as unique=True or add a set of " "fields to a unique constraint (via unique_together " "or a UniqueConstraint (without condition) in the " "model Meta.constraints)." ), obj=self, id="fields.E310", ) ] elif not has_unique_constraint: field_name = self.foreign_related_fields[0].name model_name = self.remote_field.model.__name__ return [ checks.Error( "'%s.%s' must be unique because it is referenced by " "a foreign key." % (model_name, field_name), hint=( "Add unique=True to this field or add a " "UniqueConstraint (without condition) in the model " "Meta.constraints." ), obj=self, id="fields.E311", ) ] else: return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() kwargs["on_delete"] = self.remote_field.on_delete kwargs["from_fields"] = self.from_fields kwargs["to_fields"] = self.to_fields if self.remote_field.parent_link: kwargs["parent_link"] = self.remote_field.parent_link if isinstance(self.remote_field.model, str): if "." in self.remote_field.model: app_label, model_name = self.remote_field.model.split(".") kwargs["to"] = "%s.%s" % (app_label, model_name.lower()) else: kwargs["to"] = self.remote_field.model.lower() else: kwargs["to"] = self.remote_field.model._meta.label_lower # If swappable is True, then see if we're actually pointing to the target # of a swap. swappable_setting = self.swappable_setting if swappable_setting is not None: # If it's already a settings reference, error if hasattr(kwargs["to"], "setting_name"): if kwargs["to"].setting_name != swappable_setting: raise ValueError( "Cannot deconstruct a ForeignKey pointing to a model " "that is swapped in place of more than one model (%s and %s)" % (kwargs["to"].setting_name, swappable_setting) ) # Set it kwargs["to"] = SettingsReference( kwargs["to"], swappable_setting, ) return name, path, args, kwargs def resolve_related_fields(self): if not self.from_fields or len(self.from_fields) != len(self.to_fields): raise ValueError( "Foreign Object from and to fields must be the same non-zero length" ) if isinstance(self.remote_field.model, str): raise ValueError( "Related model %r cannot be resolved" % self.remote_field.model ) related_fields = [] for index in range(len(self.from_fields)): from_field_name = self.from_fields[index] to_field_name = self.to_fields[index] from_field = ( self if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT else self.opts.get_field(from_field_name) ) to_field = ( self.remote_field.model._meta.pk if to_field_name is None else self.remote_field.model._meta.get_field(to_field_name) ) related_fields.append((from_field, to_field)) return related_fields @cached_property def related_fields(self): return self.resolve_related_fields() @cached_property def reverse_related_fields(self): return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields] @cached_property def local_related_fields(self): return tuple(lhs_field for lhs_field, rhs_field in self.related_fields) @cached_property def foreign_related_fields(self): return tuple( rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field ) def get_local_related_value(self, instance): return self.get_instance_value_for_fields(instance, self.local_related_fields) def get_foreign_related_value(self, instance): return self.get_instance_value_for_fields(instance, self.foreign_related_fields) @staticmethod def get_instance_value_for_fields(instance, fields): ret = [] opts = instance._meta for field in fields: # Gotcha: in some cases (like fixture loading) a model can have # different values in parent_ptr_id and parent's id. So, use # instance.pk (that is, parent_ptr_id) when asked for instance.id. if field.primary_key: possible_parent_link = opts.get_ancestor_link(field.model) if ( not possible_parent_link or possible_parent_link.primary_key or possible_parent_link.model._meta.abstract ): ret.append(instance.pk) continue ret.append(getattr(instance, field.attname)) return tuple(ret) def get_attname_column(self): attname, column = super().get_attname_column() return attname, None def get_joining_columns(self, reverse_join=False): source = self.reverse_related_fields if reverse_join else self.related_fields return tuple( (lhs_field.column, rhs_field.column) for lhs_field, rhs_field in source ) def get_reverse_joining_columns(self): return self.get_joining_columns(reverse_join=True) def get_extra_descriptor_filter(self, instance): """ Return an extra filter condition for related object fetching when user does 'instance.fieldname', that is the extra filter is used in the descriptor of the field. The filter should be either a dict usable in .filter(**kwargs) call or a Q-object. The condition will be ANDed together with the relation's joining columns. A parallel method is get_extra_restriction() which is used in JOIN and subquery conditions. """ return {} def get_extra_restriction(self, alias, related_alias): """ Return a pair condition used for joining and subquery pushdown. The condition is something that responds to as_sql(compiler, connection) method. Note that currently referring both the 'alias' and 'related_alias' will not work in some conditions, like subquery pushdown. A parallel method is get_extra_descriptor_filter() which is used in instance.fieldname related object fetching. """ return None def get_path_info(self, filtered_relation=None): """Get path from this field to the related model.""" opts = self.remote_field.model._meta from_opts = self.model._meta return [ PathInfo( from_opts=from_opts, to_opts=opts, target_fields=self.foreign_related_fields, join_field=self, m2m=False, direct=True, filtered_relation=filtered_relation, ) ] @cached_property def path_infos(self): return self.get_path_info() def get_reverse_path_info(self, filtered_relation=None): """Get path from the related model to this field's model.""" opts = self.model._meta from_opts = self.remote_field.model._meta return [ PathInfo( from_opts=from_opts, to_opts=opts, target_fields=(opts.pk,), join_field=self.remote_field, m2m=not self.unique, direct=False, filtered_relation=filtered_relation, ) ] @cached_property def reverse_path_infos(self): return self.get_reverse_path_info() @classmethod @functools.cache def get_class_lookups(cls): bases = inspect.getmro(cls) bases = bases[: bases.index(ForeignObject) + 1] class_lookups = [parent.__dict__.get("class_lookups", {}) for parent in bases] return cls.merge_dicts(class_lookups) def contribute_to_class(self, cls, name, private_only=False, **kwargs): super().contribute_to_class(cls, name, private_only=private_only, **kwargs) setattr(cls, self.name, self.forward_related_accessor_class(self)) def contribute_to_related_class(self, cls, related): # Internal FK's - i.e., those with a related name ending with '+' - # and swapped models don't get a related descriptor. if ( not self.remote_field.is_hidden() and not related.related_model._meta.swapped ): setattr( cls._meta.concrete_model, related.get_accessor_name(), self.related_accessor_class(related), ) # While 'limit_choices_to' might be a callable, simply pass # it along for later - this is too early because it's still # model load time. if self.remote_field.limit_choices_to: cls._meta.related_fkey_lookups.append( self.remote_field.limit_choices_to ) ForeignObject.register_lookup(RelatedIn) ForeignObject.register_lookup(RelatedExact) ForeignObject.register_lookup(RelatedLessThan) ForeignObject.register_lookup(RelatedGreaterThan) ForeignObject.register_lookup(RelatedGreaterThanOrEqual) ForeignObject.register_lookup(RelatedLessThanOrEqual) ForeignObject.register_lookup(RelatedIsNull) class ForeignKey(ForeignObject): """ Provide a many-to-one relation by adding a column to the local model to hold the remote value. By default ForeignKey will target the pk of the remote model but this behavior can be changed by using the ``to_field`` argument. """ descriptor_class = ForeignKeyDeferredAttribute # Field flags many_to_many = False many_to_one = True one_to_many = False one_to_one = False rel_class = ManyToOneRel empty_strings_allowed = False default_error_messages = { "invalid": _("%(model)s instance with %(field)s %(value)r does not exist.") } description = _("Foreign Key (type determined by related field)") def __init__( self, to, on_delete, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, to_field=None, db_constraint=True, **kwargs, ): try: to._meta.model_name except AttributeError: if not isinstance(to, str): raise TypeError( "%s(%r) is invalid. First parameter to ForeignKey must be " "either a model, a model name, or the string %r" % ( self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT, ) ) else: # For backwards compatibility purposes, we need to *try* and set # the to_field during FK construction. It won't be guaranteed to # be correct until contribute_to_class is called. Refs #12190. to_field = to_field or (to._meta.pk and to._meta.pk.name) if not callable(on_delete): raise TypeError("on_delete must be callable.") kwargs["rel"] = self.rel_class( self, to, to_field, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, parent_link=parent_link, on_delete=on_delete, ) kwargs.setdefault("db_index", True) super().__init__( to, on_delete, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, from_fields=[RECURSIVE_RELATIONSHIP_CONSTANT], to_fields=[to_field], **kwargs, ) self.db_constraint = db_constraint def __class_getitem__(cls, *args, **kwargs): return cls def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_on_delete(), *self._check_unique(), ] def _check_on_delete(self): on_delete = getattr(self.remote_field, "on_delete", None) if on_delete == SET_NULL and not self.null: return [ checks.Error( "Field specifies on_delete=SET_NULL, but cannot be null.", hint=( "Set null=True argument on the field, or change the on_delete " "rule." ), obj=self, id="fields.E320", ) ] elif on_delete == SET_DEFAULT and not self.has_default(): return [ checks.Error( "Field specifies on_delete=SET_DEFAULT, but has no default value.", hint="Set a default value, or change the on_delete rule.", obj=self, id="fields.E321", ) ] else: return [] def _check_unique(self, **kwargs): return ( [ checks.Warning( "Setting unique=True on a ForeignKey has the same effect as using " "a OneToOneField.", hint=( "ForeignKey(unique=True) is usually better served by a " "OneToOneField." ), obj=self, id="fields.W342", ) ] if self.unique else [] ) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["to_fields"] del kwargs["from_fields"] # Handle the simpler arguments if self.db_index: del kwargs["db_index"] else: kwargs["db_index"] = False if self.db_constraint is not True: kwargs["db_constraint"] = self.db_constraint # Rel needs more work. to_meta = getattr(self.remote_field.model, "_meta", None) if self.remote_field.field_name and ( not to_meta or (to_meta.pk and self.remote_field.field_name != to_meta.pk.name) ): kwargs["to_field"] = self.remote_field.field_name return name, path, args, kwargs def to_python(self, value): return self.target_field.to_python(value) @property def target_field(self): return self.foreign_related_fields[0] def validate(self, value, model_instance): if self.remote_field.parent_link: return super().validate(value, model_instance) if value is None: return using = router.db_for_read(self.remote_field.model, instance=model_instance) qs = self.remote_field.model._base_manager.using(using).filter( **{self.remote_field.field_name: value} ) qs = qs.complex_filter(self.get_limit_choices_to()) if not qs.exists(): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={ "model": self.remote_field.model._meta.verbose_name, "pk": value, "field": self.remote_field.field_name, "value": value, }, # 'pk' is included for backwards compatibility ) def resolve_related_fields(self): related_fields = super().resolve_related_fields() for from_field, to_field in related_fields: if ( to_field and to_field.model != self.remote_field.model._meta.concrete_model ): raise exceptions.FieldError( "'%s.%s' refers to field '%s' which is not local to model " "'%s'." % ( self.model._meta.label, self.name, to_field.name, self.remote_field.model._meta.concrete_model._meta.label, ) ) return related_fields def get_attname(self): return "%s_id" % self.name def get_attname_column(self): attname = self.get_attname() column = self.db_column or attname return attname, column def get_default(self): """Return the to_field if the default value is an object.""" field_default = super().get_default() if isinstance(field_default, self.remote_field.model): return getattr(field_default, self.target_field.attname) return field_default def get_db_prep_save(self, value, connection): if value is None or ( value == "" and ( not self.target_field.empty_strings_allowed or connection.features.interprets_empty_strings_as_nulls ) ): return None else: return self.target_field.get_db_prep_save(value, connection=connection) def get_db_prep_value(self, value, connection, prepared=False): return self.target_field.get_db_prep_value(value, connection, prepared) def get_prep_value(self, value): return self.target_field.get_prep_value(value) def contribute_to_related_class(self, cls, related): super().contribute_to_related_class(cls, related) if self.remote_field.field_name is None: self.remote_field.field_name = cls._meta.pk.name def formfield(self, *, using=None, **kwargs): if isinstance(self.remote_field.model, str): raise ValueError( "Cannot create form field for %r yet, because " "its related model %r has not been loaded yet" % (self.name, self.remote_field.model) ) return super().formfield( **{ "form_class": forms.ModelChoiceField, "queryset": self.remote_field.model._default_manager.using(using), "to_field_name": self.remote_field.field_name, **kwargs, "blank": self.blank, } ) def db_check(self, connection): return None def db_type(self, connection): return self.target_field.rel_db_type(connection=connection) def cast_db_type(self, connection): return self.target_field.cast_db_type(connection=connection) def db_parameters(self, connection): target_db_parameters = self.target_field.db_parameters(connection) return { "type": self.db_type(connection), "check": self.db_check(connection), "collation": target_db_parameters.get("collation"), } def convert_empty_strings(self, value, expression, connection): if (not value) and isinstance(value, str): return None return value def get_db_converters(self, connection): converters = super().get_db_converters(connection) if connection.features.interprets_empty_strings_as_nulls: converters += [self.convert_empty_strings] return converters def get_col(self, alias, output_field=None): if output_field is None: output_field = self.target_field while isinstance(output_field, ForeignKey): output_field = output_field.target_field if output_field is self: raise ValueError("Cannot resolve output_field.") return super().get_col(alias, output_field) class OneToOneField(ForeignKey): """ A OneToOneField is essentially the same as a ForeignKey, with the exception that it always carries a "unique" constraint with it and the reverse relation always returns the object pointed to (since there will only ever be one), rather than returning a list. """ # Field flags many_to_many = False many_to_one = False one_to_many = False one_to_one = True related_accessor_class = ReverseOneToOneDescriptor forward_related_accessor_class = ForwardOneToOneDescriptor rel_class = OneToOneRel description = _("One-to-one relationship") def __init__(self, to, on_delete, to_field=None, **kwargs): kwargs["unique"] = True super().__init__(to, on_delete, to_field=to_field, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if "unique" in kwargs: del kwargs["unique"] return name, path, args, kwargs def formfield(self, **kwargs): if self.remote_field.parent_link: return None return super().formfield(**kwargs) def save_form_data(self, instance, data): if isinstance(data, self.remote_field.model): setattr(instance, self.name, data) else: setattr(instance, self.attname, data) # Remote field object must be cleared otherwise Model.save() # will reassign attname using the related object pk. if data is None: setattr(instance, self.name, data) def _check_unique(self, **kwargs): # Override ForeignKey since check isn't applicable here. return [] def create_many_to_many_intermediary_model(field, klass): from django.db import models def set_managed(model, related, through): through._meta.managed = model._meta.managed or related._meta.managed to_model = resolve_relation(klass, field.remote_field.model) name = "%s_%s" % (klass._meta.object_name, field.name) lazy_related_operation(set_managed, klass, to_model, name) to = make_model_tuple(to_model)[1] from_ = klass._meta.model_name if to == from_: to = "to_%s" % to from_ = "from_%s" % from_ meta = type( "Meta", (), { "db_table": field._get_m2m_db_table(klass._meta), "auto_created": klass, "app_label": klass._meta.app_label, "db_tablespace": klass._meta.db_tablespace, "unique_together": (from_, to), "verbose_name": _("%(from)s-%(to)s relationship") % {"from": from_, "to": to}, "verbose_name_plural": _("%(from)s-%(to)s relationships") % {"from": from_, "to": to}, "apps": field.model._meta.apps, }, ) # Construct and return the new class. return type( name, (models.Model,), { "Meta": meta, "__module__": klass.__module__, from_: models.ForeignKey( klass, related_name="%s+" % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ), to: models.ForeignKey( to_model, related_name="%s+" % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ), }, ) class ManyToManyField(RelatedField): """ Provide a many-to-many relation by using an intermediary model that holds two ForeignKey fields pointed at the two sides of the relation. Unless a ``through`` model was provided, ManyToManyField will use the create_many_to_many_intermediary_model factory to automatically generate the intermediary model. """ # Field flags many_to_many = True many_to_one = False one_to_many = False one_to_one = False rel_class = ManyToManyRel description = _("Many-to-many relationship") def __init__( self, to, related_name=None, related_query_name=None, limit_choices_to=None, symmetrical=None, through=None, through_fields=None, db_constraint=True, db_table=None, swappable=True, **kwargs, ): try: to._meta except AttributeError: if not isinstance(to, str): raise TypeError( "%s(%r) is invalid. First parameter to ManyToManyField " "must be either a model, a model name, or the string %r" % ( self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT, ) ) if symmetrical is None: symmetrical = to == RECURSIVE_RELATIONSHIP_CONSTANT if through is not None and db_table is not None: raise ValueError( "Cannot specify a db_table if an intermediary model is used." ) kwargs["rel"] = self.rel_class( self, to, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, symmetrical=symmetrical, through=through, through_fields=through_fields, db_constraint=db_constraint, ) self.has_null_arg = "null" in kwargs super().__init__( related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, **kwargs, ) self.db_table = db_table self.swappable = swappable def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_unique(**kwargs), *self._check_relationship_model(**kwargs), *self._check_ignored_options(**kwargs), *self._check_table_uniqueness(**kwargs), ] def _check_unique(self, **kwargs): if self.unique: return [ checks.Error( "ManyToManyFields cannot be unique.", obj=self, id="fields.E330", ) ] return [] def _check_ignored_options(self, **kwargs): warnings = [] if self.has_null_arg: warnings.append( checks.Warning( "null has no effect on ManyToManyField.", obj=self, id="fields.W340", ) ) if self._validators: warnings.append( checks.Warning( "ManyToManyField does not support validators.", obj=self, id="fields.W341", ) ) if self.remote_field.symmetrical and self._related_name: warnings.append( checks.Warning( "related_name has no effect on ManyToManyField " 'with a symmetrical relationship, e.g. to "self".', obj=self, id="fields.W345", ) ) if self.db_comment: warnings.append( checks.Warning( "db_comment has no effect on ManyToManyField.", obj=self, id="fields.W346", ) ) return warnings def _check_relationship_model(self, from_model=None, **kwargs): if hasattr(self.remote_field.through, "_meta"): qualified_model_name = "%s.%s" % ( self.remote_field.through._meta.app_label, self.remote_field.through.__name__, ) else: qualified_model_name = self.remote_field.through errors = [] if self.remote_field.through not in self.opts.apps.get_models( include_auto_created=True ): # The relationship model is not installed. errors.append( checks.Error( "Field specifies a many-to-many relation through model " "'%s', which has not been installed." % qualified_model_name, obj=self, id="fields.E331", ) ) else: assert from_model is not None, ( "ManyToManyField with intermediate " "tables cannot be checked if you don't pass the model " "where the field is attached to." ) # Set some useful local variables to_model = resolve_relation(from_model, self.remote_field.model) from_model_name = from_model._meta.object_name if isinstance(to_model, str): to_model_name = to_model else: to_model_name = to_model._meta.object_name relationship_model_name = self.remote_field.through._meta.object_name self_referential = from_model == to_model # Count foreign keys in intermediate model if self_referential: seen_self = sum( from_model == getattr(field.remote_field, "model", None) for field in self.remote_field.through._meta.fields ) if seen_self > 2 and not self.remote_field.through_fields: errors.append( checks.Error( "The model is used as an intermediate model by " "'%s', but it has more than two foreign keys " "to '%s', which is ambiguous. You must specify " "which two foreign keys Django should use via the " "through_fields keyword argument." % (self, from_model_name), hint=( "Use through_fields to specify which two foreign keys " "Django should use." ), obj=self.remote_field.through, id="fields.E333", ) ) else: # Count foreign keys in relationship model seen_from = sum( from_model == getattr(field.remote_field, "model", None) for field in self.remote_field.through._meta.fields ) seen_to = sum( to_model == getattr(field.remote_field, "model", None) for field in self.remote_field.through._meta.fields ) if seen_from > 1 and not self.remote_field.through_fields: errors.append( checks.Error( ( "The model is used as an intermediate model by " "'%s', but it has more than one foreign key " "from '%s', which is ambiguous. You must specify " "which foreign key Django should use via the " "through_fields keyword argument." ) % (self, from_model_name), hint=( "If you want to create a recursive relationship, " 'use ManyToManyField("%s", through="%s").' ) % ( RECURSIVE_RELATIONSHIP_CONSTANT, relationship_model_name, ), obj=self, id="fields.E334", ) ) if seen_to > 1 and not self.remote_field.through_fields: errors.append( checks.Error( "The model is used as an intermediate model by " "'%s', but it has more than one foreign key " "to '%s', which is ambiguous. You must specify " "which foreign key Django should use via the " "through_fields keyword argument." % (self, to_model_name), hint=( "If you want to create a recursive relationship, " 'use ManyToManyField("%s", through="%s").' ) % ( RECURSIVE_RELATIONSHIP_CONSTANT, relationship_model_name, ), obj=self, id="fields.E335", ) ) if seen_from == 0 or seen_to == 0: errors.append( checks.Error( "The model is used as an intermediate model by " "'%s', but it does not have a foreign key to '%s' or '%s'." % (self, from_model_name, to_model_name), obj=self.remote_field.through, id="fields.E336", ) ) # Validate `through_fields`. if self.remote_field.through_fields is not None: # Validate that we're given an iterable of at least two items # and that none of them is "falsy". if not ( len(self.remote_field.through_fields) >= 2 and self.remote_field.through_fields[0] and self.remote_field.through_fields[1] ): errors.append( checks.Error( "Field specifies 'through_fields' but does not provide " "the names of the two link fields that should be used " "for the relation through model '%s'." % qualified_model_name, hint=( "Make sure you specify 'through_fields' as " "through_fields=('field1', 'field2')" ), obj=self, id="fields.E337", ) ) # Validate the given through fields -- they should be actual # fields on the through model, and also be foreign keys to the # expected models. else: assert from_model is not None, ( "ManyToManyField with intermediate " "tables cannot be checked if you don't pass the model " "where the field is attached to." ) source, through, target = ( from_model, self.remote_field.through, self.remote_field.model, ) source_field_name, target_field_name = self.remote_field.through_fields[ :2 ] for field_name, related_model in ( (source_field_name, source), (target_field_name, target), ): possible_field_names = [] for f in through._meta.fields: if ( hasattr(f, "remote_field") and getattr(f.remote_field, "model", None) == related_model ): possible_field_names.append(f.name) if possible_field_names: hint = ( "Did you mean one of the following foreign keys to '%s': " "%s?" % ( related_model._meta.object_name, ", ".join(possible_field_names), ) ) else: hint = None try: field = through._meta.get_field(field_name) except exceptions.FieldDoesNotExist: errors.append( checks.Error( "The intermediary model '%s' has no field '%s'." % (qualified_model_name, field_name), hint=hint, obj=self, id="fields.E338", ) ) else: if not ( hasattr(field, "remote_field") and getattr(field.remote_field, "model", None) == related_model ): errors.append( checks.Error( "'%s.%s' is not a foreign key to '%s'." % ( through._meta.object_name, field_name, related_model._meta.object_name, ), hint=hint, obj=self, id="fields.E339", ) ) return errors def _check_table_uniqueness(self, **kwargs): if ( isinstance(self.remote_field.through, str) or not self.remote_field.through._meta.managed ): return [] registered_tables = { model._meta.db_table: model for model in self.opts.apps.get_models(include_auto_created=True) if model != self.remote_field.through and model._meta.managed } m2m_db_table = self.m2m_db_table() model = registered_tables.get(m2m_db_table) # The second condition allows multiple m2m relations on a model if # some point to a through model that proxies another through model. if ( model and model._meta.concrete_model != self.remote_field.through._meta.concrete_model ): if model._meta.auto_created: def _get_field_name(model): for field in model._meta.auto_created._meta.many_to_many: if field.remote_field.through is model: return field.name opts = model._meta.auto_created._meta clashing_obj = "%s.%s" % (opts.label, _get_field_name(model)) else: clashing_obj = model._meta.label if settings.DATABASE_ROUTERS: error_class, error_id = checks.Warning, "fields.W344" error_hint = ( "You have configured settings.DATABASE_ROUTERS. Verify " "that the table of %r is correctly routed to a separate " "database." % clashing_obj ) else: error_class, error_id = checks.Error, "fields.E340" error_hint = None return [ error_class( "The field's intermediary table '%s' clashes with the " "table name of '%s'." % (m2m_db_table, clashing_obj), obj=self, hint=error_hint, id=error_id, ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() # Handle the simpler arguments. if self.db_table is not None: kwargs["db_table"] = self.db_table if self.remote_field.db_constraint is not True: kwargs["db_constraint"] = self.remote_field.db_constraint # Lowercase model names as they should be treated as case-insensitive. if isinstance(self.remote_field.model, str): if "." in self.remote_field.model: app_label, model_name = self.remote_field.model.split(".") kwargs["to"] = "%s.%s" % (app_label, model_name.lower()) else: kwargs["to"] = self.remote_field.model.lower() else: kwargs["to"] = self.remote_field.model._meta.label_lower if getattr(self.remote_field, "through", None) is not None: if isinstance(self.remote_field.through, str): kwargs["through"] = self.remote_field.through elif not self.remote_field.through._meta.auto_created: kwargs["through"] = self.remote_field.through._meta.label # If swappable is True, then see if we're actually pointing to the target # of a swap. swappable_setting = self.swappable_setting if swappable_setting is not None: # If it's already a settings reference, error. if hasattr(kwargs["to"], "setting_name"): if kwargs["to"].setting_name != swappable_setting: raise ValueError( "Cannot deconstruct a ManyToManyField pointing to a " "model that is swapped in place of more than one model " "(%s and %s)" % (kwargs["to"].setting_name, swappable_setting) ) kwargs["to"] = SettingsReference( kwargs["to"], swappable_setting, ) return name, path, args, kwargs def _get_path_info(self, direct=False, filtered_relation=None): """Called by both direct and indirect m2m traversal.""" int_model = self.remote_field.through linkfield1 = int_model._meta.get_field(self.m2m_field_name()) linkfield2 = int_model._meta.get_field(self.m2m_reverse_field_name()) if direct: join1infos = linkfield1.reverse_path_infos if filtered_relation: join2infos = linkfield2.get_path_info(filtered_relation) else: join2infos = linkfield2.path_infos else: join1infos = linkfield2.reverse_path_infos if filtered_relation: join2infos = linkfield1.get_path_info(filtered_relation) else: join2infos = linkfield1.path_infos # Get join infos between the last model of join 1 and the first model # of join 2. Assume the only reason these may differ is due to model # inheritance. join1_final = join1infos[-1].to_opts join2_initial = join2infos[0].from_opts if join1_final is join2_initial: intermediate_infos = [] elif issubclass(join1_final.model, join2_initial.model): intermediate_infos = join1_final.get_path_to_parent(join2_initial.model) else: intermediate_infos = join2_initial.get_path_from_parent(join1_final.model) return [*join1infos, *intermediate_infos, *join2infos] def get_path_info(self, filtered_relation=None): return self._get_path_info(direct=True, filtered_relation=filtered_relation) @cached_property def path_infos(self): return self.get_path_info() def get_reverse_path_info(self, filtered_relation=None): return self._get_path_info(direct=False, filtered_relation=filtered_relation) @cached_property def reverse_path_infos(self): return self.get_reverse_path_info() def _get_m2m_db_table(self, opts): """ Function that can be curried to provide the m2m table name for this relation. """ if self.remote_field.through is not None: return self.remote_field.through._meta.db_table elif self.db_table: return self.db_table else: m2m_table_name = "%s_%s" % (utils.strip_quotes(opts.db_table), self.name) return utils.truncate_name(m2m_table_name, connection.ops.max_name_length()) def _get_m2m_attr(self, related, attr): """ Function that can be curried to provide the source accessor or DB column name for the m2m table. """ cache_attr = "_m2m_%s_cache" % attr if hasattr(self, cache_attr): return getattr(self, cache_attr) if self.remote_field.through_fields is not None: link_field_name = self.remote_field.through_fields[0] else: link_field_name = None for f in self.remote_field.through._meta.fields: if ( f.is_relation and f.remote_field.model == related.related_model and (link_field_name is None or link_field_name == f.name) ): setattr(self, cache_attr, getattr(f, attr)) return getattr(self, cache_attr) def _get_m2m_reverse_attr(self, related, attr): """ Function that can be curried to provide the related accessor or DB column name for the m2m table. """ cache_attr = "_m2m_reverse_%s_cache" % attr if hasattr(self, cache_attr): return getattr(self, cache_attr) found = False if self.remote_field.through_fields is not None: link_field_name = self.remote_field.through_fields[1] else: link_field_name = None for f in self.remote_field.through._meta.fields: if f.is_relation and f.remote_field.model == related.model: if link_field_name is None and related.related_model == related.model: # If this is an m2m-intermediate to self, # the first foreign key you find will be # the source column. Keep searching for # the second foreign key. if found: setattr(self, cache_attr, getattr(f, attr)) break else: found = True elif link_field_name is None or link_field_name == f.name: setattr(self, cache_attr, getattr(f, attr)) break return getattr(self, cache_attr) def contribute_to_class(self, cls, name, **kwargs): # To support multiple relations to self, it's useful to have a non-None # related name on symmetrical relations for internal reasons. The # concept doesn't make a lot of sense externally ("you want me to # specify *what* on my non-reversible relation?!"), so we set it up # automatically. The funky name reduces the chance of an accidental # clash. if self.remote_field.symmetrical and ( self.remote_field.model == RECURSIVE_RELATIONSHIP_CONSTANT or self.remote_field.model == cls._meta.object_name ): self.remote_field.related_name = "%s_rel_+" % name elif self.remote_field.is_hidden(): # If the backwards relation is disabled, replace the original # related_name with one generated from the m2m field name. Django # still uses backwards relations internally and we need to avoid # clashes between multiple m2m fields with related_name == '+'. self.remote_field.related_name = "_%s_%s_%s_+" % ( cls._meta.app_label, cls.__name__.lower(), name, ) super().contribute_to_class(cls, name, **kwargs) # The intermediate m2m model is not auto created if: # 1) There is a manually specified intermediate, or # 2) The class owning the m2m field is abstract. # 3) The class owning the m2m field has been swapped out. if not cls._meta.abstract: if self.remote_field.through: def resolve_through_model(_, model, field): field.remote_field.through = model lazy_related_operation( resolve_through_model, cls, self.remote_field.through, field=self ) elif not cls._meta.swapped: self.remote_field.through = create_many_to_many_intermediary_model( self, cls ) # Add the descriptor for the m2m relation. setattr(cls, self.name, ManyToManyDescriptor(self.remote_field, reverse=False)) # Set up the accessor for the m2m table name for the relation. self.m2m_db_table = partial(self._get_m2m_db_table, cls._meta) def contribute_to_related_class(self, cls, related): # Internal M2Ms (i.e., those with a related name ending with '+') # and swapped models don't get a related descriptor. if ( not self.remote_field.is_hidden() and not related.related_model._meta.swapped ): setattr( cls, related.get_accessor_name(), ManyToManyDescriptor(self.remote_field, reverse=True), ) # Set up the accessors for the column names on the m2m table. self.m2m_column_name = partial(self._get_m2m_attr, related, "column") self.m2m_reverse_name = partial(self._get_m2m_reverse_attr, related, "column") self.m2m_field_name = partial(self._get_m2m_attr, related, "name") self.m2m_reverse_field_name = partial( self._get_m2m_reverse_attr, related, "name" ) get_m2m_rel = partial(self._get_m2m_attr, related, "remote_field") self.m2m_target_field_name = lambda: get_m2m_rel().field_name get_m2m_reverse_rel = partial( self._get_m2m_reverse_attr, related, "remote_field" ) self.m2m_reverse_target_field_name = lambda: get_m2m_reverse_rel().field_name def set_attributes_from_rel(self): pass def value_from_object(self, obj): return [] if obj.pk is None else list(getattr(obj, self.attname).all()) def save_form_data(self, instance, data): getattr(instance, self.attname).set(data) def formfield(self, *, using=None, **kwargs): defaults = { "form_class": forms.ModelMultipleChoiceField, "queryset": self.remote_field.model._default_manager.using(using), **kwargs, } # If initial is passed in, it's a list of related objects, but the # MultipleChoiceField takes a list of IDs. if defaults.get("initial") is not None: initial = defaults["initial"] if callable(initial): initial = initial() defaults["initial"] = [i.pk for i in initial] return super().formfield(**defaults) def db_check(self, connection): return None def db_type(self, connection): # A ManyToManyField is not represented by a single column, # so return None. return None def db_parameters(self, connection): return {"type": None, "check": None}
af4f778c34908941e29965cc44e93a23edddc7fdf0a4e97a98bf84affe3b9f3a
""" Create SQL statements for QuerySets. The code in here encapsulates all of the SQL construction so that QuerySets themselves do not have to (and could be backed by things other than SQL databases). The abstraction barrier only works one way: this module has to know all about the internals of models in order to get the information it needs. """ import copy import difflib import functools import sys from collections import Counter, namedtuple from collections.abc import Iterator, Mapping from itertools import chain, count, product from string import ascii_uppercase from django.core.exceptions import FieldDoesNotExist, FieldError from django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections from django.db.models.aggregates import Count from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import ( BaseExpression, Col, Exists, F, OuterRef, Ref, ResolvedOuterRef, Value, ) from django.db.models.fields import Field from django.db.models.fields.related_lookups import MultiColSource from django.db.models.lookups import Lookup from django.db.models.query_utils import ( Q, check_rel_lookup_compatibility, refs_expression, ) from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE from django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin from django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode from django.utils.functional import cached_property from django.utils.regex_helper import _lazy_re_compile from django.utils.tree import Node __all__ = ["Query", "RawQuery"] # Quotation marks ('"`[]), whitespace characters, semicolons, or inline # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/") # Inspired from # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS EXPLAIN_OPTIONS_PATTERN = _lazy_re_compile(r"[\w\-]+") def get_field_names_from_opts(opts): if opts is None: return set() return set( chain.from_iterable( (f.name, f.attname) if f.concrete else (f.name,) for f in opts.get_fields() ) ) def get_children_from_q(q): for child in q.children: if isinstance(child, Node): yield from get_children_from_q(child) else: yield child JoinInfo = namedtuple( "JoinInfo", ("final_field", "targets", "opts", "joins", "path", "transform_function"), ) class RawQuery: """A single raw SQL query.""" def __init__(self, sql, using, params=()): self.params = params self.sql = sql self.using = using self.cursor = None # Mirror some properties of a normal query so that # the compiler can be used to process results. self.low_mark, self.high_mark = 0, None # Used for offset/limit self.extra_select = {} self.annotation_select = {} def chain(self, using): return self.clone(using) def clone(self, using): return RawQuery(self.sql, using, params=self.params) def get_columns(self): if self.cursor is None: self._execute_query() converter = connections[self.using].introspection.identifier_converter return [converter(column_meta[0]) for column_meta in self.cursor.description] def __iter__(self): # Always execute a new query for a new iterator. # This could be optimized with a cache at the expense of RAM. self._execute_query() if not connections[self.using].features.can_use_chunked_reads: # If the database can't use chunked reads we need to make sure we # evaluate the entire query up front. result = list(self.cursor) else: result = self.cursor return iter(result) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) @property def params_type(self): if self.params is None: return None return dict if isinstance(self.params, Mapping) else tuple def __str__(self): if self.params_type is None: return self.sql return self.sql % self.params_type(self.params) def _execute_query(self): connection = connections[self.using] # Adapt parameters to the database, as much as possible considering # that the target type isn't known. See #17755. params_type = self.params_type adapter = connection.ops.adapt_unknown_value if params_type is tuple: params = tuple(adapter(val) for val in self.params) elif params_type is dict: params = {key: adapter(val) for key, val in self.params.items()} elif params_type is None: params = None else: raise RuntimeError("Unexpected params type: %s" % params_type) self.cursor = connection.cursor() self.cursor.execute(self.sql, params) ExplainInfo = namedtuple("ExplainInfo", ("format", "options")) class Query(BaseExpression): """A single SQL query.""" alias_prefix = "T" empty_result_set_value = None subq_aliases = frozenset([alias_prefix]) compiler = "SQLCompiler" base_table_class = BaseTable join_class = Join default_cols = True default_ordering = True standard_ordering = True filter_is_sticky = False subquery = False # SQL-related attributes. # Select and related select clauses are expressions to use in the SELECT # clause of the query. The select is used for cases where we want to set up # the select clause to contain other than default fields (values(), # subqueries...). Note that annotations go to annotations dictionary. select = () # The group_by attribute can have one of the following forms: # - None: no group by at all in the query # - A tuple of expressions: group by (at least) those expressions. # String refs are also allowed for now. # - True: group by all select fields of the model # See compiler.get_group_by() for details. group_by = None order_by = () low_mark = 0 # Used for offset/limit. high_mark = None # Used for offset/limit. distinct = False distinct_fields = () select_for_update = False select_for_update_nowait = False select_for_update_skip_locked = False select_for_update_of = () select_for_no_key_update = False select_related = False has_select_fields = False # Arbitrary limit for select_related to prevents infinite recursion. max_depth = 5 # Holds the selects defined by a call to values() or values_list() # excluding annotation_select and extra_select. values_select = () # SQL annotation-related attributes. annotation_select_mask = None _annotation_select_cache = None # Set combination attributes. combinator = None combinator_all = False combined_queries = () # These are for extensions. The contents are more or less appended verbatim # to the appropriate clause. extra_select_mask = None _extra_select_cache = None extra_tables = () extra_order_by = () # A tuple that is a set of model field names and either True, if these are # the fields to defer, or False if these are the only fields to load. deferred_loading = (frozenset(), True) explain_info = None def __init__(self, model, alias_cols=True): self.model = model self.alias_refcount = {} # alias_map is the most important data structure regarding joins. # It's used for recording which joins exist in the query and what # types they are. The key is the alias of the joined table (possibly # the table name) and the value is a Join-like object (see # sql.datastructures.Join for more information). self.alias_map = {} # Whether to provide alias to columns during reference resolving. self.alias_cols = alias_cols # Sometimes the query contains references to aliases in outer queries (as # a result of split_exclude). Correct alias quoting needs to know these # aliases too. # Map external tables to whether they are aliased. self.external_aliases = {} self.table_map = {} # Maps table names to list of aliases. self.used_aliases = set() self.where = WhereNode() # Maps alias -> Annotation Expression. self.annotations = {} # These are for extensions. The contents are more or less appended # verbatim to the appropriate clause. self.extra = {} # Maps col_alias -> (col_sql, params). self._filtered_relations = {} @property def output_field(self): if len(self.select) == 1: select = self.select[0] return getattr(select, "target", None) or select.field elif len(self.annotation_select) == 1: return next(iter(self.annotation_select.values())).output_field @cached_property def base_table(self): for alias in self.alias_map: return alias def __str__(self): """ Return the query as a string of SQL with the parameter values substituted in (use sql_with_params() to see the unsubstituted string). Parameter values won't necessarily be quoted correctly, since that is done by the database interface at execution time. """ sql, params = self.sql_with_params() return sql % params def sql_with_params(self): """ Return the query as an SQL string and the parameters that will be substituted into the query. """ return self.get_compiler(DEFAULT_DB_ALIAS).as_sql() def __deepcopy__(self, memo): """Limit the amount of work when a Query is deepcopied.""" result = self.clone() memo[id(self)] = result return result def get_compiler(self, using=None, connection=None, elide_empty=True): if using is None and connection is None: raise ValueError("Need either using or connection") if using: connection = connections[using] return connection.ops.compiler(self.compiler)( self, connection, using, elide_empty ) def get_meta(self): """ Return the Options instance (the model._meta) from which to start processing. Normally, this is self.model._meta, but it can be changed by subclasses. """ if self.model: return self.model._meta def clone(self): """ Return a copy of the current Query. A lightweight alternative to deepcopy(). """ obj = Empty() obj.__class__ = self.__class__ # Copy references to everything. obj.__dict__ = self.__dict__.copy() # Clone attributes that can't use shallow copy. obj.alias_refcount = self.alias_refcount.copy() obj.alias_map = self.alias_map.copy() obj.external_aliases = self.external_aliases.copy() obj.table_map = self.table_map.copy() obj.where = self.where.clone() obj.annotations = self.annotations.copy() if self.annotation_select_mask is not None: obj.annotation_select_mask = self.annotation_select_mask.copy() if self.combined_queries: obj.combined_queries = tuple( [query.clone() for query in self.combined_queries] ) # _annotation_select_cache cannot be copied, as doing so breaks the # (necessary) state in which both annotations and # _annotation_select_cache point to the same underlying objects. # It will get re-populated in the cloned queryset the next time it's # used. obj._annotation_select_cache = None obj.extra = self.extra.copy() if self.extra_select_mask is not None: obj.extra_select_mask = self.extra_select_mask.copy() if self._extra_select_cache is not None: obj._extra_select_cache = self._extra_select_cache.copy() if self.select_related is not False: # Use deepcopy because select_related stores fields in nested # dicts. obj.select_related = copy.deepcopy(obj.select_related) if "subq_aliases" in self.__dict__: obj.subq_aliases = self.subq_aliases.copy() obj.used_aliases = self.used_aliases.copy() obj._filtered_relations = self._filtered_relations.copy() # Clear the cached_property, if it exists. obj.__dict__.pop("base_table", None) return obj def chain(self, klass=None): """ Return a copy of the current Query that's ready for another operation. The klass argument changes the type of the Query, e.g. UpdateQuery. """ obj = self.clone() if klass and obj.__class__ != klass: obj.__class__ = klass if not obj.filter_is_sticky: obj.used_aliases = set() obj.filter_is_sticky = False if hasattr(obj, "_setup_query"): obj._setup_query() return obj def relabeled_clone(self, change_map): clone = self.clone() clone.change_aliases(change_map) return clone def _get_col(self, target, field, alias): if not self.alias_cols: alias = None return target.get_col(alias, field) def get_aggregation(self, using, aggregate_exprs): """ Return the dictionary with the values of the existing aggregations. """ if not aggregate_exprs: return {} aggregates = {} for alias, aggregate_expr in aggregate_exprs.items(): self.check_alias(alias) aggregate = aggregate_expr.resolve_expression( self, allow_joins=True, reuse=None, summarize=True ) if not aggregate.contains_aggregate: raise TypeError("%s is not an aggregate expression" % alias) aggregates[alias] = aggregate # Existing usage of aggregation can be determined by the presence of # selected aggregates but also by filters against aliased aggregates. _, having, qualify = self.where.split_having_qualify() has_existing_aggregation = ( any( getattr(annotation, "contains_aggregate", True) for annotation in self.annotations.values() ) or having ) # Decide if we need to use a subquery. # # Existing aggregations would cause incorrect results as # get_aggregation() must produce just one result and thus must not use # GROUP BY. # # If the query has limit or distinct, or uses set operations, then # those operations must be done in a subquery so that the query # aggregates on the limit and/or distinct results instead of applying # the distinct and limit after the aggregation. if ( isinstance(self.group_by, tuple) or self.is_sliced or has_existing_aggregation or qualify or self.distinct or self.combinator ): from django.db.models.sql.subqueries import AggregateQuery inner_query = self.clone() inner_query.subquery = True outer_query = AggregateQuery(self.model, inner_query) inner_query.select_for_update = False inner_query.select_related = False inner_query.set_annotation_mask(self.annotation_select) # Queries with distinct_fields need ordering and when a limit is # applied we must take the slice from the ordered query. Otherwise # no need for ordering. inner_query.clear_ordering(force=False) if not inner_query.distinct: # If the inner query uses default select and it has some # aggregate annotations, then we must make sure the inner # query is grouped by the main model's primary key. However, # clearing the select clause can alter results if distinct is # used. if inner_query.default_cols and has_existing_aggregation: inner_query.group_by = ( self.model._meta.pk.get_col(inner_query.get_initial_alias()), ) inner_query.default_cols = False if not qualify: # Mask existing annotations that are not referenced by # aggregates to be pushed to the outer query unless # filtering against window functions is involved as it # requires complex realising. annotation_mask = set() for aggregate in aggregates.values(): annotation_mask |= aggregate.get_refs() inner_query.set_annotation_mask(annotation_mask) # Add aggregates to the outer AggregateQuery. This requires making # sure all columns referenced by the aggregates are selected in the # inner query. It is achieved by retrieving all column references # by the aggregates, explicitly selecting them in the inner query, # and making sure the aggregates are repointed to them. col_refs = {} for alias, aggregate in aggregates.items(): replacements = {} for col in self._gen_cols([aggregate], resolve_refs=False): if not (col_ref := col_refs.get(col)): index = len(col_refs) + 1 col_alias = f"__col{index}" col_ref = Ref(col_alias, col) col_refs[col] = col_ref inner_query.annotations[col_alias] = col inner_query.append_annotation_mask([col_alias]) replacements[col] = col_ref outer_query.annotations[alias] = aggregate.replace_expressions( replacements ) if ( inner_query.select == () and not inner_query.default_cols and not inner_query.annotation_select_mask ): # In case of Model.objects[0:3].count(), there would be no # field selected in the inner query, yet we must use a subquery. # So, make sure at least one field is selected. inner_query.select = ( self.model._meta.pk.get_col(inner_query.get_initial_alias()), ) else: outer_query = self self.select = () self.default_cols = False self.extra = {} if self.annotations: # Inline reference to existing annotations and mask them as # they are unnecessary given only the summarized aggregations # are requested. replacements = { Ref(alias, annotation): annotation for alias, annotation in self.annotations.items() } self.annotations = { alias: aggregate.replace_expressions(replacements) for alias, aggregate in aggregates.items() } else: self.annotations = aggregates self.set_annotation_mask(aggregates) empty_set_result = [ expression.empty_result_set_value for expression in outer_query.annotation_select.values() ] elide_empty = not any(result is NotImplemented for result in empty_set_result) outer_query.clear_ordering(force=True) outer_query.clear_limits() outer_query.select_for_update = False outer_query.select_related = False compiler = outer_query.get_compiler(using, elide_empty=elide_empty) result = compiler.execute_sql(SINGLE) if result is None: result = empty_set_result else: converters = compiler.get_converters(outer_query.annotation_select.values()) result = next(compiler.apply_converters((result,), converters)) return dict(zip(outer_query.annotation_select, result)) def get_count(self, using): """ Perform a COUNT() query using the current filter constraints. """ obj = self.clone() return obj.get_aggregation(using, {"__count": Count("*")})["__count"] def has_filters(self): return self.where def exists(self, limit=True): q = self.clone() if not (q.distinct and q.is_sliced): if q.group_by is True: q.add_fields( (f.attname for f in self.model._meta.concrete_fields), False ) # Disable GROUP BY aliases to avoid orphaning references to the # SELECT clause which is about to be cleared. q.set_group_by(allow_aliases=False) q.clear_select_clause() if q.combined_queries and q.combinator == "union": q.combined_queries = tuple( combined_query.exists(limit=False) for combined_query in q.combined_queries ) q.clear_ordering(force=True) if limit: q.set_limits(high=1) q.add_annotation(Value(1), "a") return q def has_results(self, using): q = self.exists(using) compiler = q.get_compiler(using=using) return compiler.has_results() def explain(self, using, format=None, **options): q = self.clone() for option_name in options: if ( not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name) or "--" in option_name ): raise ValueError(f"Invalid option name: {option_name!r}.") q.explain_info = ExplainInfo(format, options) compiler = q.get_compiler(using=using) return "\n".join(compiler.explain_query()) def combine(self, rhs, connector): """ Merge the 'rhs' query into the current one (with any 'rhs' effects being applied *after* (that is, "to the right of") anything in the current query. 'rhs' is not modified during a call to this function. The 'connector' parameter describes how to connect filters from the 'rhs' query. """ if self.model != rhs.model: raise TypeError("Cannot combine queries on two different base models.") if self.is_sliced: raise TypeError("Cannot combine queries once a slice has been taken.") if self.distinct != rhs.distinct: raise TypeError("Cannot combine a unique query with a non-unique query.") if self.distinct_fields != rhs.distinct_fields: raise TypeError("Cannot combine queries with different distinct fields.") # If lhs and rhs shares the same alias prefix, it is possible to have # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up # as T4 -> T6 while combining two querysets. To prevent this, change an # alias prefix of the rhs and update current aliases accordingly, # except if the alias is the base table since it must be present in the # query on both sides. initial_alias = self.get_initial_alias() rhs.bump_prefix(self, exclude={initial_alias}) # Work out how to relabel the rhs aliases, if necessary. change_map = {} conjunction = connector == AND # Determine which existing joins can be reused. When combining the # query with AND we must recreate all joins for m2m filters. When # combining with OR we can reuse joins. The reason is that in AND # case a single row can't fulfill a condition like: # revrel__col=1 & revrel__col=2 # But, there might be two different related rows matching this # condition. In OR case a single True is enough, so single row is # enough, too. # # Note that we will be creating duplicate joins for non-m2m joins in # the AND case. The results will be correct but this creates too many # joins. This is something that could be fixed later on. reuse = set() if conjunction else set(self.alias_map) joinpromoter = JoinPromoter(connector, 2, False) joinpromoter.add_votes( j for j in self.alias_map if self.alias_map[j].join_type == INNER ) rhs_votes = set() # Now, add the joins from rhs query into the new query (skipping base # table). rhs_tables = list(rhs.alias_map)[1:] for alias in rhs_tables: join = rhs.alias_map[alias] # If the left side of the join was already relabeled, use the # updated alias. join = join.relabeled_clone(change_map) new_alias = self.join(join, reuse=reuse) if join.join_type == INNER: rhs_votes.add(new_alias) # We can't reuse the same join again in the query. If we have two # distinct joins for the same connection in rhs query, then the # combined query must have two joins, too. reuse.discard(new_alias) if alias != new_alias: change_map[alias] = new_alias if not rhs.alias_refcount[alias]: # The alias was unused in the rhs query. Unref it so that it # will be unused in the new query, too. We have to add and # unref the alias so that join promotion has information of # the join type for the unused alias. self.unref_alias(new_alias) joinpromoter.add_votes(rhs_votes) joinpromoter.update_join_types(self) # Combine subqueries aliases to ensure aliases relabelling properly # handle subqueries when combining where and select clauses. self.subq_aliases |= rhs.subq_aliases # Now relabel a copy of the rhs where-clause and add it to the current # one. w = rhs.where.clone() w.relabel_aliases(change_map) self.where.add(w, connector) # Selection columns and extra extensions are those provided by 'rhs'. if rhs.select: self.set_select([col.relabeled_clone(change_map) for col in rhs.select]) else: self.select = () if connector == OR: # It would be nice to be able to handle this, but the queries don't # really make sense (or return consistent value sets). Not worth # the extra complexity when you can write a real query instead. if self.extra and rhs.extra: raise ValueError( "When merging querysets using 'or', you cannot have " "extra(select=...) on both sides." ) self.extra.update(rhs.extra) extra_select_mask = set() if self.extra_select_mask is not None: extra_select_mask.update(self.extra_select_mask) if rhs.extra_select_mask is not None: extra_select_mask.update(rhs.extra_select_mask) if extra_select_mask: self.set_extra_mask(extra_select_mask) self.extra_tables += rhs.extra_tables # Ordering uses the 'rhs' ordering, unless it has none, in which case # the current ordering is used. self.order_by = rhs.order_by or self.order_by self.extra_order_by = rhs.extra_order_by or self.extra_order_by def _get_defer_select_mask(self, opts, mask, select_mask=None): if select_mask is None: select_mask = {} select_mask[opts.pk] = {} # All concrete fields that are not part of the defer mask must be # loaded. If a relational field is encountered it gets added to the # mask for it be considered if `select_related` and the cycle continues # by recursively calling this function. for field in opts.concrete_fields: field_mask = mask.pop(field.name, None) if field_mask is None: select_mask.setdefault(field, {}) elif field_mask: if not field.is_relation: raise FieldError(next(iter(field_mask))) field_select_mask = select_mask.setdefault(field, {}) related_model = field.remote_field.model._meta.concrete_model self._get_defer_select_mask( related_model._meta, field_mask, field_select_mask ) # Remaining defer entries must be references to reverse relationships. # The following code is expected to raise FieldError if it encounters # a malformed defer entry. for field_name, field_mask in mask.items(): if filtered_relation := self._filtered_relations.get(field_name): relation = opts.get_field(filtered_relation.relation_name) field_select_mask = select_mask.setdefault((field_name, relation), {}) field = relation.field else: field = opts.get_field(field_name).field field_select_mask = select_mask.setdefault(field, {}) related_model = field.model._meta.concrete_model self._get_defer_select_mask( related_model._meta, field_mask, field_select_mask ) return select_mask def _get_only_select_mask(self, opts, mask, select_mask=None): if select_mask is None: select_mask = {} select_mask[opts.pk] = {} # Only include fields mentioned in the mask. for field_name, field_mask in mask.items(): field = opts.get_field(field_name) field_select_mask = select_mask.setdefault(field, {}) if field_mask: if not field.is_relation: raise FieldError(next(iter(field_mask))) related_model = field.remote_field.model._meta.concrete_model self._get_only_select_mask( related_model._meta, field_mask, field_select_mask ) return select_mask def get_select_mask(self): """ Convert the self.deferred_loading data structure to an alternate data structure, describing the field that *will* be loaded. This is used to compute the columns to select from the database and also by the QuerySet class to work out which fields are being initialized on each model. Models that have all their fields included aren't mentioned in the result, only those that have field restrictions in place. """ field_names, defer = self.deferred_loading if not field_names: return {} mask = {} for field_name in field_names: part_mask = mask for part in field_name.split(LOOKUP_SEP): part_mask = part_mask.setdefault(part, {}) opts = self.get_meta() if defer: return self._get_defer_select_mask(opts, mask) return self._get_only_select_mask(opts, mask) def table_alias(self, table_name, create=False, filtered_relation=None): """ Return a table alias for the given table_name and whether this is a new alias or not. If 'create' is true, a new alias is always created. Otherwise, the most recently created alias for the table (if one exists) is reused. """ alias_list = self.table_map.get(table_name) if not create and alias_list: alias = alias_list[0] self.alias_refcount[alias] += 1 return alias, False # Create a new alias for this table. if alias_list: alias = "%s%d" % (self.alias_prefix, len(self.alias_map) + 1) alias_list.append(alias) else: # The first occurrence of a table uses the table name directly. alias = ( filtered_relation.alias if filtered_relation is not None else table_name ) self.table_map[table_name] = [alias] self.alias_refcount[alias] = 1 return alias, True def ref_alias(self, alias): """Increases the reference count for this alias.""" self.alias_refcount[alias] += 1 def unref_alias(self, alias, amount=1): """Decreases the reference count for this alias.""" self.alias_refcount[alias] -= amount def promote_joins(self, aliases): """ Promote recursively the join type of given aliases and its children to an outer join. If 'unconditional' is False, only promote the join if it is nullable or the parent join is an outer join. The children promotion is done to avoid join chains that contain a LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b is promoted, then we must also promote b->c automatically, or otherwise the promotion of a->b doesn't actually change anything in the query results. """ aliases = list(aliases) while aliases: alias = aliases.pop(0) if self.alias_map[alias].join_type is None: # This is the base table (first FROM entry) - this table # isn't really joined at all in the query, so we should not # alter its join type. continue # Only the first alias (skipped above) should have None join_type assert self.alias_map[alias].join_type is not None parent_alias = self.alias_map[alias].parent_alias parent_louter = ( parent_alias and self.alias_map[parent_alias].join_type == LOUTER ) already_louter = self.alias_map[alias].join_type == LOUTER if (self.alias_map[alias].nullable or parent_louter) and not already_louter: self.alias_map[alias] = self.alias_map[alias].promote() # Join type of 'alias' changed, so re-examine all aliases that # refer to this one. aliases.extend( join for join in self.alias_map if self.alias_map[join].parent_alias == alias and join not in aliases ) def demote_joins(self, aliases): """ Change join type from LOUTER to INNER for all joins in aliases. Similarly to promote_joins(), this method must ensure no join chains containing first an outer, then an inner join are generated. If we are demoting b->c join in chain a LOUTER b LOUTER c then we must demote a->b automatically, or otherwise the demotion of b->c doesn't actually change anything in the query results. . """ aliases = list(aliases) while aliases: alias = aliases.pop(0) if self.alias_map[alias].join_type == LOUTER: self.alias_map[alias] = self.alias_map[alias].demote() parent_alias = self.alias_map[alias].parent_alias if self.alias_map[parent_alias].join_type == INNER: aliases.append(parent_alias) def reset_refcounts(self, to_counts): """ Reset reference counts for aliases so that they match the value passed in `to_counts`. """ for alias, cur_refcount in self.alias_refcount.copy().items(): unref_amount = cur_refcount - to_counts.get(alias, 0) self.unref_alias(alias, unref_amount) def change_aliases(self, change_map): """ Change the aliases in change_map (which maps old-alias -> new-alias), relabelling any references to them in select columns and the where clause. """ # If keys and values of change_map were to intersect, an alias might be # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending # on their order in change_map. assert set(change_map).isdisjoint(change_map.values()) # 1. Update references in "select" (normal columns plus aliases), # "group by" and "where". self.where.relabel_aliases(change_map) if isinstance(self.group_by, tuple): self.group_by = tuple( [col.relabeled_clone(change_map) for col in self.group_by] ) self.select = tuple([col.relabeled_clone(change_map) for col in self.select]) self.annotations = self.annotations and { key: col.relabeled_clone(change_map) for key, col in self.annotations.items() } # 2. Rename the alias in the internal table/alias datastructures. for old_alias, new_alias in change_map.items(): if old_alias not in self.alias_map: continue alias_data = self.alias_map[old_alias].relabeled_clone(change_map) self.alias_map[new_alias] = alias_data self.alias_refcount[new_alias] = self.alias_refcount[old_alias] del self.alias_refcount[old_alias] del self.alias_map[old_alias] table_aliases = self.table_map[alias_data.table_name] for pos, alias in enumerate(table_aliases): if alias == old_alias: table_aliases[pos] = new_alias break self.external_aliases = { # Table is aliased or it's being changed and thus is aliased. change_map.get(alias, alias): (aliased or alias in change_map) for alias, aliased in self.external_aliases.items() } def bump_prefix(self, other_query, exclude=None): """ Change the alias prefix to the next letter in the alphabet in a way that the other query's aliases and this query's aliases will not conflict. Even tables that previously had no alias will get an alias after this call. To prevent changing aliases use the exclude parameter. """ def prefix_gen(): """ Generate a sequence of characters in alphabetical order: -> 'A', 'B', 'C', ... When the alphabet is finished, the sequence will continue with the Cartesian product: -> 'AA', 'AB', 'AC', ... """ alphabet = ascii_uppercase prefix = chr(ord(self.alias_prefix) + 1) yield prefix for n in count(1): seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet for s in product(seq, repeat=n): yield "".join(s) prefix = None if self.alias_prefix != other_query.alias_prefix: # No clashes between self and outer query should be possible. return # Explicitly avoid infinite loop. The constant divider is based on how # much depth recursive subquery references add to the stack. This value # might need to be adjusted when adding or removing function calls from # the code path in charge of performing these operations. local_recursion_limit = sys.getrecursionlimit() // 16 for pos, prefix in enumerate(prefix_gen()): if prefix not in self.subq_aliases: self.alias_prefix = prefix break if pos > local_recursion_limit: raise RecursionError( "Maximum recursion depth exceeded: too many subqueries." ) self.subq_aliases = self.subq_aliases.union([self.alias_prefix]) other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases) if exclude is None: exclude = {} self.change_aliases( { alias: "%s%d" % (self.alias_prefix, pos) for pos, alias in enumerate(self.alias_map) if alias not in exclude } ) def get_initial_alias(self): """ Return the first alias for this query, after increasing its reference count. """ if self.alias_map: alias = self.base_table self.ref_alias(alias) elif self.model: alias = self.join(self.base_table_class(self.get_meta().db_table, None)) else: alias = None return alias def count_active_tables(self): """ Return the number of tables in this query with a non-zero reference count. After execution, the reference counts are zeroed, so tables added in compiler will not be seen by this method. """ return len([1 for count in self.alias_refcount.values() if count]) def join(self, join, reuse=None, reuse_with_filtered_relation=False): """ Return an alias for the 'join', either reusing an existing alias for that join or creating a new one. 'join' is either a base_table_class or join_class. The 'reuse' parameter can be either None which means all joins are reusable, or it can be a set containing the aliases that can be reused. The 'reuse_with_filtered_relation' parameter is used when computing FilteredRelation instances. A join is always created as LOUTER if the lhs alias is LOUTER to make sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new joins are created as LOUTER if the join is nullable. """ if reuse_with_filtered_relation and reuse: reuse_aliases = [ a for a, j in self.alias_map.items() if a in reuse and j.equals(join) ] else: reuse_aliases = [ a for a, j in self.alias_map.items() if (reuse is None or a in reuse) and j == join ] if reuse_aliases: if join.table_alias in reuse_aliases: reuse_alias = join.table_alias else: # Reuse the most recent alias of the joined table # (a many-to-many relation may be joined multiple times). reuse_alias = reuse_aliases[-1] self.ref_alias(reuse_alias) return reuse_alias # No reuse is possible, so we need a new alias. alias, _ = self.table_alias( join.table_name, create=True, filtered_relation=join.filtered_relation ) if join.join_type: if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable: join_type = LOUTER else: join_type = INNER join.join_type = join_type join.table_alias = alias self.alias_map[alias] = join return alias def join_parent_model(self, opts, model, alias, seen): """ Make sure the given 'model' is joined in the query. If 'model' isn't a parent of 'opts' or if it is None this method is a no-op. The 'alias' is the root alias for starting the join, 'seen' is a dict of model -> alias of existing joins. It must also contain a mapping of None -> some alias. This will be returned in the no-op case. """ if model in seen: return seen[model] chain = opts.get_base_chain(model) if not chain: return alias curr_opts = opts for int_model in chain: if int_model in seen: curr_opts = int_model._meta alias = seen[int_model] continue # Proxy model have elements in base chain # with no parents, assign the new options # object and skip to the next base in that # case if not curr_opts.parents[int_model]: curr_opts = int_model._meta continue link_field = curr_opts.get_ancestor_link(int_model) join_info = self.setup_joins([link_field.name], curr_opts, alias) curr_opts = int_model._meta alias = seen[int_model] = join_info.joins[-1] return alias or seen[None] def check_alias(self, alias): if FORBIDDEN_ALIAS_PATTERN.search(alias): raise ValueError( "Column aliases cannot contain whitespace characters, quotation marks, " "semicolons, or SQL comments." ) def add_annotation(self, annotation, alias, select=True): """Add a single annotation expression to the Query.""" self.check_alias(alias) annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None) if select: self.append_annotation_mask([alias]) else: annotation_mask = ( value for value in dict.fromkeys(self.annotation_select) if value != alias ) self.set_annotation_mask(annotation_mask) self.annotations[alias] = annotation def resolve_expression(self, query, *args, **kwargs): clone = self.clone() # Subqueries need to use a different set of aliases than the outer query. clone.bump_prefix(query) clone.subquery = True clone.where.resolve_expression(query, *args, **kwargs) # Resolve combined queries. if clone.combinator: clone.combined_queries = tuple( [ combined_query.resolve_expression(query, *args, **kwargs) for combined_query in clone.combined_queries ] ) for key, value in clone.annotations.items(): resolved = value.resolve_expression(query, *args, **kwargs) if hasattr(resolved, "external_aliases"): resolved.external_aliases.update(clone.external_aliases) clone.annotations[key] = resolved # Outer query's aliases are considered external. for alias, table in query.alias_map.items(): clone.external_aliases[alias] = ( isinstance(table, Join) and table.join_field.related_model._meta.db_table != alias ) or ( isinstance(table, BaseTable) and table.table_name != table.table_alias ) return clone def get_external_cols(self): exprs = chain(self.annotations.values(), self.where.children) return [ col for col in self._gen_cols(exprs, include_external=True) if col.alias in self.external_aliases ] def get_group_by_cols(self, wrapper=None): # If wrapper is referenced by an alias for an explicit GROUP BY through # values() a reference to this expression and not the self must be # returned to ensure external column references are not grouped against # as well. external_cols = self.get_external_cols() if any(col.possibly_multivalued for col in external_cols): return [wrapper or self] return external_cols def as_sql(self, compiler, connection): # Some backends (e.g. Oracle) raise an error when a subquery contains # unnecessary ORDER BY clause. if ( self.subquery and not connection.features.ignores_unnecessary_order_by_in_subqueries ): self.clear_ordering(force=False) for query in self.combined_queries: query.clear_ordering(force=False) sql, params = self.get_compiler(connection=connection).as_sql() if self.subquery: sql = "(%s)" % sql return sql, params def resolve_lookup_value(self, value, can_reuse, allow_joins): if hasattr(value, "resolve_expression"): value = value.resolve_expression( self, reuse=can_reuse, allow_joins=allow_joins, ) elif isinstance(value, (list, tuple)): # The items of the iterable may be expressions and therefore need # to be resolved independently. values = ( self.resolve_lookup_value(sub_value, can_reuse, allow_joins) for sub_value in value ) type_ = type(value) if hasattr(type_, "_make"): # namedtuple return type_(*values) return type_(values) return value def solve_lookup_type(self, lookup, summarize=False): """ Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains'). """ lookup_splitted = lookup.split(LOOKUP_SEP) if self.annotations: annotation, expression_lookups = refs_expression( lookup_splitted, self.annotations ) if annotation: expression = self.annotations[annotation] if summarize: expression = Ref(annotation, expression) return expression_lookups, (), expression _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)] if len(lookup_parts) > 1 and not field_parts: raise FieldError( 'Invalid lookup "%s" for model %s".' % (lookup, self.get_meta().model.__name__) ) return lookup_parts, field_parts, False def check_query_object_type(self, value, opts, field): """ Check whether the object passed while querying is of the correct type. If not, raise a ValueError specifying the wrong object. """ if hasattr(value, "_meta"): if not check_rel_lookup_compatibility(value._meta.model, opts, field): raise ValueError( 'Cannot query "%s": Must be "%s" instance.' % (value, opts.object_name) ) def check_related_objects(self, field, value, opts): """Check the type of object passed to query relations.""" if field.is_relation: # Check that the field and the queryset use the same model in a # query like .filter(author=Author.objects.all()). For example, the # opts would be Author's (from the author field) and value.model # would be Author.objects.all() queryset's .model (Author also). # The field is the related field on the lhs side. if ( isinstance(value, Query) and not value.has_select_fields and not check_rel_lookup_compatibility(value.model, opts, field) ): raise ValueError( 'Cannot use QuerySet for "%s": Use a QuerySet for "%s".' % (value.model._meta.object_name, opts.object_name) ) elif hasattr(value, "_meta"): self.check_query_object_type(value, opts, field) elif hasattr(value, "__iter__"): for v in value: self.check_query_object_type(v, opts, field) def check_filterable(self, expression): """Raise an error if expression cannot be used in a WHERE clause.""" if hasattr(expression, "resolve_expression") and not getattr( expression, "filterable", True ): raise NotSupportedError( expression.__class__.__name__ + " is disallowed in the filter " "clause." ) if hasattr(expression, "get_source_expressions"): for expr in expression.get_source_expressions(): self.check_filterable(expr) def build_lookup(self, lookups, lhs, rhs): """ Try to extract transforms and lookup from given lhs. The lhs value is something that works like SQLExpression. The rhs value is what the lookup is going to compare against. The lookups is a list of names to extract using get_lookup() and get_transform(). """ # __exact is the default lookup if one isn't given. *transforms, lookup_name = lookups or ["exact"] for name in transforms: lhs = self.try_transform(lhs, name) # First try get_lookup() so that the lookup takes precedence if the lhs # supports both transform and lookup for the name. lookup_class = lhs.get_lookup(lookup_name) if not lookup_class: # A lookup wasn't found. Try to interpret the name as a transform # and do an Exact lookup against it. lhs = self.try_transform(lhs, lookup_name) lookup_name = "exact" lookup_class = lhs.get_lookup(lookup_name) if not lookup_class: return lookup = lookup_class(lhs, rhs) # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all # uses of None as a query value unless the lookup supports it. if lookup.rhs is None and not lookup.can_use_none_as_rhs: if lookup_name not in ("exact", "iexact"): raise ValueError("Cannot use None as a query value") return lhs.get_lookup("isnull")(lhs, True) # For Oracle '' is equivalent to null. The check must be done at this # stage because join promotion can't be done in the compiler. Using # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here. # A similar thing is done in is_nullable(), too. if ( lookup_name == "exact" and lookup.rhs == "" and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls ): return lhs.get_lookup("isnull")(lhs, True) return lookup def try_transform(self, lhs, name): """ Helper method for build_lookup(). Try to fetch and initialize a transform for name parameter from lhs. """ transform_class = lhs.get_transform(name) if transform_class: return transform_class(lhs) else: output_field = lhs.output_field.__class__ suggested_lookups = difflib.get_close_matches( name, output_field.get_lookups() ) if suggested_lookups: suggestion = ", perhaps you meant %s?" % " or ".join(suggested_lookups) else: suggestion = "." raise FieldError( "Unsupported lookup '%s' for %s or join on the field not " "permitted%s" % (name, output_field.__name__, suggestion) ) def build_filter( self, filter_expr, branch_negated=False, current_negated=False, can_reuse=None, allow_joins=True, split_subq=True, reuse_with_filtered_relation=False, check_filterable=True, summarize=False, ): """ Build a WhereNode for a single filter clause but don't add it to this Query. Query.add_q() will then add this filter to the where Node. The 'branch_negated' tells us if the current branch contains any negations. This will be used to determine if subqueries are needed. The 'current_negated' is used to determine if the current filter is negated or not and this will be used to determine if IS NULL filtering is needed. The difference between current_negated and branch_negated is that branch_negated is set on first negation, but current_negated is flipped for each negation. Note that add_filter will not do any negating itself, that is done upper in the code by add_q(). The 'can_reuse' is a set of reusable joins for multijoins. If 'reuse_with_filtered_relation' is True, then only joins in can_reuse will be reused. The method will create a filter clause that can be added to the current query. However, if the filter isn't added to the query then the caller is responsible for unreffing the joins used. """ if isinstance(filter_expr, dict): raise FieldError("Cannot parse keyword query as dict") if isinstance(filter_expr, Q): return self._add_q( filter_expr, branch_negated=branch_negated, current_negated=current_negated, used_aliases=can_reuse, allow_joins=allow_joins, split_subq=split_subq, check_filterable=check_filterable, summarize=summarize, ) if hasattr(filter_expr, "resolve_expression"): if not getattr(filter_expr, "conditional", False): raise TypeError("Cannot filter against a non-conditional expression.") condition = filter_expr.resolve_expression( self, allow_joins=allow_joins, summarize=summarize ) if not isinstance(condition, Lookup): condition = self.build_lookup(["exact"], condition, True) return WhereNode([condition], connector=AND), [] arg, value = filter_expr if not arg: raise FieldError("Cannot parse keyword query %r" % arg) lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize) if check_filterable: self.check_filterable(reffed_expression) if not allow_joins and len(parts) > 1: raise FieldError("Joined field references are not permitted in this query") pre_joins = self.alias_refcount.copy() value = self.resolve_lookup_value(value, can_reuse, allow_joins) used_joins = { k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0) } if check_filterable: self.check_filterable(value) if reffed_expression: condition = self.build_lookup(lookups, reffed_expression, value) return WhereNode([condition], connector=AND), [] opts = self.get_meta() alias = self.get_initial_alias() allow_many = not branch_negated or not split_subq try: join_info = self.setup_joins( parts, opts, alias, can_reuse=can_reuse, allow_many=allow_many, reuse_with_filtered_relation=reuse_with_filtered_relation, ) # Prevent iterator from being consumed by check_related_objects() if isinstance(value, Iterator): value = list(value) self.check_related_objects(join_info.final_field, value, join_info.opts) # split_exclude() needs to know which joins were generated for the # lookup parts self._lookup_joins = join_info.joins except MultiJoin as e: return self.split_exclude(filter_expr, can_reuse, e.names_with_path) # Update used_joins before trimming since they are reused to determine # which joins could be later promoted to INNER. used_joins.update(join_info.joins) targets, alias, join_list = self.trim_joins( join_info.targets, join_info.joins, join_info.path ) if can_reuse is not None: can_reuse.update(join_list) if join_info.final_field.is_relation: if len(targets) == 1: col = self._get_col(targets[0], join_info.final_field, alias) else: col = MultiColSource( alias, targets, join_info.targets, join_info.final_field ) else: col = self._get_col(targets[0], join_info.final_field, alias) condition = self.build_lookup(lookups, col, value) lookup_type = condition.lookup_name clause = WhereNode([condition], connector=AND) require_outer = ( lookup_type == "isnull" and condition.rhs is True and not current_negated ) if ( current_negated and (lookup_type != "isnull" or condition.rhs is False) and condition.rhs is not None ): require_outer = True if lookup_type != "isnull": # The condition added here will be SQL like this: # NOT (col IS NOT NULL), where the first NOT is added in # upper layers of code. The reason for addition is that if col # is null, then col != someval will result in SQL "unknown" # which isn't the same as in Python. The Python None handling # is wanted, and it can be gotten by # (col IS NULL OR col != someval) # <=> # NOT (col IS NOT NULL AND col = someval). if ( self.is_nullable(targets[0]) or self.alias_map[join_list[-1]].join_type == LOUTER ): lookup_class = targets[0].get_lookup("isnull") col = self._get_col(targets[0], join_info.targets[0], alias) clause.add(lookup_class(col, False), AND) # If someval is a nullable column, someval IS NOT NULL is # added. if isinstance(value, Col) and self.is_nullable(value.target): lookup_class = value.target.get_lookup("isnull") clause.add(lookup_class(value, False), AND) return clause, used_joins if not require_outer else () def add_filter(self, filter_lhs, filter_rhs): self.add_q(Q((filter_lhs, filter_rhs))) def add_q(self, q_object): """ A preprocessor for the internal _add_q(). Responsible for doing final join promotion. """ # For join promotion this case is doing an AND for the added q_object # and existing conditions. So, any existing inner join forces the join # type to remain inner. Existing outer joins can however be demoted. # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if # rel_a doesn't produce any rows, then the whole condition must fail. # So, demotion is OK. existing_inner = { a for a in self.alias_map if self.alias_map[a].join_type == INNER } clause, _ = self._add_q(q_object, self.used_aliases) if clause: self.where.add(clause, AND) self.demote_joins(existing_inner) def build_where(self, filter_expr): return self.build_filter(filter_expr, allow_joins=False)[0] def clear_where(self): self.where = WhereNode() def _add_q( self, q_object, used_aliases, branch_negated=False, current_negated=False, allow_joins=True, split_subq=True, check_filterable=True, summarize=False, ): """Add a Q-object to the current filter.""" connector = q_object.connector current_negated ^= q_object.negated branch_negated = branch_negated or q_object.negated target_clause = WhereNode(connector=connector, negated=q_object.negated) joinpromoter = JoinPromoter( q_object.connector, len(q_object.children), current_negated ) for child in q_object.children: child_clause, needed_inner = self.build_filter( child, can_reuse=used_aliases, branch_negated=branch_negated, current_negated=current_negated, allow_joins=allow_joins, split_subq=split_subq, check_filterable=check_filterable, summarize=summarize, ) joinpromoter.add_votes(needed_inner) if child_clause: target_clause.add(child_clause, connector) needed_inner = joinpromoter.update_join_types(self) return target_clause, needed_inner def build_filtered_relation_q( self, q_object, reuse, branch_negated=False, current_negated=False ): """Add a FilteredRelation object to the current filter.""" connector = q_object.connector current_negated ^= q_object.negated branch_negated = branch_negated or q_object.negated target_clause = WhereNode(connector=connector, negated=q_object.negated) for child in q_object.children: if isinstance(child, Node): child_clause = self.build_filtered_relation_q( child, reuse=reuse, branch_negated=branch_negated, current_negated=current_negated, ) else: child_clause, _ = self.build_filter( child, can_reuse=reuse, branch_negated=branch_negated, current_negated=current_negated, allow_joins=True, split_subq=False, reuse_with_filtered_relation=True, ) target_clause.add(child_clause, connector) return target_clause def add_filtered_relation(self, filtered_relation, alias): filtered_relation.alias = alias lookups = dict(get_children_from_q(filtered_relation.condition)) relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type( filtered_relation.relation_name ) if relation_lookup_parts: raise ValueError( "FilteredRelation's relation_name cannot contain lookups " "(got %r)." % filtered_relation.relation_name ) for lookup in chain(lookups): lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup) shift = 2 if not lookup_parts else 1 lookup_field_path = lookup_field_parts[:-shift] for idx, lookup_field_part in enumerate(lookup_field_path): if len(relation_field_parts) > idx: if relation_field_parts[idx] != lookup_field_part: raise ValueError( "FilteredRelation's condition doesn't support " "relations outside the %r (got %r)." % (filtered_relation.relation_name, lookup) ) else: raise ValueError( "FilteredRelation's condition doesn't support nested " "relations deeper than the relation_name (got %r for " "%r)." % (lookup, filtered_relation.relation_name) ) self._filtered_relations[filtered_relation.alias] = filtered_relation def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False): """ Walk the list of names and turns them into PathInfo tuples. A single name in 'names' can generate multiple PathInfos (m2m, for example). 'names' is the path of names to travel, 'opts' is the model Options we start the name resolving from, 'allow_many' is as for setup_joins(). If fail_on_missing is set to True, then a name that can't be resolved will generate a FieldError. Return a list of PathInfo tuples. In addition return the final field (the last used join field) and target (which is a field guaranteed to contain the same value as the final field). Finally, return those names that weren't found (which are likely transforms and the final lookup). """ path, names_with_path = [], [] for pos, name in enumerate(names): cur_names_with_path = (name, []) if name == "pk": name = opts.pk.name field = None filtered_relation = None try: if opts is None: raise FieldDoesNotExist field = opts.get_field(name) except FieldDoesNotExist: if name in self.annotation_select: field = self.annotation_select[name].output_field elif name in self._filtered_relations and pos == 0: filtered_relation = self._filtered_relations[name] if LOOKUP_SEP in filtered_relation.relation_name: parts = filtered_relation.relation_name.split(LOOKUP_SEP) filtered_relation_path, field, _, _ = self.names_to_path( parts, opts, allow_many, fail_on_missing, ) path.extend(filtered_relation_path[:-1]) else: field = opts.get_field(filtered_relation.relation_name) if field is not None: # Fields that contain one-to-many relations with a generic # model (like a GenericForeignKey) cannot generate reverse # relations and therefore cannot be used for reverse querying. if field.is_relation and not field.related_model: raise FieldError( "Field %r does not generate an automatic reverse " "relation and therefore cannot be used for reverse " "querying. If it is a GenericForeignKey, consider " "adding a GenericRelation." % name ) try: model = field.model._meta.concrete_model except AttributeError: # QuerySet.annotate() may introduce fields that aren't # attached to a model. model = None else: # We didn't find the current field, so move position back # one step. pos -= 1 if pos == -1 or fail_on_missing: available = sorted( [ *get_field_names_from_opts(opts), *self.annotation_select, *self._filtered_relations, ] ) raise FieldError( "Cannot resolve keyword '%s' into field. " "Choices are: %s" % (name, ", ".join(available)) ) break # Check if we need any joins for concrete inheritance cases (the # field lives in parent, but we are currently in one of its # children) if opts is not None and model is not opts.model: path_to_parent = opts.get_path_to_parent(model) if path_to_parent: path.extend(path_to_parent) cur_names_with_path[1].extend(path_to_parent) opts = path_to_parent[-1].to_opts if hasattr(field, "path_infos"): if filtered_relation: pathinfos = field.get_path_info(filtered_relation) else: pathinfos = field.path_infos if not allow_many: for inner_pos, p in enumerate(pathinfos): if p.m2m: cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1]) names_with_path.append(cur_names_with_path) raise MultiJoin(pos + 1, names_with_path) last = pathinfos[-1] path.extend(pathinfos) final_field = last.join_field opts = last.to_opts targets = last.target_fields cur_names_with_path[1].extend(pathinfos) names_with_path.append(cur_names_with_path) else: # Local non-relational field. final_field = field targets = (field,) if fail_on_missing and pos + 1 != len(names): raise FieldError( "Cannot resolve keyword %r into field. Join on '%s'" " not permitted." % (names[pos + 1], name) ) break return path, final_field, targets, names[pos + 1 :] def setup_joins( self, names, opts, alias, can_reuse=None, allow_many=True, reuse_with_filtered_relation=False, ): """ Compute the necessary table joins for the passage through the fields given in 'names'. 'opts' is the Options class for the current model (which gives the table we are starting from), 'alias' is the alias for the table to start the joining from. The 'can_reuse' defines the reverse foreign key joins we can reuse. It can be None in which case all joins are reusable or a set of aliases that can be reused. Note that non-reverse foreign keys are always reusable when using setup_joins(). The 'reuse_with_filtered_relation' can be used to force 'can_reuse' parameter and force the relation on the given connections. If 'allow_many' is False, then any reverse foreign key seen will generate a MultiJoin exception. Return the final field involved in the joins, the target field (used for any 'where' constraint), the final 'opts' value, the joins, the field path traveled to generate the joins, and a transform function that takes a field and alias and is equivalent to `field.get_col(alias)` in the simple case but wraps field transforms if they were included in names. The target field is the field containing the concrete value. Final field can be something different, for example foreign key pointing to that value. Final field is needed for example in some value conversions (convert 'obj' in fk__id=obj to pk val using the foreign key field for example). """ joins = [alias] # The transform can't be applied yet, as joins must be trimmed later. # To avoid making every caller of this method look up transforms # directly, compute transforms here and create a partial that converts # fields to the appropriate wrapped version. def final_transformer(field, alias): if not self.alias_cols: alias = None return field.get_col(alias) # Try resolving all the names as fields first. If there's an error, # treat trailing names as lookups until a field can be resolved. last_field_exception = None for pivot in range(len(names), 0, -1): try: path, final_field, targets, rest = self.names_to_path( names[:pivot], opts, allow_many, fail_on_missing=True, ) except FieldError as exc: if pivot == 1: # The first item cannot be a lookup, so it's safe # to raise the field error here. raise else: last_field_exception = exc else: # The transforms are the remaining items that couldn't be # resolved into fields. transforms = names[pivot:] break for name in transforms: def transform(field, alias, *, name, previous): try: wrapped = previous(field, alias) return self.try_transform(wrapped, name) except FieldError: # FieldError is raised if the transform doesn't exist. if isinstance(final_field, Field) and last_field_exception: raise last_field_exception else: raise final_transformer = functools.partial( transform, name=name, previous=final_transformer ) final_transformer.has_transforms = True # Then, add the path to the query's joins. Note that we can't trim # joins at this stage - we will need the information about join type # of the trimmed joins. for join in path: if join.filtered_relation: filtered_relation = join.filtered_relation.clone() table_alias = filtered_relation.alias else: filtered_relation = None table_alias = None opts = join.to_opts if join.direct: nullable = self.is_nullable(join.join_field) else: nullable = True connection = self.join_class( opts.db_table, alias, table_alias, INNER, join.join_field, nullable, filtered_relation=filtered_relation, ) reuse = can_reuse if join.m2m or reuse_with_filtered_relation else None alias = self.join( connection, reuse=reuse, reuse_with_filtered_relation=reuse_with_filtered_relation, ) joins.append(alias) if filtered_relation: filtered_relation.path = joins[:] return JoinInfo(final_field, targets, opts, joins, path, final_transformer) def trim_joins(self, targets, joins, path): """ The 'target' parameter is the final field being joined to, 'joins' is the full list of join aliases. The 'path' contain the PathInfos used to create the joins. Return the final target field and table alias and the new active joins. Always trim any direct join if the target column is already in the previous table. Can't trim reverse joins as it's unknown if there's anything on the other side of the join. """ joins = joins[:] for pos, info in enumerate(reversed(path)): if len(joins) == 1 or not info.direct: break if info.filtered_relation: break join_targets = {t.column for t in info.join_field.foreign_related_fields} cur_targets = {t.column for t in targets} if not cur_targets.issubset(join_targets): break targets_dict = { r[1].column: r[0] for r in info.join_field.related_fields if r[1].column in cur_targets } targets = tuple(targets_dict[t.column] for t in targets) self.unref_alias(joins.pop()) return targets, joins[-1], joins @classmethod def _gen_cols(cls, exprs, include_external=False, resolve_refs=True): for expr in exprs: if isinstance(expr, Col): yield expr elif include_external and callable( getattr(expr, "get_external_cols", None) ): yield from expr.get_external_cols() elif hasattr(expr, "get_source_expressions"): if not resolve_refs and isinstance(expr, Ref): continue yield from cls._gen_cols( expr.get_source_expressions(), include_external=include_external, resolve_refs=resolve_refs, ) @classmethod def _gen_col_aliases(cls, exprs): yield from (expr.alias for expr in cls._gen_cols(exprs)) def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False): annotation = self.annotations.get(name) if annotation is not None: if not allow_joins: for alias in self._gen_col_aliases([annotation]): if isinstance(self.alias_map[alias], Join): raise FieldError( "Joined field references are not permitted in this query" ) if summarize: # Summarize currently means we are doing an aggregate() query # which is executed as a wrapped subquery if any of the # aggregate() elements reference an existing annotation. In # that case we need to return a Ref to the subquery's annotation. if name not in self.annotation_select: raise FieldError( "Cannot aggregate over the '%s' alias. Use annotate() " "to promote it." % name ) return Ref(name, self.annotation_select[name]) else: return annotation else: field_list = name.split(LOOKUP_SEP) annotation = self.annotations.get(field_list[0]) if annotation is not None: for transform in field_list[1:]: annotation = self.try_transform(annotation, transform) return annotation join_info = self.setup_joins( field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse ) targets, final_alias, join_list = self.trim_joins( join_info.targets, join_info.joins, join_info.path ) if not allow_joins and len(join_list) > 1: raise FieldError( "Joined field references are not permitted in this query" ) if len(targets) > 1: raise FieldError( "Referencing multicolumn fields with F() objects isn't supported" ) # Verify that the last lookup in name is a field or a transform: # transform_function() raises FieldError if not. transform = join_info.transform_function(targets[0], final_alias) if reuse is not None: reuse.update(join_list) return transform def split_exclude(self, filter_expr, can_reuse, names_with_path): """ When doing an exclude against any kind of N-to-many relation, we need to use a subquery. This method constructs the nested query, given the original exclude filter (filter_expr) and the portion up to the first N-to-many relation field. For example, if the origin filter is ~Q(child__name='foo'), filter_expr is ('child__name', 'foo') and can_reuse is a set of joins usable for filters in the original query. We will turn this into equivalent of: WHERE NOT EXISTS( SELECT 1 FROM child WHERE name = 'foo' AND child.parent_id = parent.id LIMIT 1 ) """ # Generate the inner query. query = self.__class__(self.model) query._filtered_relations = self._filtered_relations filter_lhs, filter_rhs = filter_expr if isinstance(filter_rhs, OuterRef): filter_rhs = OuterRef(filter_rhs) elif isinstance(filter_rhs, F): filter_rhs = OuterRef(filter_rhs.name) query.add_filter(filter_lhs, filter_rhs) query.clear_ordering(force=True) # Try to have as simple as possible subquery -> trim leading joins from # the subquery. trimmed_prefix, contains_louter = query.trim_start(names_with_path) col = query.select[0] select_field = col.target alias = col.alias if alias in can_reuse: pk = select_field.model._meta.pk # Need to add a restriction so that outer query's filters are in effect for # the subquery, too. query.bump_prefix(self) lookup_class = select_field.get_lookup("exact") # Note that the query.select[0].alias is different from alias # due to bump_prefix above. lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias)) query.where.add(lookup, AND) query.external_aliases[alias] = True lookup_class = select_field.get_lookup("exact") lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix)) query.where.add(lookup, AND) condition, needed_inner = self.build_filter(Exists(query)) if contains_louter: or_null_condition, _ = self.build_filter( ("%s__isnull" % trimmed_prefix, True), current_negated=True, branch_negated=True, can_reuse=can_reuse, ) condition.add(or_null_condition, OR) # Note that the end result will be: # (outercol NOT IN innerq AND outercol IS NOT NULL) OR outercol IS NULL. # This might look crazy but due to how IN works, this seems to be # correct. If the IS NOT NULL check is removed then outercol NOT # IN will return UNKNOWN. If the IS NULL check is removed, then if # outercol IS NULL we will not match the row. return condition, needed_inner def set_empty(self): self.where.add(NothingNode(), AND) for query in self.combined_queries: query.set_empty() def is_empty(self): return any(isinstance(c, NothingNode) for c in self.where.children) def set_limits(self, low=None, high=None): """ Adjust the limits on the rows retrieved. Use low/high to set these, as it makes it more Pythonic to read and write. When the SQL query is created, convert them to the appropriate offset and limit values. Apply any limits passed in here to the existing constraints. Add low to the current low value and clamp both to any existing high value. """ if high is not None: if self.high_mark is not None: self.high_mark = min(self.high_mark, self.low_mark + high) else: self.high_mark = self.low_mark + high if low is not None: if self.high_mark is not None: self.low_mark = min(self.high_mark, self.low_mark + low) else: self.low_mark = self.low_mark + low if self.low_mark == self.high_mark: self.set_empty() def clear_limits(self): """Clear any existing limits.""" self.low_mark, self.high_mark = 0, None @property def is_sliced(self): return self.low_mark != 0 or self.high_mark is not None def has_limit_one(self): return self.high_mark is not None and (self.high_mark - self.low_mark) == 1 def can_filter(self): """ Return True if adding filters to this instance is still possible. Typically, this means no limits or offsets have been put on the results. """ return not self.is_sliced def clear_select_clause(self): """Remove all fields from SELECT clause.""" self.select = () self.default_cols = False self.select_related = False self.set_extra_mask(()) self.set_annotation_mask(()) def clear_select_fields(self): """ Clear the list of fields to select (but not extra_select columns). Some queryset types completely replace any existing list of select columns. """ self.select = () self.values_select = () def add_select_col(self, col, name): self.select += (col,) self.values_select += (name,) def set_select(self, cols): self.default_cols = False self.select = tuple(cols) def add_distinct_fields(self, *field_names): """ Add and resolve the given fields to the query's "distinct on" clause. """ self.distinct_fields = field_names self.distinct = True def add_fields(self, field_names, allow_m2m=True): """ Add the given (model) fields to the select set. Add the field names in the order specified. """ alias = self.get_initial_alias() opts = self.get_meta() try: cols = [] for name in field_names: # Join promotion note - we must not remove any rows here, so # if there is no existing joins, use outer join. join_info = self.setup_joins( name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m ) targets, final_alias, joins = self.trim_joins( join_info.targets, join_info.joins, join_info.path, ) for target in targets: cols.append(join_info.transform_function(target, final_alias)) if cols: self.set_select(cols) except MultiJoin: raise FieldError("Invalid field name: '%s'" % name) except FieldError: if LOOKUP_SEP in name: # For lookups spanning over relationships, show the error # from the model on which the lookup failed. raise else: names = sorted( [ *get_field_names_from_opts(opts), *self.extra, *self.annotation_select, *self._filtered_relations, ] ) raise FieldError( "Cannot resolve keyword %r into field. " "Choices are: %s" % (name, ", ".join(names)) ) def add_ordering(self, *ordering): """ Add items from the 'ordering' sequence to the query's "order by" clause. These items are either field names (not column names) -- possibly with a direction prefix ('-' or '?') -- or OrderBy expressions. If 'ordering' is empty, clear all ordering from the query. """ errors = [] for item in ordering: if isinstance(item, str): if item == "?": continue item = item.removeprefix("-") if item in self.annotations: continue if self.extra and item in self.extra: continue # names_to_path() validates the lookup. A descriptive # FieldError will be raise if it's not. self.names_to_path(item.split(LOOKUP_SEP), self.model._meta) elif not hasattr(item, "resolve_expression"): errors.append(item) if getattr(item, "contains_aggregate", False): raise FieldError( "Using an aggregate in order_by() without also including " "it in annotate() is not allowed: %s" % item ) if errors: raise FieldError("Invalid order_by arguments: %s" % errors) if ordering: self.order_by += ordering else: self.default_ordering = False def clear_ordering(self, force=False, clear_default=True): """ Remove any ordering settings if the current query allows it without side effects, set 'force' to True to clear the ordering regardless. If 'clear_default' is True, there will be no ordering in the resulting query (not even the model's default). """ if not force and ( self.is_sliced or self.distinct_fields or self.select_for_update ): return self.order_by = () self.extra_order_by = () if clear_default: self.default_ordering = False def set_group_by(self, allow_aliases=True): """ Expand the GROUP BY clause required by the query. This will usually be the set of all non-aggregate fields in the return data. If the database backend supports grouping by the primary key, and the query would be equivalent, the optimization will be made automatically. """ if allow_aliases and self.values_select: # If grouping by aliases is allowed assign selected value aliases # by moving them to annotations. group_by_annotations = {} values_select = {} for alias, expr in zip(self.values_select, self.select): if isinstance(expr, Col): values_select[alias] = expr else: group_by_annotations[alias] = expr self.annotations = {**group_by_annotations, **self.annotations} self.append_annotation_mask(group_by_annotations) self.select = tuple(values_select.values()) self.values_select = tuple(values_select) group_by = list(self.select) for alias, annotation in self.annotation_select.items(): if not (group_by_cols := annotation.get_group_by_cols()): continue if allow_aliases and not annotation.contains_aggregate: group_by.append(Ref(alias, annotation)) else: group_by.extend(group_by_cols) self.group_by = tuple(group_by) def add_select_related(self, fields): """ Set up the select_related data structure so that we only select certain related models (as opposed to all models, when self.select_related=True). """ if isinstance(self.select_related, bool): field_dict = {} else: field_dict = self.select_related for field in fields: d = field_dict for part in field.split(LOOKUP_SEP): d = d.setdefault(part, {}) self.select_related = field_dict def add_extra(self, select, select_params, where, params, tables, order_by): """ Add data to the various extra_* attributes for user-created additions to the query. """ if select: # We need to pair any placeholder markers in the 'select' # dictionary with their parameters in 'select_params' so that # subsequent updates to the select dictionary also adjust the # parameters appropriately. select_pairs = {} if select_params: param_iter = iter(select_params) else: param_iter = iter([]) for name, entry in select.items(): self.check_alias(name) entry = str(entry) entry_params = [] pos = entry.find("%s") while pos != -1: if pos == 0 or entry[pos - 1] != "%": entry_params.append(next(param_iter)) pos = entry.find("%s", pos + 2) select_pairs[name] = (entry, entry_params) self.extra.update(select_pairs) if where or params: self.where.add(ExtraWhere(where, params), AND) if tables: self.extra_tables += tuple(tables) if order_by: self.extra_order_by = order_by def clear_deferred_loading(self): """Remove any fields from the deferred loading set.""" self.deferred_loading = (frozenset(), True) def add_deferred_loading(self, field_names): """ Add the given list of model field names to the set of fields to exclude from loading from the database when automatic column selection is done. Add the new field names to any existing field names that are deferred (or removed from any existing field names that are marked as the only ones for immediate loading). """ # Fields on related models are stored in the literal double-underscore # format, so that we can use a set datastructure. We do the foo__bar # splitting and handling when computing the SQL column names (as part of # get_columns()). existing, defer = self.deferred_loading if defer: # Add to existing deferred names. self.deferred_loading = existing.union(field_names), True else: # Remove names from the set of any existing "immediate load" names. if new_existing := existing.difference(field_names): self.deferred_loading = new_existing, False else: self.clear_deferred_loading() if new_only := set(field_names).difference(existing): self.deferred_loading = new_only, True def add_immediate_loading(self, field_names): """ Add the given list of model field names to the set of fields to retrieve when the SQL is executed ("immediate loading" fields). The field names replace any existing immediate loading field names. If there are field names already specified for deferred loading, remove those names from the new field_names before storing the new names for immediate loading. (That is, immediate loading overrides any existing immediate values, but respects existing deferrals.) """ existing, defer = self.deferred_loading field_names = set(field_names) if "pk" in field_names: field_names.remove("pk") field_names.add(self.get_meta().pk.name) if defer: # Remove any existing deferred names from the current set before # setting the new names. self.deferred_loading = field_names.difference(existing), False else: # Replace any existing "immediate load" field names. self.deferred_loading = frozenset(field_names), False def set_annotation_mask(self, names): """Set the mask of annotations that will be returned by the SELECT.""" if names is None: self.annotation_select_mask = None else: self.annotation_select_mask = list(dict.fromkeys(names)) self._annotation_select_cache = None def append_annotation_mask(self, names): if self.annotation_select_mask is not None: self.set_annotation_mask((*self.annotation_select_mask, *names)) def set_extra_mask(self, names): """ Set the mask of extra select items that will be returned by SELECT. Don't remove them from the Query since they might be used later. """ if names is None: self.extra_select_mask = None else: self.extra_select_mask = set(names) self._extra_select_cache = None def set_values(self, fields): self.select_related = False self.clear_deferred_loading() self.clear_select_fields() self.has_select_fields = True if fields: field_names = [] extra_names = [] annotation_names = [] if not self.extra and not self.annotations: # Shortcut - if there are no extra or annotations, then # the values() clause must be just field names. field_names = list(fields) else: self.default_cols = False for f in fields: if f in self.extra_select: extra_names.append(f) elif f in self.annotation_select: annotation_names.append(f) elif f in self.annotations: raise FieldError( f"Cannot select the '{f}' alias. Use annotate() to " "promote it." ) else: # Call `names_to_path` to ensure a FieldError including # annotations about to be masked as valid choices if # `f` is not resolvable. if self.annotation_select: self.names_to_path(f.split(LOOKUP_SEP), self.model._meta) field_names.append(f) self.set_extra_mask(extra_names) self.set_annotation_mask(annotation_names) selected = frozenset(field_names + extra_names + annotation_names) else: field_names = [f.attname for f in self.model._meta.concrete_fields] selected = frozenset(field_names) # Selected annotations must be known before setting the GROUP BY # clause. if self.group_by is True: self.add_fields( (f.attname for f in self.model._meta.concrete_fields), False ) # Disable GROUP BY aliases to avoid orphaning references to the # SELECT clause which is about to be cleared. self.set_group_by(allow_aliases=False) self.clear_select_fields() elif self.group_by: # Resolve GROUP BY annotation references if they are not part of # the selected fields anymore. group_by = [] for expr in self.group_by: if isinstance(expr, Ref) and expr.refs not in selected: expr = self.annotations[expr.refs] group_by.append(expr) self.group_by = tuple(group_by) self.values_select = tuple(field_names) self.add_fields(field_names, True) @property def annotation_select(self): """ Return the dictionary of aggregate columns that are not masked and should be used in the SELECT clause. Cache this result for performance. """ if self._annotation_select_cache is not None: return self._annotation_select_cache elif not self.annotations: return {} elif self.annotation_select_mask is not None: self._annotation_select_cache = { k: self.annotations[k] for k in self.annotation_select_mask if k in self.annotations } return self._annotation_select_cache else: return self.annotations @property def extra_select(self): if self._extra_select_cache is not None: return self._extra_select_cache if not self.extra: return {} elif self.extra_select_mask is not None: self._extra_select_cache = { k: v for k, v in self.extra.items() if k in self.extra_select_mask } return self._extra_select_cache else: return self.extra def trim_start(self, names_with_path): """ Trim joins from the start of the join path. The candidates for trim are the PathInfos in names_with_path structure that are m2m joins. Also set the select column so the start matches the join. This method is meant to be used for generating the subquery joins & cols in split_exclude(). Return a lookup usable for doing outerq.filter(lookup=self) and a boolean indicating if the joins in the prefix contain a LEFT OUTER join. _""" all_paths = [] for _, paths in names_with_path: all_paths.extend(paths) contains_louter = False # Trim and operate only on tables that were generated for # the lookup part of the query. That is, avoid trimming # joins generated for F() expressions. lookup_tables = [ t for t in self.alias_map if t in self._lookup_joins or t == self.base_table ] for trimmed_paths, path in enumerate(all_paths): if path.m2m: break if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER: contains_louter = True alias = lookup_tables[trimmed_paths] self.unref_alias(alias) # The path.join_field is a Rel, lets get the other side's field join_field = path.join_field.field # Build the filter prefix. paths_in_prefix = trimmed_paths trimmed_prefix = [] for name, path in names_with_path: if paths_in_prefix - len(path) < 0: break trimmed_prefix.append(name) paths_in_prefix -= len(path) trimmed_prefix.append(join_field.foreign_related_fields[0].name) trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix) # Lets still see if we can trim the first join from the inner query # (that is, self). We can't do this for: # - LEFT JOINs because we would miss those rows that have nothing on # the outer side, # - INNER JOINs from filtered relations because we would miss their # filters. first_join = self.alias_map[lookup_tables[trimmed_paths + 1]] if first_join.join_type != LOUTER and not first_join.filtered_relation: select_fields = [r[0] for r in join_field.related_fields] select_alias = lookup_tables[trimmed_paths + 1] self.unref_alias(lookup_tables[trimmed_paths]) extra_restriction = join_field.get_extra_restriction( None, lookup_tables[trimmed_paths + 1] ) if extra_restriction: self.where.add(extra_restriction, AND) else: # TODO: It might be possible to trim more joins from the start of the # inner query if it happens to have a longer join chain containing the # values in select_fields. Lets punt this one for now. select_fields = [r[1] for r in join_field.related_fields] select_alias = lookup_tables[trimmed_paths] # The found starting point is likely a join_class instead of a # base_table_class reference. But the first entry in the query's FROM # clause must not be a JOIN. for table in self.alias_map: if self.alias_refcount[table] > 0: self.alias_map[table] = self.base_table_class( self.alias_map[table].table_name, table, ) break self.set_select([f.get_col(select_alias) for f in select_fields]) return trimmed_prefix, contains_louter def is_nullable(self, field): """ Check if the given field should be treated as nullable. Some backends treat '' as null and Django treats such fields as nullable for those backends. In such situations field.null can be False even if we should treat the field as nullable. """ # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have # (nor should it have) knowledge of which connection is going to be # used. The proper fix would be to defer all decisions where # is_nullable() is needed to the compiler stage, but that is not easy # to do currently. return field.null or ( field.empty_strings_allowed and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls ) def get_order_dir(field, default="ASC"): """ Return the field name and direction for an order specification. For example, '-foo' is returned as ('foo', 'DESC'). The 'default' param is used to indicate which way no prefix (or a '+' prefix) should sort. The '-' prefix always sorts the opposite way. """ dirn = ORDER_DIR[default] if field[0] == "-": return field[1:], dirn[1] return field, dirn[0] class JoinPromoter: """ A class to abstract away join promotion problems for complex filter conditions. """ def __init__(self, connector, num_children, negated): self.connector = connector self.negated = negated if self.negated: if connector == AND: self.effective_connector = OR else: self.effective_connector = AND else: self.effective_connector = self.connector self.num_children = num_children # Maps of table alias to how many times it is seen as required for # inner and/or outer joins. self.votes = Counter() def __repr__(self): return ( f"{self.__class__.__qualname__}(connector={self.connector!r}, " f"num_children={self.num_children!r}, negated={self.negated!r})" ) def add_votes(self, votes): """ Add single vote per item to self.votes. Parameter can be any iterable. """ self.votes.update(votes) def update_join_types(self, query): """ Change join types so that the generated query is as efficient as possible, but still correct. So, change as many joins as possible to INNER, but don't make OUTER joins INNER if that could remove results from the query. """ to_promote = set() to_demote = set() # The effective_connector is used so that NOT (a AND b) is treated # similarly to (a OR b) for join promotion. for table, votes in self.votes.items(): # We must use outer joins in OR case when the join isn't contained # in all of the joins. Otherwise the INNER JOIN itself could remove # valid results. Consider the case where a model with rel_a and # rel_b relations is queried with rel_a__col=1 | rel_b__col=2. Now, # if rel_a join doesn't produce any results is null (for example # reverse foreign key or null value in direct foreign key), and # there is a matching row in rel_b with col=2, then an INNER join # to rel_a would remove a valid match from the query. So, we need # to promote any existing INNER to LOUTER (it is possible this # promotion in turn will be demoted later on). if self.effective_connector == OR and votes < self.num_children: to_promote.add(table) # If connector is AND and there is a filter that can match only # when there is a joinable row, then use INNER. For example, in # rel_a__col=1 & rel_b__col=2, if either of the rels produce NULL # as join output, then the col=1 or col=2 can't match (as # NULL=anything is always false). # For the OR case, if all children voted for a join to be inner, # then we can use INNER for the join. For example: # (rel_a__col__icontains=Alex | rel_a__col__icontains=Russell) # then if rel_a doesn't produce any rows, the whole condition # can't match. Hence we can safely use INNER join. if self.effective_connector == AND or ( self.effective_connector == OR and votes == self.num_children ): to_demote.add(table) # Finally, what happens in cases where we have: # (rel_a__col=1|rel_b__col=2) & rel_a__col__gte=0 # Now, we first generate the OR clause, and promote joins for it # in the first if branch above. Both rel_a and rel_b are promoted # to LOUTER joins. After that we do the AND case. The OR case # voted no inner joins but the rel_a__col__gte=0 votes inner join # for rel_a. We demote it back to INNER join (in AND case a single # vote is enough). The demotion is OK, if rel_a doesn't produce # rows, then the rel_a__col__gte=0 clause can't be true, and thus # the whole clause must be false. So, it is safe to use INNER # join. # Note that in this example we could just as well have the __gte # clause and the OR clause swapped. Or we could replace the __gte # clause with an OR clause containing rel_a__col=1|rel_a__col=2, # and again we could safely demote to INNER. query.promote_joins(to_promote) query.demote_joins(to_demote) return to_demote
a479757d77ab8cf25c46a6a2af04a74e62401da045e31f981463e4802320037d
import operator from django.db.backends.base.features import BaseDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): empty_fetchmany_value = () allows_group_by_selected_pks = True related_fields_match_type = True # MySQL doesn't support sliced subqueries with IN/ALL/ANY/SOME. allow_sliced_subqueries_with_in = False has_select_for_update = True supports_forward_references = False supports_regex_backreferencing = False supports_date_lookup_using_string = False supports_timezones = False requires_explicit_null_ordering_when_grouping = True atomic_transactions = False can_clone_databases = True supports_comments = True supports_comments_inline = True supports_temporal_subtraction = True supports_slicing_ordering_in_compound = True supports_index_on_text_field = False supports_update_conflicts = True create_test_procedure_without_params_sql = """ CREATE PROCEDURE test_procedure () BEGIN DECLARE V_I INTEGER; SET V_I = 1; END; """ create_test_procedure_with_int_param_sql = """ CREATE PROCEDURE test_procedure (P_I INTEGER) BEGIN DECLARE V_I INTEGER; SET V_I = P_I; END; """ create_test_table_with_composite_primary_key = """ CREATE TABLE test_table_composite_pk ( column_1 INTEGER NOT NULL, column_2 INTEGER NOT NULL, PRIMARY KEY(column_1, column_2) ) """ # Neither MySQL nor MariaDB support partial indexes. supports_partial_indexes = False # COLLATE must be wrapped in parentheses because MySQL treats COLLATE as an # indexed expression. collate_as_index_expression = True supports_order_by_nulls_modifier = False order_by_nulls_first = True supports_logical_xor = True @cached_property def minimum_database_version(self): if self.connection.mysql_is_mariadb: return (10, 4) else: return (8,) @cached_property def test_collations(self): charset = "utf8" if ( self.connection.mysql_is_mariadb and self.connection.mysql_version >= (10, 6) ) or ( not self.connection.mysql_is_mariadb and self.connection.mysql_version >= (8, 0, 30) ): # utf8 is an alias for utf8mb3 in MariaDB 10.6+ and MySQL 8.0.30+. charset = "utf8mb3" return { "ci": f"{charset}_general_ci", "non_default": f"{charset}_esperanto_ci", "swedish_ci": f"{charset}_swedish_ci", } test_now_utc_template = "UTC_TIMESTAMP(6)" @cached_property def django_test_skips(self): skips = { "This doesn't work on MySQL.": { "db_functions.comparison.test_greatest.GreatestTests." "test_coalesce_workaround", "db_functions.comparison.test_least.LeastTests." "test_coalesce_workaround", }, "Running on MySQL requires utf8mb4 encoding (#18392).": { "model_fields.test_textfield.TextFieldTests.test_emoji", "model_fields.test_charfield.TestCharField.test_emoji", }, "MySQL doesn't support functional indexes on a function that " "returns JSON": { "schema.tests.SchemaTests.test_func_index_json_key_transform", }, "MySQL supports multiplying and dividing DurationFields by a " "scalar value but it's not implemented (#25287).": { "expressions.tests.FTimeDeltaTests.test_durationfield_multiply_divide", }, "UPDATE ... ORDER BY syntax on MySQL/MariaDB does not support ordering by" "related fields.": { "update.tests.AdvancedTests." "test_update_ordered_by_inline_m2m_annotation", "update.tests.AdvancedTests.test_update_ordered_by_m2m_annotation", "update.tests.AdvancedTests.test_update_ordered_by_m2m_annotation_desc", }, } if self.connection.mysql_is_mariadb and ( 10, 4, 3, ) < self.connection.mysql_version < (10, 5, 2): skips.update( { "https://jira.mariadb.org/browse/MDEV-19598": { "schema.tests.SchemaTests." "test_alter_not_unique_field_to_primary_key", }, } ) if self.connection.mysql_is_mariadb and ( 10, 4, 12, ) < self.connection.mysql_version < (10, 5): skips.update( { "https://jira.mariadb.org/browse/MDEV-22775": { "schema.tests.SchemaTests." "test_alter_pk_with_self_referential_field", }, } ) if not self.supports_explain_analyze: skips.update( { "MariaDB and MySQL >= 8.0.18 specific.": { "queries.test_explain.ExplainTests.test_mysql_analyze", }, } ) if "ONLY_FULL_GROUP_BY" in self.connection.sql_mode: skips.update( { "GROUP BY cannot contain nonaggregated column when " "ONLY_FULL_GROUP_BY mode is enabled on MySQL, see #34262.": { "aggregation.tests.AggregateTestCase." "test_group_by_nested_expression_with_params", }, } ) if self.connection.mysql_version < (8, 0, 31): skips.update( { "Nesting of UNIONs at the right-hand side is not supported on " "MySQL < 8.0.31": { "queries.test_qs_combinators.QuerySetSetOperationTests." "test_union_nested" }, } ) return skips @cached_property def _mysql_storage_engine(self): "Internal method used in Django tests. Don't rely on this from your code" return self.connection.mysql_server_data["default_storage_engine"] @cached_property def allows_auto_pk_0(self): """ Autoincrement primary key can be set to 0 if it doesn't generate new autoincrement values. """ return "NO_AUTO_VALUE_ON_ZERO" in self.connection.sql_mode @cached_property def update_can_self_select(self): return self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 3, 2, ) @cached_property def can_introspect_foreign_keys(self): "Confirm support for introspected foreign keys" return self._mysql_storage_engine != "MyISAM" @cached_property def introspected_field_types(self): return { **super().introspected_field_types, "BinaryField": "TextField", "BooleanField": "IntegerField", "DurationField": "BigIntegerField", "GenericIPAddressField": "CharField", } @cached_property def can_return_columns_from_insert(self): return self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 5, 0, ) can_return_rows_from_bulk_insert = property( operator.attrgetter("can_return_columns_from_insert") ) @cached_property def has_zoneinfo_database(self): return self.connection.mysql_server_data["has_zoneinfo_database"] @cached_property def is_sql_auto_is_null_enabled(self): return self.connection.mysql_server_data["sql_auto_is_null"] @cached_property def supports_over_clause(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 2) supports_frame_range_fixed_distance = property( operator.attrgetter("supports_over_clause") ) @cached_property def supports_column_check_constraints(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 16) supports_table_check_constraints = property( operator.attrgetter("supports_column_check_constraints") ) @cached_property def can_introspect_check_constraints(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 16) @cached_property def has_select_for_update_skip_locked(self): if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 6) return self.connection.mysql_version >= (8, 0, 1) @cached_property def has_select_for_update_nowait(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 1) @cached_property def has_select_for_update_of(self): return ( not self.connection.mysql_is_mariadb and self.connection.mysql_version >= (8, 0, 1) ) @cached_property def supports_explain_analyze(self): return self.connection.mysql_is_mariadb or self.connection.mysql_version >= ( 8, 0, 18, ) @cached_property def supported_explain_formats(self): # Alias MySQL's TRADITIONAL to TEXT for consistency with other # backends. formats = {"JSON", "TEXT", "TRADITIONAL"} if not self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 8, 0, 16, ): formats.add("TREE") return formats @cached_property def supports_transactions(self): """ All storage engines except MyISAM support transactions. """ return self._mysql_storage_engine != "MyISAM" uses_savepoints = property(operator.attrgetter("supports_transactions")) can_release_savepoints = property(operator.attrgetter("supports_transactions")) @cached_property def ignores_table_name_case(self): return self.connection.mysql_server_data["lower_case_table_names"] @cached_property def supports_default_in_lead_lag(self): # To be added in https://jira.mariadb.org/browse/MDEV-12981. return not self.connection.mysql_is_mariadb @cached_property def can_introspect_json_field(self): if self.connection.mysql_is_mariadb: return self.can_introspect_check_constraints return True @cached_property def supports_index_column_ordering(self): if self._mysql_storage_engine != "InnoDB": return False if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 8) return self.connection.mysql_version >= (8, 0, 1) @cached_property def supports_expression_indexes(self): return ( not self.connection.mysql_is_mariadb and self._mysql_storage_engine != "MyISAM" and self.connection.mysql_version >= (8, 0, 13) ) @cached_property def supports_select_intersection(self): is_mariadb = self.connection.mysql_is_mariadb return is_mariadb or self.connection.mysql_version >= (8, 0, 31) supports_select_difference = property( operator.attrgetter("supports_select_intersection") ) @cached_property def can_rename_index(self): if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 5, 2) return True
479fc3414917c8939772db6286d4fa7bee5e91937bb853e4dde62036e38be17f
import os import pathlib from django.core.exceptions import SuspiciousFileOperation def validate_file_name(name, allow_relative_path=False): # Remove potentially dangerous names if os.path.basename(name) in {"", ".", ".."}: raise SuspiciousFileOperation("Could not derive file name from '%s'" % name) if allow_relative_path: # Use PurePosixPath() because this branch is checked only in # FileField.generate_filename() where all file paths are expected to be # Unix style (with forward slashes). path = pathlib.PurePosixPath(name) if path.is_absolute() or ".." in path.parts: raise SuspiciousFileOperation( "Detected path traversal attempt in '%s'" % name ) elif name != os.path.basename(name): raise SuspiciousFileOperation("File name '%s' includes path elements" % name) return name class FileProxyMixin: """ A mixin class used to forward file methods to an underlying file object. The internal file object has to be called "file":: class FileProxy(FileProxyMixin): def __init__(self, file): self.file = file """ encoding = property(lambda self: self.file.encoding) fileno = property(lambda self: self.file.fileno) flush = property(lambda self: self.file.flush) isatty = property(lambda self: self.file.isatty) newlines = property(lambda self: self.file.newlines) read = property(lambda self: self.file.read) readinto = property(lambda self: self.file.readinto) readline = property(lambda self: self.file.readline) readlines = property(lambda self: self.file.readlines) seek = property(lambda self: self.file.seek) tell = property(lambda self: self.file.tell) truncate = property(lambda self: self.file.truncate) write = property(lambda self: self.file.write) writelines = property(lambda self: self.file.writelines) @property def closed(self): return not self.file or self.file.closed def readable(self): if self.closed: return False if hasattr(self.file, "readable"): return self.file.readable() return True def writable(self): if self.closed: return False if hasattr(self.file, "writable"): return self.file.writable() return "w" in getattr(self.file, "mode", "") def seekable(self): if self.closed: return False if hasattr(self.file, "seekable"): return self.file.seekable() return True def __iter__(self): return iter(self.file)
6aba7163b905da8542cd51506339edf071c97d32d35e2bd33cefbfd5d71e37a1
"""SMTP email backend class.""" import smtplib import ssl import threading from django.conf import settings from django.core.mail.backends.base import BaseEmailBackend from django.core.mail.message import sanitize_address from django.core.mail.utils import DNS_NAME from django.utils.functional import cached_property class EmailBackend(BaseEmailBackend): """ A wrapper that manages the SMTP network connection. """ def __init__( self, host=None, port=None, username=None, password=None, use_tls=None, fail_silently=False, use_ssl=None, timeout=None, ssl_keyfile=None, ssl_certfile=None, **kwargs, ): super().__init__(fail_silently=fail_silently) self.host = host or settings.EMAIL_HOST self.port = port or settings.EMAIL_PORT self.username = settings.EMAIL_HOST_USER if username is None else username self.password = settings.EMAIL_HOST_PASSWORD if password is None else password self.use_tls = settings.EMAIL_USE_TLS if use_tls is None else use_tls self.use_ssl = settings.EMAIL_USE_SSL if use_ssl is None else use_ssl self.timeout = settings.EMAIL_TIMEOUT if timeout is None else timeout self.ssl_keyfile = ( settings.EMAIL_SSL_KEYFILE if ssl_keyfile is None else ssl_keyfile ) self.ssl_certfile = ( settings.EMAIL_SSL_CERTFILE if ssl_certfile is None else ssl_certfile ) if self.use_ssl and self.use_tls: raise ValueError( "EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set " "one of those settings to True." ) self.connection = None self._lock = threading.RLock() @property def connection_class(self): return smtplib.SMTP_SSL if self.use_ssl else smtplib.SMTP @cached_property def ssl_context(self): if self.ssl_certfile or self.ssl_keyfile: ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT) ssl_context.load_cert_chain(self.ssl_certfile, self.ssl_keyfile) return ssl_context else: return ssl.create_default_context() def open(self): """ Ensure an open connection to the email server. Return whether or not a new connection was required (True or False) or None if an exception passed silently. """ if self.connection: # Nothing to do if the connection is already open. return False # If local_hostname is not specified, socket.getfqdn() gets used. # For performance, we use the cached FQDN for local_hostname. connection_params = {"local_hostname": DNS_NAME.get_fqdn()} if self.timeout is not None: connection_params["timeout"] = self.timeout if self.use_ssl: connection_params["context"] = self.ssl_context try: self.connection = self.connection_class( self.host, self.port, **connection_params ) # TLS/SSL are mutually exclusive, so only attempt TLS over # non-secure connections. if not self.use_ssl and self.use_tls: self.connection.starttls(context=self.ssl_context) if self.username and self.password: self.connection.login(self.username, self.password) return True except OSError: if not self.fail_silently: raise def close(self): """Close the connection to the email server.""" if self.connection is None: return try: try: self.connection.quit() except (ssl.SSLError, smtplib.SMTPServerDisconnected): # This happens when calling quit() on a TLS connection # sometimes, or when the connection was already disconnected # by the server. self.connection.close() except smtplib.SMTPException: if self.fail_silently: return raise finally: self.connection = None def send_messages(self, email_messages): """ Send one or more EmailMessage objects and return the number of email messages sent. """ if not email_messages: return 0 with self._lock: new_conn_created = self.open() if not self.connection or new_conn_created is None: # We failed silently on open(). # Trying to send would be pointless. return 0 num_sent = 0 try: for message in email_messages: sent = self._send(message) if sent: num_sent += 1 finally: if new_conn_created: self.close() return num_sent def _send(self, email_message): """A helper method that does the actual sending.""" if not email_message.recipients(): return False encoding = email_message.encoding or settings.DEFAULT_CHARSET from_email = sanitize_address(email_message.from_email, encoding) recipients = [ sanitize_address(addr, encoding) for addr in email_message.recipients() ] message = email_message.message() try: self.connection.sendmail( from_email, recipients, message.as_bytes(linesep="\r\n") ) except smtplib.SMTPException: if not self.fail_silently: raise return False return True
10cef088cf4529504edc5960c52fc4ccc35cfe8da787be8f8d1899d39ccdb6cb
import datetime import decimal import json from collections import defaultdict from functools import reduce from operator import or_ from django.core.exceptions import FieldDoesNotExist from django.db import models, router from django.db.models.constants import LOOKUP_SEP from django.db.models.deletion import Collector from django.forms.utils import pretty_name from django.urls import NoReverseMatch, reverse from django.utils import formats, timezone from django.utils.hashable import make_hashable from django.utils.html import format_html from django.utils.regex_helper import _lazy_re_compile from django.utils.text import capfirst from django.utils.translation import ngettext from django.utils.translation import override as translation_override QUOTE_MAP = {i: "_%02X" % i for i in b'":/_#?;@&=+$,"[]<>%\n\\'} UNQUOTE_MAP = {v: chr(k) for k, v in QUOTE_MAP.items()} UNQUOTE_RE = _lazy_re_compile("_(?:%s)" % "|".join([x[1:] for x in UNQUOTE_MAP])) class FieldIsAForeignKeyColumnName(Exception): """A field is a foreign key attname, i.e. <FK>_id.""" pass def lookup_spawns_duplicates(opts, lookup_path): """ Return True if the given lookup path spawns duplicates. """ lookup_fields = lookup_path.split(LOOKUP_SEP) # Go through the fields (following all relations) and look for an m2m. for field_name in lookup_fields: if field_name == "pk": field_name = opts.pk.name try: field = opts.get_field(field_name) except FieldDoesNotExist: # Ignore query lookups. continue else: if hasattr(field, "path_infos"): # This field is a relation; update opts to follow the relation. path_info = field.path_infos opts = path_info[-1].to_opts if any(path.m2m for path in path_info): # This field is a m2m relation so duplicates must be # handled. return True return False def get_last_value_from_parameters(parameters, key): value = parameters.get(key) return value[-1] if isinstance(value, list) else value def prepare_lookup_value(key, value, separator=","): """ Return a lookup value prepared to be used in queryset filtering. """ if isinstance(value, list): return [prepare_lookup_value(key, v, separator=separator) for v in value] # if key ends with __in, split parameter into separate values if key.endswith("__in"): value = value.split(separator) # if key ends with __isnull, special case '' and the string literals 'false' and '0' elif key.endswith("__isnull"): value = value.lower() not in ("", "false", "0") return value def build_q_object_from_lookup_parameters(parameters): q_object = models.Q() for param, param_item_list in parameters.items(): q_object &= reduce(or_, (models.Q((param, item)) for item in param_item_list)) return q_object def quote(s): """ Ensure that primary key values do not confuse the admin URLs by escaping any '/', '_' and ':' and similarly problematic characters. Similar to urllib.parse.quote(), except that the quoting is slightly different so that it doesn't get automatically unquoted by the web browser. """ return s.translate(QUOTE_MAP) if isinstance(s, str) else s def unquote(s): """Undo the effects of quote().""" return UNQUOTE_RE.sub(lambda m: UNQUOTE_MAP[m[0]], s) def flatten(fields): """ Return a list which is a single level of flattening of the original list. """ flat = [] for field in fields: if isinstance(field, (list, tuple)): flat.extend(field) else: flat.append(field) return flat def flatten_fieldsets(fieldsets): """Return a list of field names from an admin fieldsets structure.""" field_names = [] for name, opts in fieldsets: field_names.extend(flatten(opts["fields"])) return field_names def get_deleted_objects(objs, request, admin_site): """ Find all objects related to ``objs`` that should also be deleted. ``objs`` must be a homogeneous iterable of objects (e.g. a QuerySet). Return a nested list of strings suitable for display in the template with the ``unordered_list`` filter. """ try: obj = objs[0] except IndexError: return [], {}, set(), [] else: using = router.db_for_write(obj._meta.model) collector = NestedObjects(using=using, origin=objs) collector.collect(objs) perms_needed = set() def format_callback(obj): model = obj.__class__ has_admin = model in admin_site._registry opts = obj._meta no_edit_link = "%s: %s" % (capfirst(opts.verbose_name), obj) if has_admin: if not admin_site._registry[model].has_delete_permission(request, obj): perms_needed.add(opts.verbose_name) try: admin_url = reverse( "%s:%s_%s_change" % (admin_site.name, opts.app_label, opts.model_name), None, (quote(obj.pk),), ) except NoReverseMatch: # Change url doesn't exist -- don't display link to edit return no_edit_link # Display a link to the admin page. return format_html( '{}: <a href="{}">{}</a>', capfirst(opts.verbose_name), admin_url, obj ) else: # Don't display link to edit, because it either has no # admin or is edited inline. return no_edit_link to_delete = collector.nested(format_callback) protected = [format_callback(obj) for obj in collector.protected] model_count = { model._meta.verbose_name_plural: len(objs) for model, objs in collector.model_objs.items() } return to_delete, model_count, perms_needed, protected class NestedObjects(Collector): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.edges = {} # {from_instance: [to_instances]} self.protected = set() self.model_objs = defaultdict(set) def add_edge(self, source, target): self.edges.setdefault(source, []).append(target) def collect(self, objs, source=None, source_attr=None, **kwargs): for obj in objs: if source_attr and not source_attr.endswith("+"): related_name = source_attr % { "class": source._meta.model_name, "app_label": source._meta.app_label, } self.add_edge(getattr(obj, related_name), obj) else: self.add_edge(None, obj) self.model_objs[obj._meta.model].add(obj) try: return super().collect(objs, source_attr=source_attr, **kwargs) except models.ProtectedError as e: self.protected.update(e.protected_objects) except models.RestrictedError as e: self.protected.update(e.restricted_objects) def related_objects(self, related_model, related_fields, objs): qs = super().related_objects(related_model, related_fields, objs) return qs.select_related( *[related_field.name for related_field in related_fields] ) def _nested(self, obj, seen, format_callback): if obj in seen: return [] seen.add(obj) children = [] for child in self.edges.get(obj, ()): children.extend(self._nested(child, seen, format_callback)) if format_callback: ret = [format_callback(obj)] else: ret = [obj] if children: ret.append(children) return ret def nested(self, format_callback=None): """ Return the graph as a nested list. """ seen = set() roots = [] for root in self.edges.get(None, ()): roots.extend(self._nested(root, seen, format_callback)) return roots def can_fast_delete(self, *args, **kwargs): """ We always want to load the objects into memory so that we can display them to the user in confirm page. """ return False def model_format_dict(obj): """ Return a `dict` with keys 'verbose_name' and 'verbose_name_plural', typically for use with string formatting. `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance. """ if isinstance(obj, (models.Model, models.base.ModelBase)): opts = obj._meta elif isinstance(obj, models.query.QuerySet): opts = obj.model._meta else: opts = obj return { "verbose_name": opts.verbose_name, "verbose_name_plural": opts.verbose_name_plural, } def model_ngettext(obj, n=None): """ Return the appropriate `verbose_name` or `verbose_name_plural` value for `obj` depending on the count `n`. `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance. If `obj` is a `QuerySet` instance, `n` is optional and the length of the `QuerySet` is used. """ if isinstance(obj, models.query.QuerySet): if n is None: n = obj.count() obj = obj.model d = model_format_dict(obj) singular, plural = d["verbose_name"], d["verbose_name_plural"] return ngettext(singular, plural, n or 0) def lookup_field(name, obj, model_admin=None): opts = obj._meta try: f = _get_non_gfk_field(opts, name) except (FieldDoesNotExist, FieldIsAForeignKeyColumnName): # For non-field values, the value is either a method, property or # returned via a callable. if callable(name): attr = name value = attr(obj) elif hasattr(model_admin, name) and name != "__str__": attr = getattr(model_admin, name) value = attr(obj) else: attr = getattr(obj, name) if callable(attr): value = attr() else: value = attr f = None else: attr = None value = getattr(obj, name) return f, attr, value def _get_non_gfk_field(opts, name): """ For historical reasons, the admin app relies on GenericForeignKeys as being "not found" by get_field(). This could likely be cleaned up. Reverse relations should also be excluded as these aren't attributes of the model (rather something like `foo_set`). """ field = opts.get_field(name) if ( field.is_relation and # Generic foreign keys OR reverse relations ((field.many_to_one and not field.related_model) or field.one_to_many) ): raise FieldDoesNotExist() # Avoid coercing <FK>_id fields to FK if ( field.is_relation and not field.many_to_many and hasattr(field, "attname") and field.attname == name ): raise FieldIsAForeignKeyColumnName() return field def label_for_field(name, model, model_admin=None, return_attr=False, form=None): """ Return a sensible label for a field name. The name can be a callable, property (but not created with @property decorator), or the name of an object's attribute, as well as a model field. If return_attr is True, also return the resolved attribute (which could be a callable). This will be None if (and only if) the name refers to a field. """ attr = None try: field = _get_non_gfk_field(model._meta, name) try: label = field.verbose_name except AttributeError: # field is likely a ForeignObjectRel label = field.related_model._meta.verbose_name except FieldDoesNotExist: if name == "__str__": label = str(model._meta.verbose_name) attr = str else: if callable(name): attr = name elif hasattr(model_admin, name): attr = getattr(model_admin, name) elif hasattr(model, name): attr = getattr(model, name) elif form and name in form.fields: attr = form.fields[name] else: message = "Unable to lookup '%s' on %s" % ( name, model._meta.object_name, ) if model_admin: message += " or %s" % model_admin.__class__.__name__ if form: message += " or %s" % form.__class__.__name__ raise AttributeError(message) if hasattr(attr, "short_description"): label = attr.short_description elif ( isinstance(attr, property) and hasattr(attr, "fget") and hasattr(attr.fget, "short_description") ): label = attr.fget.short_description elif callable(attr): if attr.__name__ == "<lambda>": label = "--" else: label = pretty_name(attr.__name__) else: label = pretty_name(name) except FieldIsAForeignKeyColumnName: label = pretty_name(name) attr = name if return_attr: return (label, attr) else: return label def help_text_for_field(name, model): help_text = "" try: field = _get_non_gfk_field(model._meta, name) except (FieldDoesNotExist, FieldIsAForeignKeyColumnName): pass else: if hasattr(field, "help_text"): help_text = field.help_text return help_text def display_for_field(value, field, empty_value_display): from django.contrib.admin.templatetags.admin_list import _boolean_icon if getattr(field, "flatchoices", None): try: return dict(field.flatchoices).get(value, empty_value_display) except TypeError: # Allow list-like choices. flatchoices = make_hashable(field.flatchoices) value = make_hashable(value) return dict(flatchoices).get(value, empty_value_display) # BooleanField needs special-case null-handling, so it comes before the # general null test. elif isinstance(field, models.BooleanField): return _boolean_icon(value) elif value is None: return empty_value_display elif isinstance(field, models.DateTimeField): return formats.localize(timezone.template_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, (models.IntegerField, models.FloatField)): 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 json.dumps(value, ensure_ascii=False, cls=field.encoder) except TypeError: return display_for_value(value, empty_value_display) else: return display_for_value(value, empty_value_display) def display_for_value(value, empty_value_display, boolean=False): from django.contrib.admin.templatetags.admin_list import _boolean_icon if boolean: return _boolean_icon(value) elif value is None: return empty_value_display elif isinstance(value, bool): return str(value) elif isinstance(value, datetime.datetime): return formats.localize(timezone.template_localtime(value)) elif isinstance(value, (datetime.date, datetime.time)): return formats.localize(value) elif isinstance(value, (int, decimal.Decimal, float)): return formats.number_format(value) elif isinstance(value, (list, tuple)): return ", ".join(str(v) for v in value) else: return str(value) class NotRelationField(Exception): pass def get_model_from_relation(field): if hasattr(field, "path_infos"): return field.path_infos[-1].to_opts.model else: raise NotRelationField def reverse_field_path(model, path): """Create a reversed field path. E.g. Given (Order, "user__groups"), return (Group, "user__order"). Final field must be a related model, not a data field. """ reversed_path = [] parent = model pieces = path.split(LOOKUP_SEP) for piece in pieces: field = parent._meta.get_field(piece) # skip trailing data field if extant: if len(reversed_path) == len(pieces) - 1: # final iteration try: get_model_from_relation(field) except NotRelationField: break # Field should point to another model if field.is_relation and not (field.auto_created and not field.concrete): related_name = field.related_query_name() parent = field.remote_field.model else: related_name = field.field.name parent = field.related_model reversed_path.insert(0, related_name) return (parent, LOOKUP_SEP.join(reversed_path)) def get_fields_from_path(model, path): """Return list of Fields given path relative to model. e.g. (ModelX, "user__groups__name") -> [ <django.db.models.fields.related.ForeignKey object at 0x...>, <django.db.models.fields.related.ManyToManyField object at 0x...>, <django.db.models.fields.CharField object at 0x...>, ] """ pieces = path.split(LOOKUP_SEP) fields = [] for piece in pieces: if fields: parent = get_model_from_relation(fields[-1]) else: parent = model fields.append(parent._meta.get_field(piece)) return fields def construct_change_message(form, formsets, add): """ Construct a JSON structure describing changes from a changed object. Translations are deactivated so that strings are stored untranslated. Translation happens later on LogEntry access. """ # Evaluating `form.changed_data` prior to disabling translations is required # to avoid fields affected by localization from being included incorrectly, # e.g. where date formats differ such as MM/DD/YYYY vs DD/MM/YYYY. changed_data = form.changed_data with translation_override(None): # Deactivate translations while fetching verbose_name for form # field labels and using `field_name`, if verbose_name is not provided. # Translations will happen later on LogEntry access. changed_field_labels = _get_changed_field_labels_from_form(form, changed_data) change_message = [] if add: change_message.append({"added": {}}) elif form.changed_data: change_message.append({"changed": {"fields": changed_field_labels}}) if formsets: with translation_override(None): for formset in formsets: for added_object in formset.new_objects: change_message.append( { "added": { "name": str(added_object._meta.verbose_name), "object": str(added_object), } } ) for changed_object, changed_fields in formset.changed_objects: change_message.append( { "changed": { "name": str(changed_object._meta.verbose_name), "object": str(changed_object), "fields": _get_changed_field_labels_from_form( formset.forms[0], changed_fields ), } } ) for deleted_object in formset.deleted_objects: change_message.append( { "deleted": { "name": str(deleted_object._meta.verbose_name), "object": str(deleted_object), } } ) return change_message def _get_changed_field_labels_from_form(form, changed_data): changed_field_labels = [] for field_name in changed_data: try: verbose_field_name = form.fields[field_name].label or field_name except KeyError: verbose_field_name = field_name changed_field_labels.append(str(verbose_field_name)) return changed_field_labels
8456317b1f217dca49291dd82d87d2706280f1fe0d1c0750b666bf9e2063fabb
""" This encapsulates the logic for displaying filters in the Django admin. Filters are specified in models with the "list_filter" option. Each filter subclass knows how to display a filter for a field that passes a certain test -- e.g. being a DateField or ForeignKey. """ import datetime from django.contrib.admin.options import IncorrectLookupParameters from django.contrib.admin.utils import ( build_q_object_from_lookup_parameters, get_last_value_from_parameters, get_model_from_relation, prepare_lookup_value, reverse_field_path, ) from django.core.exceptions import ImproperlyConfigured, ValidationError from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ class ListFilter: title = None # Human-readable title to appear in the right sidebar. template = "admin/filter.html" def __init__(self, request, params, model, model_admin): self.request = request # This dictionary will eventually contain the request's query string # parameters actually used by this filter. self.used_parameters = {} if self.title is None: raise ImproperlyConfigured( "The list filter '%s' does not specify a 'title'." % self.__class__.__name__ ) def has_output(self): """ Return True if some choices would be output for this filter. """ raise NotImplementedError( "subclasses of ListFilter must provide a has_output() method" ) def choices(self, changelist): """ Return choices ready to be output in the template. `changelist` is the ChangeList to be displayed. """ raise NotImplementedError( "subclasses of ListFilter must provide a choices() method" ) def queryset(self, request, queryset): """ Return the filtered queryset. """ raise NotImplementedError( "subclasses of ListFilter must provide a queryset() method" ) def expected_parameters(self): """ Return the list of parameter names that are expected from the request's query string and that will be used by this filter. """ raise NotImplementedError( "subclasses of ListFilter must provide an expected_parameters() method" ) class FacetsMixin: def get_facet_counts(self, pk_attname, filtered_qs): raise NotImplementedError( "subclasses of FacetsMixin must provide a get_facet_counts() method." ) def get_facet_queryset(self, changelist): filtered_qs = changelist.get_queryset( self.request, exclude_parameters=self.expected_parameters() ) return filtered_qs.aggregate( **self.get_facet_counts(changelist.pk_attname, filtered_qs) ) class SimpleListFilter(FacetsMixin, ListFilter): # The parameter that should be used in the query string for that filter. parameter_name = None def __init__(self, request, params, model, model_admin): super().__init__(request, params, model, model_admin) if self.parameter_name is None: raise ImproperlyConfigured( "The list filter '%s' does not specify a 'parameter_name'." % self.__class__.__name__ ) if self.parameter_name in params: value = params.pop(self.parameter_name) self.used_parameters[self.parameter_name] = value[-1] lookup_choices = self.lookups(request, model_admin) if lookup_choices is None: lookup_choices = () self.lookup_choices = list(lookup_choices) def has_output(self): return len(self.lookup_choices) > 0 def value(self): """ Return the value (in string format) provided in the request's query string for this filter, if any, or None if the value wasn't provided. """ return self.used_parameters.get(self.parameter_name) def lookups(self, request, model_admin): """ Must be overridden to return a list of tuples (value, verbose value) """ raise NotImplementedError( "The SimpleListFilter.lookups() method must be overridden to " "return a list of tuples (value, verbose value)." ) def expected_parameters(self): return [self.parameter_name] def get_facet_counts(self, pk_attname, filtered_qs): original_value = self.used_parameters.get(self.parameter_name) counts = {} for i, choice in enumerate(self.lookup_choices): self.used_parameters[self.parameter_name] = choice[0] lookup_qs = self.queryset(self.request, filtered_qs) if lookup_qs is not None: counts[f"{i}__c"] = models.Count( pk_attname, filter=lookup_qs.query.where, ) self.used_parameters[self.parameter_name] = original_value return counts def choices(self, changelist): add_facets = changelist.add_facets facet_counts = self.get_facet_queryset(changelist) if add_facets else None yield { "selected": self.value() is None, "query_string": changelist.get_query_string(remove=[self.parameter_name]), "display": _("All"), } for i, (lookup, title) in enumerate(self.lookup_choices): if add_facets: if (count := facet_counts.get(f"{i}__c", -1)) != -1: title = f"{title} ({count})" else: title = f"{title} (-)" yield { "selected": self.value() == str(lookup), "query_string": changelist.get_query_string( {self.parameter_name: lookup} ), "display": title, } class FieldListFilter(FacetsMixin, ListFilter): _field_list_filters = [] _take_priority_index = 0 list_separator = "," def __init__(self, field, request, params, model, model_admin, field_path): self.field = field self.field_path = field_path self.title = getattr(field, "verbose_name", field_path) super().__init__(request, params, model, model_admin) for p in self.expected_parameters(): if p in params: value = params.pop(p) self.used_parameters[p] = prepare_lookup_value( p, value, self.list_separator ) def has_output(self): return True def queryset(self, request, queryset): try: q_object = build_q_object_from_lookup_parameters(self.used_parameters) return queryset.filter(q_object) except (ValueError, ValidationError) as e: # Fields may raise a ValueError or ValidationError when converting # the parameters to the correct type. raise IncorrectLookupParameters(e) @classmethod def register(cls, test, list_filter_class, take_priority=False): if take_priority: # This is to allow overriding the default filters for certain types # of fields with some custom filters. The first found in the list # is used in priority. cls._field_list_filters.insert( cls._take_priority_index, (test, list_filter_class) ) cls._take_priority_index += 1 else: cls._field_list_filters.append((test, list_filter_class)) @classmethod def create(cls, field, request, params, model, model_admin, field_path): for test, list_filter_class in cls._field_list_filters: if test(field): return list_filter_class( field, request, params, model, model_admin, field_path=field_path ) class RelatedFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): other_model = get_model_from_relation(field) self.lookup_kwarg = "%s__%s__exact" % (field_path, field.target_field.name) self.lookup_kwarg_isnull = "%s__isnull" % field_path self.lookup_val = params.get(self.lookup_kwarg) self.lookup_val_isnull = get_last_value_from_parameters( params, self.lookup_kwarg_isnull ) super().__init__(field, request, params, model, model_admin, field_path) self.lookup_choices = self.field_choices(field, request, model_admin) if hasattr(field, "verbose_name"): self.lookup_title = field.verbose_name else: self.lookup_title = other_model._meta.verbose_name self.title = self.lookup_title self.empty_value_display = model_admin.get_empty_value_display() @property def include_empty_choice(self): """ Return True if a "(None)" choice should be included, which filters out everything except empty relationships. """ return self.field.null or (self.field.is_relation and self.field.many_to_many) def has_output(self): if self.include_empty_choice: extra = 1 else: extra = 0 return len(self.lookup_choices) + extra > 1 def expected_parameters(self): return [self.lookup_kwarg, self.lookup_kwarg_isnull] def field_admin_ordering(self, field, request, model_admin): """ Return the model admin's ordering for related field, if provided. """ related_admin = model_admin.admin_site._registry.get(field.remote_field.model) if related_admin is not None: return related_admin.get_ordering(request) return () def field_choices(self, field, request, model_admin): ordering = self.field_admin_ordering(field, request, model_admin) return field.get_choices(include_blank=False, ordering=ordering) def get_facet_counts(self, pk_attname, filtered_qs): counts = { f"{pk_val}__c": models.Count( pk_attname, filter=models.Q(**{self.lookup_kwarg: pk_val}) ) for pk_val, _ in self.lookup_choices } if self.include_empty_choice: counts["__c"] = models.Count( pk_attname, filter=models.Q(**{self.lookup_kwarg_isnull: True}) ) return counts def choices(self, changelist): add_facets = changelist.add_facets facet_counts = self.get_facet_queryset(changelist) if add_facets else None yield { "selected": self.lookup_val is None and not self.lookup_val_isnull, "query_string": changelist.get_query_string( remove=[self.lookup_kwarg, self.lookup_kwarg_isnull] ), "display": _("All"), } count = None for pk_val, val in self.lookup_choices: if add_facets: count = facet_counts[f"{pk_val}__c"] val = f"{val} ({count})" yield { "selected": self.lookup_val is not None and str(pk_val) in self.lookup_val, "query_string": changelist.get_query_string( {self.lookup_kwarg: pk_val}, [self.lookup_kwarg_isnull] ), "display": val, } empty_title = self.empty_value_display if self.include_empty_choice: if add_facets: count = facet_counts["__c"] empty_title = f"{empty_title} ({count})" yield { "selected": bool(self.lookup_val_isnull), "query_string": changelist.get_query_string( {self.lookup_kwarg_isnull: "True"}, [self.lookup_kwarg] ), "display": empty_title, } FieldListFilter.register(lambda f: f.remote_field, RelatedFieldListFilter) class BooleanFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): self.lookup_kwarg = "%s__exact" % field_path self.lookup_kwarg2 = "%s__isnull" % field_path self.lookup_val = get_last_value_from_parameters(params, self.lookup_kwarg) self.lookup_val2 = get_last_value_from_parameters(params, self.lookup_kwarg2) super().__init__(field, request, params, model, model_admin, field_path) if ( self.used_parameters and self.lookup_kwarg in self.used_parameters and self.used_parameters[self.lookup_kwarg] in ("1", "0") ): self.used_parameters[self.lookup_kwarg] = bool( int(self.used_parameters[self.lookup_kwarg]) ) def expected_parameters(self): return [self.lookup_kwarg, self.lookup_kwarg2] def get_facet_counts(self, pk_attname, filtered_qs): return { "true__c": models.Count( pk_attname, filter=models.Q(**{self.field_path: True}) ), "false__c": models.Count( pk_attname, filter=models.Q(**{self.field_path: False}) ), "null__c": models.Count( pk_attname, filter=models.Q(**{self.lookup_kwarg2: True}) ), } def choices(self, changelist): field_choices = dict(self.field.flatchoices) add_facets = changelist.add_facets facet_counts = self.get_facet_queryset(changelist) if add_facets else None for lookup, title, count_field in ( (None, _("All"), None), ("1", field_choices.get(True, _("Yes")), "true__c"), ("0", field_choices.get(False, _("No")), "false__c"), ): if add_facets: if count_field is not None: count = facet_counts[count_field] title = f"{title} ({count})" yield { "selected": self.lookup_val == lookup and not self.lookup_val2, "query_string": changelist.get_query_string( {self.lookup_kwarg: lookup}, [self.lookup_kwarg2] ), "display": title, } if self.field.null: display = field_choices.get(None, _("Unknown")) if add_facets: count = facet_counts["null__c"] display = f"{display} ({count})" yield { "selected": self.lookup_val2 == "True", "query_string": changelist.get_query_string( {self.lookup_kwarg2: "True"}, [self.lookup_kwarg] ), "display": display, } FieldListFilter.register( lambda f: isinstance(f, models.BooleanField), BooleanFieldListFilter ) class ChoicesFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): self.lookup_kwarg = "%s__exact" % field_path self.lookup_kwarg_isnull = "%s__isnull" % field_path self.lookup_val = params.get(self.lookup_kwarg) self.lookup_val_isnull = get_last_value_from_parameters( params, self.lookup_kwarg_isnull ) super().__init__(field, request, params, model, model_admin, field_path) def expected_parameters(self): return [self.lookup_kwarg, self.lookup_kwarg_isnull] def get_facet_counts(self, pk_attname, filtered_qs): return { f"{i}__c": models.Count( pk_attname, filter=models.Q( (self.lookup_kwarg, value) if value is not None else (self.lookup_kwarg_isnull, True) ), ) for i, (value, _) in enumerate(self.field.flatchoices) } def choices(self, changelist): add_facets = changelist.add_facets facet_counts = self.get_facet_queryset(changelist) if add_facets else None yield { "selected": self.lookup_val is None, "query_string": changelist.get_query_string( remove=[self.lookup_kwarg, self.lookup_kwarg_isnull] ), "display": _("All"), } none_title = "" for i, (lookup, title) in enumerate(self.field.flatchoices): if add_facets: count = facet_counts[f"{i}__c"] title = f"{title} ({count})" if lookup is None: none_title = title continue yield { "selected": self.lookup_val is not None and str(lookup) in self.lookup_val, "query_string": changelist.get_query_string( {self.lookup_kwarg: lookup}, [self.lookup_kwarg_isnull] ), "display": title, } if none_title: yield { "selected": bool(self.lookup_val_isnull), "query_string": changelist.get_query_string( {self.lookup_kwarg_isnull: "True"}, [self.lookup_kwarg] ), "display": none_title, } FieldListFilter.register(lambda f: bool(f.choices), ChoicesFieldListFilter) class DateFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): self.field_generic = "%s__" % field_path self.date_params = { k: v[-1] for k, v in params.items() if k.startswith(self.field_generic) } now = timezone.now() # When time zone support is enabled, convert "now" to the user's time # zone so Django's definition of "Today" matches what the user expects. if timezone.is_aware(now): now = timezone.localtime(now) if isinstance(field, models.DateTimeField): today = now.replace(hour=0, minute=0, second=0, microsecond=0) else: # field is a models.DateField today = now.date() tomorrow = today + datetime.timedelta(days=1) if today.month == 12: next_month = today.replace(year=today.year + 1, month=1, day=1) else: next_month = today.replace(month=today.month + 1, day=1) next_year = today.replace(year=today.year + 1, month=1, day=1) self.lookup_kwarg_since = "%s__gte" % field_path self.lookup_kwarg_until = "%s__lt" % field_path self.links = ( (_("Any date"), {}), ( _("Today"), { self.lookup_kwarg_since: today, self.lookup_kwarg_until: tomorrow, }, ), ( _("Past 7 days"), { self.lookup_kwarg_since: today - datetime.timedelta(days=7), self.lookup_kwarg_until: tomorrow, }, ), ( _("This month"), { self.lookup_kwarg_since: today.replace(day=1), self.lookup_kwarg_until: next_month, }, ), ( _("This year"), { self.lookup_kwarg_since: today.replace(month=1, day=1), self.lookup_kwarg_until: next_year, }, ), ) if field.null: self.lookup_kwarg_isnull = "%s__isnull" % field_path self.links += ( (_("No date"), {self.field_generic + "isnull": True}), (_("Has date"), {self.field_generic + "isnull": False}), ) super().__init__(field, request, params, model, model_admin, field_path) def expected_parameters(self): params = [self.lookup_kwarg_since, self.lookup_kwarg_until] if self.field.null: params.append(self.lookup_kwarg_isnull) return params def get_facet_counts(self, pk_attname, filtered_qs): return { f"{i}__c": models.Count(pk_attname, filter=models.Q(**param_dict)) for i, (_, param_dict) in enumerate(self.links) } def choices(self, changelist): add_facets = changelist.add_facets facet_counts = self.get_facet_queryset(changelist) if add_facets else None for i, (title, param_dict) in enumerate(self.links): param_dict_str = {key: str(value) for key, value in param_dict.items()} if add_facets: count = facet_counts[f"{i}__c"] title = f"{title} ({count})" yield { "selected": self.date_params == param_dict_str, "query_string": changelist.get_query_string( param_dict_str, [self.field_generic] ), "display": title, } FieldListFilter.register(lambda f: isinstance(f, models.DateField), DateFieldListFilter) # This should be registered last, because it's a last resort. For example, # if a field is eligible to use the BooleanFieldListFilter, that'd be much # more appropriate, and the AllValuesFieldListFilter won't get used for it. class AllValuesFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): self.lookup_kwarg = field_path self.lookup_kwarg_isnull = "%s__isnull" % field_path self.lookup_val = params.get(self.lookup_kwarg) self.lookup_val_isnull = get_last_value_from_parameters( params, self.lookup_kwarg_isnull ) self.empty_value_display = model_admin.get_empty_value_display() parent_model, reverse_path = reverse_field_path(model, field_path) # Obey parent ModelAdmin queryset when deciding which options to show if model == parent_model: queryset = model_admin.get_queryset(request) else: queryset = parent_model._default_manager.all() self.lookup_choices = ( queryset.distinct().order_by(field.name).values_list(field.name, flat=True) ) super().__init__(field, request, params, model, model_admin, field_path) def expected_parameters(self): return [self.lookup_kwarg, self.lookup_kwarg_isnull] def get_facet_counts(self, pk_attname, filtered_qs): return { f"{i}__c": models.Count( pk_attname, filter=models.Q( (self.lookup_kwarg, value) if value is not None else (self.lookup_kwarg_isnull, True) ), ) for i, value in enumerate(self.lookup_choices) } def choices(self, changelist): add_facets = changelist.add_facets facet_counts = self.get_facet_queryset(changelist) if add_facets else None yield { "selected": self.lookup_val is None and self.lookup_val_isnull is None, "query_string": changelist.get_query_string( remove=[self.lookup_kwarg, self.lookup_kwarg_isnull] ), "display": _("All"), } include_none = False count = None empty_title = self.empty_value_display for i, val in enumerate(self.lookup_choices): if add_facets: count = facet_counts[f"{i}__c"] if val is None: include_none = True empty_title = f"{empty_title} ({count})" if add_facets else empty_title continue val = str(val) yield { "selected": self.lookup_val is not None and val in self.lookup_val, "query_string": changelist.get_query_string( {self.lookup_kwarg: val}, [self.lookup_kwarg_isnull] ), "display": f"{val} ({count})" if add_facets else val, } if include_none: yield { "selected": bool(self.lookup_val_isnull), "query_string": changelist.get_query_string( {self.lookup_kwarg_isnull: "True"}, [self.lookup_kwarg] ), "display": empty_title, } FieldListFilter.register(lambda f: True, AllValuesFieldListFilter) class RelatedOnlyFieldListFilter(RelatedFieldListFilter): def field_choices(self, field, request, model_admin): pk_qs = ( model_admin.get_queryset(request) .distinct() .values_list("%s__pk" % self.field_path, flat=True) ) ordering = self.field_admin_ordering(field, request, model_admin) return field.get_choices( include_blank=False, limit_choices_to={"pk__in": pk_qs}, ordering=ordering ) class EmptyFieldListFilter(FieldListFilter): def __init__(self, field, request, params, model, model_admin, field_path): if not field.empty_strings_allowed and not field.null: raise ImproperlyConfigured( "The list filter '%s' cannot be used with field '%s' which " "doesn't allow empty strings and nulls." % ( self.__class__.__name__, field.name, ) ) self.lookup_kwarg = "%s__isempty" % field_path self.lookup_val = get_last_value_from_parameters(params, self.lookup_kwarg) super().__init__(field, request, params, model, model_admin, field_path) def get_lookup_condition(self): lookup_conditions = [] if self.field.empty_strings_allowed: lookup_conditions.append((self.field_path, "")) if self.field.null: lookup_conditions.append((f"{self.field_path}__isnull", True)) return models.Q.create(lookup_conditions, connector=models.Q.OR) def queryset(self, request, queryset): if self.lookup_kwarg not in self.used_parameters: return queryset if self.lookup_val not in ("0", "1"): raise IncorrectLookupParameters lookup_condition = self.get_lookup_condition() if self.lookup_val == "1": return queryset.filter(lookup_condition) return queryset.exclude(lookup_condition) def expected_parameters(self): return [self.lookup_kwarg] def get_facet_counts(self, pk_attname, filtered_qs): lookup_condition = self.get_lookup_condition() return { "empty__c": models.Count(pk_attname, filter=lookup_condition), "not_empty__c": models.Count(pk_attname, filter=~lookup_condition), } def choices(self, changelist): add_facets = changelist.add_facets facet_counts = self.get_facet_queryset(changelist) if add_facets else None for lookup, title, count_field in ( (None, _("All"), None), ("1", _("Empty"), "empty__c"), ("0", _("Not empty"), "not_empty__c"), ): if add_facets: if count_field is not None: count = facet_counts[count_field] title = f"{title} ({count})" yield { "selected": self.lookup_val == lookup, "query_string": changelist.get_query_string( {self.lookup_kwarg: lookup} ), "display": title, }
0de0db5ef214792b3489c96ce1ed47437cbeebe6a08cefdcd8ee6e7e44a7ba5b
from urllib.parse import urlparse from urllib.request import url2pathname from asgiref.sync import sync_to_async from django.conf import settings from django.contrib.staticfiles import utils from django.contrib.staticfiles.views import serve from django.core.handlers.asgi import ASGIHandler from django.core.handlers.exception import response_for_exception from django.core.handlers.wsgi import WSGIHandler, get_path_info from django.http import Http404 class StaticFilesHandlerMixin: """ Common methods used by WSGI and ASGI handlers. """ # May be used to differentiate between handler types (e.g. in a # request_finished signal) handles_files = True def load_middleware(self): # Middleware are already loaded for self.application; no need to reload # them for self. pass def get_base_url(self): utils.check_settings() return settings.STATIC_URL def _should_handle(self, path): """ Check if the path should be handled. Ignore the path if: * the host is provided as part of the base_url * the request's path isn't under the media path (or equal) """ return path.startswith(self.base_url[2]) and not self.base_url[1] def file_path(self, url): """ Return the relative path to the media file on disk for the given URL. """ relative_url = url.removeprefix(self.base_url[2]) return url2pathname(relative_url) def serve(self, request): """Serve the request path.""" return serve(request, self.file_path(request.path), insecure=True) def get_response(self, request): try: return self.serve(request) except Http404 as e: return response_for_exception(request, e) async def get_response_async(self, request): try: return await sync_to_async(self.serve, thread_sensitive=False)(request) except Http404 as e: return await sync_to_async(response_for_exception, thread_sensitive=False)( request, e ) class StaticFilesHandler(StaticFilesHandlerMixin, WSGIHandler): """ WSGI middleware that intercepts calls to the static files directory, as defined by the STATIC_URL setting, and serves those files. """ def __init__(self, application): self.application = application self.base_url = urlparse(self.get_base_url()) super().__init__() def __call__(self, environ, start_response): if not self._should_handle(get_path_info(environ)): return self.application(environ, start_response) return super().__call__(environ, start_response) class ASGIStaticFilesHandler(StaticFilesHandlerMixin, ASGIHandler): """ ASGI application which wraps another and intercepts requests for static files, passing them off to Django's static file serving. """ def __init__(self, application): self.application = application self.base_url = urlparse(self.get_base_url()) async def __call__(self, scope, receive, send): # Only even look at HTTP requests if scope["type"] == "http" and self._should_handle(scope["path"]): # Serve static content # (the one thing super() doesn't do is __call__, apparently) return await super().__call__(scope, receive, send) # Hand off to the main app return await self.application(scope, receive, send) async def get_response_async(self, request): response = await super().get_response_async(request) response._resource_closers.append(request.close) # FileResponse is not async compatible. if response.streaming and not response.is_async: _iterator = response.streaming_content async def awrapper(): for part in await sync_to_async(list)(_iterator): yield part response.streaming_content = awrapper() return response
c8ba0179a0df09a38a8711b27e95581960e4d3c50a92862ec8089a7df8ff9cf6
import json import os import posixpath import re from hashlib import md5 from urllib.parse import unquote, urldefrag, urlsplit, urlunsplit from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles.utils import check_settings, matches_patterns from django.core.exceptions import ImproperlyConfigured from django.core.files.base import ContentFile from django.core.files.storage import FileSystemStorage, storages from django.utils.functional import LazyObject class StaticFilesStorage(FileSystemStorage): """ Standard file system storage for static files. The defaults for ``location`` and ``base_url`` are ``STATIC_ROOT`` and ``STATIC_URL``. """ def __init__(self, location=None, base_url=None, *args, **kwargs): if location is None: location = settings.STATIC_ROOT if base_url is None: base_url = settings.STATIC_URL check_settings(base_url) super().__init__(location, base_url, *args, **kwargs) # FileSystemStorage fallbacks to MEDIA_ROOT when location # is empty, so we restore the empty value. if not location: self.base_location = None self.location = None def path(self, name): if not self.location: raise ImproperlyConfigured( "You're using the staticfiles app " "without having set the STATIC_ROOT " "setting to a filesystem path." ) return super().path(name) class HashedFilesMixin: default_template = """url("%(url)s")""" max_post_process_passes = 5 support_js_module_import_aggregation = False _js_module_import_aggregation_patterns = ( "*.js", ( ( ( r"""(?P<matched>import(?s:(?P<import>[\s\{].*?))""" r"""\s*from\s*['"](?P<url>[\.\/].*?)["']\s*;)""" ), """import%(import)s from "%(url)s";""", ), ( ( r"""(?P<matched>export(?s:(?P<exports>[\s\{].*?))""" r"""\s*from\s*["'](?P<url>[\.\/].*?)["']\s*;)""" ), """export%(exports)s from "%(url)s";""", ), ( r"""(?P<matched>import\s*['"](?P<url>[\.\/].*?)["']\s*;)""", """import"%(url)s";""", ), ( r"""(?P<matched>import\(["'](?P<url>.*?)["']\))""", """import("%(url)s")""", ), ), ) patterns = ( ( "*.css", ( r"""(?P<matched>url\(['"]{0,1}\s*(?P<url>.*?)["']{0,1}\))""", ( r"""(?P<matched>@import\s*["']\s*(?P<url>.*?)["'])""", """@import url("%(url)s")""", ), ( ( r"(?m)(?P<matched>)^(/\*#[ \t]" r"(?-i:sourceMappingURL)=(?P<url>.*)[ \t]*\*/)$" ), "/*# sourceMappingURL=%(url)s */", ), ), ), ( "*.js", ( ( r"(?m)(?P<matched>)^(//# (?-i:sourceMappingURL)=(?P<url>.*))$", "//# sourceMappingURL=%(url)s", ), ), ), ) keep_intermediate_files = True def __init__(self, *args, **kwargs): if self.support_js_module_import_aggregation: self.patterns += (self._js_module_import_aggregation_patterns,) super().__init__(*args, **kwargs) self._patterns = {} self.hashed_files = {} for extension, patterns in self.patterns: for pattern in patterns: if isinstance(pattern, (tuple, list)): pattern, template = pattern else: template = self.default_template compiled = re.compile(pattern, re.IGNORECASE) self._patterns.setdefault(extension, []).append((compiled, template)) def file_hash(self, name, content=None): """ Return a hash of the file with the given name and optional content. """ if content is None: return None hasher = md5(usedforsecurity=False) for chunk in content.chunks(): hasher.update(chunk) return hasher.hexdigest()[:12] def hashed_name(self, name, content=None, filename=None): # `filename` is the name of file to hash if `content` isn't given. # `name` is the base name to construct the new hashed filename from. parsed_name = urlsplit(unquote(name)) clean_name = parsed_name.path.strip() filename = (filename and urlsplit(unquote(filename)).path.strip()) or clean_name opened = content is None if opened: if not self.exists(filename): raise ValueError( "The file '%s' could not be found with %r." % (filename, self) ) try: content = self.open(filename) except OSError: # Handle directory paths and fragments return name try: file_hash = self.file_hash(clean_name, content) finally: if opened: content.close() path, filename = os.path.split(clean_name) root, ext = os.path.splitext(filename) file_hash = (".%s" % file_hash) if file_hash else "" hashed_name = os.path.join(path, "%s%s%s" % (root, file_hash, ext)) unparsed_name = list(parsed_name) unparsed_name[2] = hashed_name # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax if "?#" in name and not unparsed_name[3]: unparsed_name[2] += "?" return urlunsplit(unparsed_name) def _url(self, hashed_name_func, name, force=False, hashed_files=None): """ Return the non-hashed URL in DEBUG mode. """ if settings.DEBUG and not force: hashed_name, fragment = name, "" else: clean_name, fragment = urldefrag(name) if urlsplit(clean_name).path.endswith("/"): # don't hash paths hashed_name = name else: args = (clean_name,) if hashed_files is not None: args += (hashed_files,) hashed_name = hashed_name_func(*args) final_url = super().url(hashed_name) # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax query_fragment = "?#" in name # [sic!] if fragment or query_fragment: urlparts = list(urlsplit(final_url)) if fragment and not urlparts[4]: urlparts[4] = fragment if query_fragment and not urlparts[3]: urlparts[2] += "?" final_url = urlunsplit(urlparts) return unquote(final_url) def url(self, name, force=False): """ Return the non-hashed URL in DEBUG mode. """ return self._url(self.stored_name, name, force) def url_converter(self, name, hashed_files, template=None): """ Return the custom URL converter for the given file name. """ if template is None: template = self.default_template def converter(matchobj): """ Convert the matched URL to a normalized and hashed URL. This requires figuring out which files the matched URL resolves to and calling the url() method of the storage. """ matches = matchobj.groupdict() matched = matches["matched"] url = matches["url"] # Ignore absolute/protocol-relative and data-uri URLs. if re.match(r"^[a-z]+:", url): return matched # Ignore absolute URLs that don't point to a static file (dynamic # CSS / JS?). Note that STATIC_URL cannot be empty. if url.startswith("/") and not url.startswith(settings.STATIC_URL): return matched # Strip off the fragment so a path-like fragment won't interfere. url_path, fragment = urldefrag(url) # Ignore URLs without a path if not url_path: return matched if url_path.startswith("/"): # Otherwise the condition above would have returned prematurely. assert url_path.startswith(settings.STATIC_URL) target_name = url_path.removeprefix(settings.STATIC_URL) else: # We're using the posixpath module to mix paths and URLs conveniently. source_name = name if os.sep == "/" else name.replace(os.sep, "/") target_name = posixpath.join(posixpath.dirname(source_name), url_path) # Determine the hashed name of the target file with the storage backend. hashed_url = self._url( self._stored_name, unquote(target_name), force=True, hashed_files=hashed_files, ) transformed_url = "/".join( url_path.split("/")[:-1] + hashed_url.split("/")[-1:] ) # Restore the fragment that was stripped off earlier. if fragment: transformed_url += ("?#" if "?#" in url else "#") + fragment # Return the hashed version to the file matches["url"] = unquote(transformed_url) return template % matches return converter def post_process(self, paths, dry_run=False, **options): """ Post process the given dictionary of files (called from collectstatic). Processing is actually two separate operations: 1. renaming files to include a hash of their content for cache-busting, and copying those files to the target storage. 2. adjusting files which contain references to other files so they refer to the cache-busting filenames. If either of these are performed on a file, then that file is considered post-processed. """ # don't even dare to process the files if we're in dry run mode if dry_run: return # where to store the new paths hashed_files = {} # build a list of adjustable files adjustable_paths = [ path for path in paths if matches_patterns(path, self._patterns) ] # Adjustable files to yield at end, keyed by the original path. processed_adjustable_paths = {} # Do a single pass first. Post-process all files once, yielding not # adjustable files and exceptions, and collecting adjustable files. for name, hashed_name, processed, _ in self._post_process( paths, adjustable_paths, hashed_files ): if name not in adjustable_paths or isinstance(processed, Exception): yield name, hashed_name, processed else: processed_adjustable_paths[name] = (name, hashed_name, processed) paths = {path: paths[path] for path in adjustable_paths} substitutions = False for i in range(self.max_post_process_passes): substitutions = False for name, hashed_name, processed, subst in self._post_process( paths, adjustable_paths, hashed_files ): # Overwrite since hashed_name may be newer. processed_adjustable_paths[name] = (name, hashed_name, processed) substitutions = substitutions or subst if not substitutions: break if substitutions: yield "All", None, RuntimeError("Max post-process passes exceeded.") # Store the processed paths self.hashed_files.update(hashed_files) # Yield adjustable files with final, hashed name. yield from processed_adjustable_paths.values() def _post_process(self, paths, adjustable_paths, hashed_files): # Sort the files by directory level def path_level(name): return len(name.split(os.sep)) for name in sorted(paths, key=path_level, reverse=True): substitutions = True # use the original, local file, not the copied-but-unprocessed # file, which might be somewhere far away, like S3 storage, path = paths[name] with storage.open(path) as original_file: cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) # generate the hash with the original content, even for # adjustable files. if hash_key not in hashed_files: hashed_name = self.hashed_name(name, original_file) else: hashed_name = hashed_files[hash_key] # then get the original's file content.. if hasattr(original_file, "seek"): original_file.seek(0) hashed_file_exists = self.exists(hashed_name) processed = False # ..to apply each replacement pattern to the content if name in adjustable_paths: old_hashed_name = hashed_name try: content = original_file.read().decode("utf-8") except UnicodeDecodeError as exc: yield name, None, exc, False for extension, patterns in self._patterns.items(): if matches_patterns(path, (extension,)): for pattern, template in patterns: converter = self.url_converter( name, hashed_files, template ) try: content = pattern.sub(converter, content) except ValueError as exc: yield name, None, exc, False if hashed_file_exists: self.delete(hashed_name) # then save the processed result content_file = ContentFile(content.encode()) if self.keep_intermediate_files: # Save intermediate file for reference self._save(hashed_name, content_file) hashed_name = self.hashed_name(name, content_file) if self.exists(hashed_name): self.delete(hashed_name) saved_name = self._save(hashed_name, content_file) hashed_name = self.clean_name(saved_name) # If the file hash stayed the same, this file didn't change if old_hashed_name == hashed_name: substitutions = False processed = True if not processed: # or handle the case in which neither processing nor # a change to the original file happened if not hashed_file_exists: processed = True saved_name = self._save(hashed_name, original_file) hashed_name = self.clean_name(saved_name) # and then set the cache accordingly hashed_files[hash_key] = hashed_name yield name, hashed_name, processed, substitutions def clean_name(self, name): return name.replace("\\", "/") def hash_key(self, name): return name def _stored_name(self, name, hashed_files): # Normalize the path to avoid multiple names for the same file like # ../foo/bar.css and ../foo/../foo/bar.css which normalize to the same # path. name = posixpath.normpath(name) cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) cache_name = hashed_files.get(hash_key) if cache_name is None: cache_name = self.clean_name(self.hashed_name(name)) return cache_name def stored_name(self, name): cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) cache_name = self.hashed_files.get(hash_key) if cache_name: return cache_name # No cached name found, recalculate it from the files. intermediate_name = name for i in range(self.max_post_process_passes + 1): cache_name = self.clean_name( self.hashed_name(name, content=None, filename=intermediate_name) ) if intermediate_name == cache_name: # Store the hashed name if there was a miss. self.hashed_files[hash_key] = cache_name return cache_name else: # Move on to the next intermediate file. intermediate_name = cache_name # If the cache name can't be determined after the max number of passes, # the intermediate files on disk may be corrupt; avoid an infinite loop. raise ValueError("The name '%s' could not be hashed with %r." % (name, self)) class ManifestFilesMixin(HashedFilesMixin): manifest_version = "1.1" # the manifest format standard manifest_name = "staticfiles.json" manifest_strict = True keep_intermediate_files = False def __init__(self, *args, manifest_storage=None, **kwargs): super().__init__(*args, **kwargs) if manifest_storage is None: manifest_storage = self self.manifest_storage = manifest_storage self.hashed_files, self.manifest_hash = self.load_manifest() def read_manifest(self): try: with self.manifest_storage.open(self.manifest_name) as manifest: return manifest.read().decode() except FileNotFoundError: return None def load_manifest(self): content = self.read_manifest() if content is None: return {}, "" try: stored = json.loads(content) except json.JSONDecodeError: pass else: version = stored.get("version") if version in ("1.0", "1.1"): return stored.get("paths", {}), stored.get("hash", "") raise ValueError( "Couldn't load manifest '%s' (version %s)" % (self.manifest_name, self.manifest_version) ) def post_process(self, *args, **kwargs): self.hashed_files = {} yield from super().post_process(*args, **kwargs) if not kwargs.get("dry_run"): self.save_manifest() def save_manifest(self): self.manifest_hash = self.file_hash( None, ContentFile(json.dumps(sorted(self.hashed_files.items())).encode()) ) payload = { "paths": self.hashed_files, "version": self.manifest_version, "hash": self.manifest_hash, } if self.manifest_storage.exists(self.manifest_name): self.manifest_storage.delete(self.manifest_name) contents = json.dumps(payload).encode() self.manifest_storage._save(self.manifest_name, ContentFile(contents)) def stored_name(self, name): parsed_name = urlsplit(unquote(name)) clean_name = parsed_name.path.strip() hash_key = self.hash_key(clean_name) cache_name = self.hashed_files.get(hash_key) if cache_name is None: if self.manifest_strict: raise ValueError( "Missing staticfiles manifest entry for '%s'" % clean_name ) cache_name = self.clean_name(self.hashed_name(name)) unparsed_name = list(parsed_name) unparsed_name[2] = cache_name # Special casing for a @font-face hack, like url(myfont.eot?#iefix") # http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax if "?#" in name and not unparsed_name[3]: unparsed_name[2] += "?" return urlunsplit(unparsed_name) class ManifestStaticFilesStorage(ManifestFilesMixin, StaticFilesStorage): """ A static file system storage backend which also saves hashed copies of the files it saves. """ pass class ConfiguredStorage(LazyObject): def _setup(self): self._wrapped = storages[STATICFILES_STORAGE_ALIAS] staticfiles_storage = ConfiguredStorage()
eabfb3fccc982268040b92cfbe339da7ae31c24895fe26fded28383787978f16
import binascii import json from django.conf import settings from django.contrib.messages.storage.base import BaseStorage, Message from django.core import signing from django.http import SimpleCookie from django.utils.safestring import SafeData, mark_safe class MessageEncoder(json.JSONEncoder): """ Compactly serialize instances of the ``Message`` class as JSON. """ message_key = "__json_message" def default(self, obj): if isinstance(obj, Message): # Using 0/1 here instead of False/True to produce more compact json is_safedata = 1 if isinstance(obj.message, SafeData) else 0 message = [self.message_key, is_safedata, obj.level, obj.message] if obj.extra_tags is not None: message.append(obj.extra_tags) return message return super().default(obj) class MessageDecoder(json.JSONDecoder): """ Decode JSON that includes serialized ``Message`` instances. """ def process_messages(self, obj): if isinstance(obj, list) and obj: if obj[0] == MessageEncoder.message_key: if obj[1]: obj[3] = mark_safe(obj[3]) return Message(*obj[2:]) return [self.process_messages(item) for item in obj] if isinstance(obj, dict): return {key: self.process_messages(value) for key, value in obj.items()} return obj def decode(self, s, **kwargs): decoded = super().decode(s, **kwargs) return self.process_messages(decoded) class MessagePartSerializer: def dumps(self, obj): return [ json.dumps( o, separators=(",", ":"), cls=MessageEncoder, ) for o in obj ] class MessagePartGatherSerializer: def dumps(self, obj): """ The parameter is an already serialized list of Message objects. No need to serialize it again, only join the list together and encode it. """ return ("[" + ",".join(obj) + "]").encode("latin-1") class MessageSerializer: def loads(self, data): return json.loads(data.decode("latin-1"), cls=MessageDecoder) class CookieStorage(BaseStorage): """ Store messages in a cookie. """ cookie_name = "messages" # uwsgi's default configuration enforces a maximum size of 4kb for all the # HTTP headers. In order to leave some room for other cookies and headers, # restrict the session cookie to 1/2 of 4kb. See #18781. max_cookie_size = 2048 not_finished = "__messagesnotfinished__" not_finished_json = json.dumps("__messagesnotfinished__") key_salt = "django.contrib.messages" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.signer = signing.get_cookie_signer(salt=self.key_salt) def _get(self, *args, **kwargs): """ Retrieve a list of messages from the messages cookie. If the not_finished sentinel value is found at the end of the message list, remove it and return a result indicating that not all messages were retrieved by this storage. """ data = self.request.COOKIES.get(self.cookie_name) messages = self._decode(data) all_retrieved = not (messages and messages[-1] == self.not_finished) if messages and not all_retrieved: # remove the sentinel value messages.pop() return messages, all_retrieved def _update_cookie(self, encoded_data, response): """ Either set the cookie with the encoded data if there is any data to store, or delete the cookie. """ if encoded_data: response.set_cookie( self.cookie_name, encoded_data, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE or None, httponly=settings.SESSION_COOKIE_HTTPONLY or None, samesite=settings.SESSION_COOKIE_SAMESITE, ) else: response.delete_cookie( self.cookie_name, domain=settings.SESSION_COOKIE_DOMAIN, samesite=settings.SESSION_COOKIE_SAMESITE, ) def _store(self, messages, response, remove_oldest=True, *args, **kwargs): """ Store the messages to a cookie and return a list of any messages which could not be stored. If the encoded data is larger than ``max_cookie_size``, remove messages until the data fits (these are the messages which are returned), and add the not_finished sentinel value to indicate as much. """ unstored_messages = [] serialized_messages = MessagePartSerializer().dumps(messages) encoded_data = self._encode_parts(serialized_messages) if self.max_cookie_size: # data is going to be stored eventually by SimpleCookie, which # adds its own overhead, which we must account for. cookie = SimpleCookie() # create outside the loop def is_too_large_for_cookie(data): return data and len(cookie.value_encode(data)[1]) > self.max_cookie_size def compute_msg(some_serialized_msg): return self._encode_parts( some_serialized_msg + [self.not_finished_json], encode_empty=True, ) if is_too_large_for_cookie(encoded_data): if remove_oldest: idx = bisect_keep_right( serialized_messages, fn=lambda m: is_too_large_for_cookie(compute_msg(m)), ) unstored_messages = messages[:idx] encoded_data = compute_msg(serialized_messages[idx:]) else: idx = bisect_keep_left( serialized_messages, fn=lambda m: is_too_large_for_cookie(compute_msg(m)), ) unstored_messages = messages[idx:] encoded_data = compute_msg(serialized_messages[:idx]) self._update_cookie(encoded_data, response) return unstored_messages def _encode_parts(self, messages, encode_empty=False): """ Return an encoded version of the serialized messages list which can be stored as plain text. Since the data will be retrieved from the client-side, the encoded data also contains a hash to ensure that the data was not tampered with. """ if messages or encode_empty: return self.signer.sign_object( messages, serializer=MessagePartGatherSerializer, compress=True ) def _encode(self, messages, encode_empty=False): """ Return an encoded version of the messages list which can be stored as plain text. Proxies MessagePartSerializer.dumps and _encoded_parts. """ serialized_messages = MessagePartSerializer().dumps(messages) return self._encode_parts(serialized_messages, encode_empty=encode_empty) def _decode(self, data): """ Safely decode an encoded text stream back into a list of messages. If the encoded text stream contained an invalid hash or was in an invalid format, return None. """ if not data: return None try: return self.signer.unsign_object(data, serializer=MessageSerializer) except (signing.BadSignature, binascii.Error, json.JSONDecodeError): pass # Mark the data as used (so it gets removed) since something was wrong # with the data. self.used = True return None def bisect_keep_left(a, fn): """ Find the index of the first element from the start of the array that verifies the given condition. The function is applied from the start of the array to the pivot. """ lo = 0 hi = len(a) while lo < hi: mid = (lo + hi) // 2 if fn(a[: mid + 1]): hi = mid else: lo = mid + 1 return lo def bisect_keep_right(a, fn): """ Find the index of the first element from the end of the array that verifies the given condition. The function is applied from the pivot to the end of array. """ lo = 0 hi = len(a) while lo < hi: mid = (lo + hi) // 2 if fn(a[mid:]): lo = mid + 1 else: hi = mid return lo
e5a7ce79c86229174ee3822a3640920b414b66d88b3b1488946ca4ed30138416
from datetime import datetime, timedelta from django import forms from django.conf import settings from django.contrib import messages from django.contrib.admin import FieldListFilter from django.contrib.admin.exceptions import ( DisallowedModelAdminLookup, DisallowedModelAdminToField, ) from django.contrib.admin.options import ( IS_FACETS_VAR, IS_POPUP_VAR, TO_FIELD_VAR, IncorrectLookupParameters, ShowFacets, ) from django.contrib.admin.utils import ( build_q_object_from_lookup_parameters, get_fields_from_path, lookup_spawns_duplicates, prepare_lookup_value, quote, ) from django.core.exceptions import ( FieldDoesNotExist, ImproperlyConfigured, SuspiciousOperation, ) from django.core.paginator import InvalidPage from django.db.models import Exists, F, Field, ManyToOneRel, OrderBy, OuterRef from django.db.models.expressions import Combinable from django.urls import reverse from django.utils.http import urlencode from django.utils.timezone import make_aware from django.utils.translation import gettext # Changelist settings ALL_VAR = "all" ORDER_VAR = "o" PAGE_VAR = "p" SEARCH_VAR = "q" ERROR_FLAG = "e" IGNORED_PARAMS = ( ALL_VAR, ORDER_VAR, SEARCH_VAR, IS_FACETS_VAR, IS_POPUP_VAR, TO_FIELD_VAR, ) class ChangeListSearchForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Populate "fields" dynamically because SEARCH_VAR is a variable: self.fields = { SEARCH_VAR: forms.CharField(required=False, strip=False), } class ChangeList: search_form_class = ChangeListSearchForm def __init__( self, request, model, list_display, list_display_links, list_filter, date_hierarchy, search_fields, list_select_related, list_per_page, list_max_show_all, list_editable, model_admin, sortable_by, search_help_text, ): self.model = model self.opts = model._meta self.lookup_opts = self.opts self.root_queryset = model_admin.get_queryset(request) self.list_display = list_display self.list_display_links = list_display_links self.list_filter = list_filter self.has_filters = None self.has_active_filters = None self.clear_all_filters_qs = None self.date_hierarchy = date_hierarchy self.search_fields = search_fields self.list_select_related = list_select_related self.list_per_page = list_per_page self.list_max_show_all = list_max_show_all self.model_admin = model_admin self.preserved_filters = model_admin.get_preserved_filters(request) self.sortable_by = sortable_by self.search_help_text = search_help_text # Get search parameters from the query string. _search_form = self.search_form_class(request.GET) if not _search_form.is_valid(): for error in _search_form.errors.values(): messages.error(request, ", ".join(error)) self.query = _search_form.cleaned_data.get(SEARCH_VAR) or "" try: self.page_num = int(request.GET.get(PAGE_VAR, 1)) except ValueError: self.page_num = 1 self.show_all = ALL_VAR in request.GET self.is_popup = IS_POPUP_VAR in request.GET self.add_facets = model_admin.show_facets is ShowFacets.ALWAYS or ( model_admin.show_facets is ShowFacets.ALLOW and IS_FACETS_VAR in request.GET ) self.is_facets_optional = model_admin.show_facets is ShowFacets.ALLOW to_field = request.GET.get(TO_FIELD_VAR) if to_field and not model_admin.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( "The field %s cannot be referenced." % to_field ) self.to_field = to_field self.params = dict(request.GET.items()) self.filter_params = dict(request.GET.lists()) if PAGE_VAR in self.params: del self.params[PAGE_VAR] del self.filter_params[PAGE_VAR] if ERROR_FLAG in self.params: del self.params[ERROR_FLAG] del self.filter_params[ERROR_FLAG] self.remove_facet_link = self.get_query_string(remove=[IS_FACETS_VAR]) self.add_facet_link = self.get_query_string({IS_FACETS_VAR: True}) if self.is_popup: self.list_editable = () else: self.list_editable = list_editable self.queryset = self.get_queryset(request) self.get_results(request) if self.is_popup: title = gettext("Select %s") elif self.model_admin.has_change_permission(request): title = gettext("Select %s to change") else: title = gettext("Select %s to view") self.title = title % self.opts.verbose_name self.pk_attname = self.lookup_opts.pk.attname def __repr__(self): return "<%s: model=%s model_admin=%s>" % ( self.__class__.__qualname__, self.model.__qualname__, self.model_admin.__class__.__qualname__, ) def get_filters_params(self, params=None): """ Return all params except IGNORED_PARAMS. """ params = params or self.filter_params lookup_params = params.copy() # a dictionary of the query string # Remove all the parameters that are globally and systematically # ignored. for ignored in IGNORED_PARAMS: if ignored in lookup_params: del lookup_params[ignored] return lookup_params def get_filters(self, request): lookup_params = self.get_filters_params() may_have_duplicates = False has_active_filters = False for key, value_list in lookup_params.items(): for value in value_list: if not self.model_admin.lookup_allowed(key, value): raise DisallowedModelAdminLookup(f"Filtering by {key} not allowed") filter_specs = [] for list_filter in self.list_filter: lookup_params_count = len(lookup_params) if callable(list_filter): # This is simply a custom list filter class. spec = list_filter(request, lookup_params, self.model, self.model_admin) else: field_path = None if isinstance(list_filter, (tuple, list)): # This is a custom FieldListFilter class for a given field. field, field_list_filter_class = list_filter else: # This is simply a field name, so use the default # FieldListFilter class that has been registered for the # type of the given field. field, field_list_filter_class = list_filter, FieldListFilter.create if not isinstance(field, Field): field_path = field field = get_fields_from_path(self.model, field_path)[-1] spec = field_list_filter_class( field, request, lookup_params, self.model, self.model_admin, field_path=field_path, ) # field_list_filter_class removes any lookup_params it # processes. If that happened, check if duplicates should be # removed. if lookup_params_count > len(lookup_params): may_have_duplicates |= lookup_spawns_duplicates( self.lookup_opts, field_path, ) if spec and spec.has_output(): filter_specs.append(spec) if lookup_params_count > len(lookup_params): has_active_filters = True if self.date_hierarchy: # Create bounded lookup parameters so that the query is more # efficient. year = lookup_params.pop("%s__year" % self.date_hierarchy, None) if year is not None: month = lookup_params.pop("%s__month" % self.date_hierarchy, None) day = lookup_params.pop("%s__day" % self.date_hierarchy, None) try: from_date = datetime( int(year[-1]), int(month[-1] if month is not None else 1), int(day[-1] if day is not None else 1), ) except ValueError as e: raise IncorrectLookupParameters(e) from e if day: to_date = from_date + timedelta(days=1) elif month: # In this branch, from_date will always be the first of a # month, so advancing 32 days gives the next month. to_date = (from_date + timedelta(days=32)).replace(day=1) else: to_date = from_date.replace(year=from_date.year + 1) if settings.USE_TZ: from_date = make_aware(from_date) to_date = make_aware(to_date) lookup_params.update( { "%s__gte" % self.date_hierarchy: [from_date], "%s__lt" % self.date_hierarchy: [to_date], } ) # At this point, all the parameters used by the various ListFilters # have been removed from lookup_params, which now only contains other # parameters passed via the query string. We now loop through the # remaining parameters both to ensure that all the parameters are valid # fields and to determine if at least one of them spawns duplicates. If # the lookup parameters aren't real fields, then bail out. try: for key, value in lookup_params.items(): lookup_params[key] = prepare_lookup_value(key, value) may_have_duplicates |= lookup_spawns_duplicates(self.lookup_opts, key) return ( filter_specs, bool(filter_specs), lookup_params, may_have_duplicates, has_active_filters, ) except FieldDoesNotExist as e: raise IncorrectLookupParameters(e) from e def get_query_string(self, new_params=None, remove=None): if new_params is None: new_params = {} if remove is None: remove = [] p = self.filter_params.copy() for r in remove: for k in list(p): if k.startswith(r): del p[k] for k, v in new_params.items(): if v is None: if k in p: del p[k] else: p[k] = v return "?%s" % urlencode(sorted(p.items()), doseq=True) def get_results(self, request): paginator = self.model_admin.get_paginator( request, self.queryset, self.list_per_page ) # Get the number of objects, with admin filters applied. result_count = paginator.count # Get the total number of objects, with no admin filters applied. if self.model_admin.show_full_result_count: full_result_count = self.root_queryset.count() else: full_result_count = None can_show_all = result_count <= self.list_max_show_all multi_page = result_count > self.list_per_page # Get the list of objects to display on this page. if (self.show_all and can_show_all) or not multi_page: result_list = self.queryset._clone() else: try: result_list = paginator.page(self.page_num).object_list except InvalidPage: raise IncorrectLookupParameters self.result_count = result_count self.show_full_result_count = self.model_admin.show_full_result_count # Admin actions are shown if there is at least one entry # or if entries are not counted because show_full_result_count is disabled self.show_admin_actions = not self.show_full_result_count or bool( full_result_count ) self.full_result_count = full_result_count self.result_list = result_list self.can_show_all = can_show_all self.multi_page = multi_page self.paginator = paginator def _get_default_ordering(self): ordering = [] if self.model_admin.ordering: ordering = self.model_admin.ordering elif self.lookup_opts.ordering: ordering = self.lookup_opts.ordering return ordering def get_ordering_field(self, field_name): """ Return the proper model field name corresponding to the given field_name to use for ordering. field_name may either be the name of a proper model field or the name of a method (on the admin or model) or a callable with the 'admin_order_field' attribute. Return None if no proper model field name can be matched. """ try: field = self.lookup_opts.get_field(field_name) return field.name except FieldDoesNotExist: # See whether field_name is a name of a non-field # that allows sorting. if callable(field_name): attr = field_name elif hasattr(self.model_admin, field_name): attr = getattr(self.model_admin, field_name) else: attr = getattr(self.model, field_name) if isinstance(attr, property) and hasattr(attr, "fget"): attr = attr.fget return getattr(attr, "admin_order_field", None) def get_ordering(self, request, queryset): """ Return the list of ordering fields for the change list. First check the get_ordering() method in model admin, then check the object's default ordering. Then, any manually-specified ordering from the query string overrides anything. Finally, a deterministic order is guaranteed by calling _get_deterministic_ordering() with the constructed ordering. """ params = self.params ordering = list( self.model_admin.get_ordering(request) or self._get_default_ordering() ) if ORDER_VAR in params: # Clear ordering and used params ordering = [] order_params = params[ORDER_VAR].split(".") for p in order_params: try: none, pfx, idx = p.rpartition("-") field_name = self.list_display[int(idx)] order_field = self.get_ordering_field(field_name) if not order_field: continue # No 'admin_order_field', skip it if isinstance(order_field, OrderBy): if pfx == "-": order_field = order_field.copy() order_field.reverse_ordering() ordering.append(order_field) elif hasattr(order_field, "resolve_expression"): # order_field is an expression. ordering.append( order_field.desc() if pfx == "-" else order_field.asc() ) # reverse order if order_field has already "-" as prefix elif pfx == "-" and order_field.startswith(pfx): ordering.append(order_field.removeprefix(pfx)) else: ordering.append(pfx + order_field) except (IndexError, ValueError): continue # Invalid ordering specified, skip it. # Add the given query's ordering fields, if any. ordering.extend(queryset.query.order_by) return self._get_deterministic_ordering(ordering) def _get_deterministic_ordering(self, ordering): """ Ensure a deterministic order across all database backends. Search for a single field or unique together set of fields providing a total ordering. If these are missing, augment the ordering with a descendant primary key. """ ordering = list(ordering) ordering_fields = set() total_ordering_fields = {"pk"} | { field.attname for field in self.lookup_opts.fields if field.unique and not field.null } for part in ordering: # Search for single field providing a total ordering. field_name = None if isinstance(part, str): field_name = part.lstrip("-") elif isinstance(part, F): field_name = part.name elif isinstance(part, OrderBy) and isinstance(part.expression, F): field_name = part.expression.name if field_name: # Normalize attname references by using get_field(). try: field = self.lookup_opts.get_field(field_name) except FieldDoesNotExist: # Could be "?" for random ordering or a related field # lookup. Skip this part of introspection for now. continue # Ordering by a related field name orders by the referenced # model's ordering. Skip this part of introspection for now. if field.remote_field and field_name == field.name: continue if field.attname in total_ordering_fields: break ordering_fields.add(field.attname) else: # No single total ordering field, try unique_together and total # unique constraints. constraint_field_names = ( *self.lookup_opts.unique_together, *( constraint.fields for constraint in self.lookup_opts.total_unique_constraints ), ) for field_names in constraint_field_names: # Normalize attname references by using get_field(). fields = [ self.lookup_opts.get_field(field_name) for field_name in field_names ] # Composite unique constraints containing a nullable column # cannot ensure total ordering. if any(field.null for field in fields): continue if ordering_fields.issuperset(field.attname for field in fields): break else: # If no set of unique fields is present in the ordering, rely # on the primary key to provide total ordering. ordering.append("-pk") return ordering def get_ordering_field_columns(self): """ Return a dictionary of ordering field column numbers and asc/desc. """ # We must cope with more than one column having the same underlying sort # field, so we base things on column numbers. ordering = self._get_default_ordering() ordering_fields = {} if ORDER_VAR not in self.params: # for ordering specified on ModelAdmin or model Meta, we don't know # the right column numbers absolutely, because there might be more # than one column associated with that ordering, so we guess. for field in ordering: if isinstance(field, (Combinable, OrderBy)): if not isinstance(field, OrderBy): field = field.asc() if isinstance(field.expression, F): order_type = "desc" if field.descending else "asc" field = field.expression.name else: continue elif field.startswith("-"): field = field.removeprefix("-") order_type = "desc" else: order_type = "asc" for index, attr in enumerate(self.list_display): if self.get_ordering_field(attr) == field: ordering_fields[index] = order_type break else: for p in self.params[ORDER_VAR].split("."): none, pfx, idx = p.rpartition("-") try: idx = int(idx) except ValueError: continue # skip it ordering_fields[idx] = "desc" if pfx == "-" else "asc" return ordering_fields def get_queryset(self, request, exclude_parameters=None): # First, we collect all the declared list filters. ( self.filter_specs, self.has_filters, remaining_lookup_params, filters_may_have_duplicates, self.has_active_filters, ) = self.get_filters(request) # Then, we let every list filter modify the queryset to its liking. qs = self.root_queryset for filter_spec in self.filter_specs: if ( exclude_parameters is None or filter_spec.expected_parameters() != exclude_parameters ): new_qs = filter_spec.queryset(request, qs) if new_qs is not None: qs = new_qs try: # Finally, we apply the remaining lookup parameters from the query # string (i.e. those that haven't already been processed by the # filters). q_object = build_q_object_from_lookup_parameters(remaining_lookup_params) qs = qs.filter(q_object) except (SuspiciousOperation, ImproperlyConfigured): # Allow certain types of errors to be re-raised as-is so that the # caller can treat them in a special way. raise except Exception as e: # Every other error is caught with a naked except, because we don't # have any other way of validating lookup parameters. They might be # invalid if the keyword arguments are incorrect, or if the values # are not in the correct type, so we might get FieldError, # ValueError, ValidationError, or ?. raise IncorrectLookupParameters(e) # Apply search results qs, search_may_have_duplicates = self.model_admin.get_search_results( request, qs, self.query, ) # Set query string for clearing all filters. self.clear_all_filters_qs = self.get_query_string( new_params=remaining_lookup_params, remove=self.get_filters_params(), ) # Remove duplicates from results, if necessary if filters_may_have_duplicates | search_may_have_duplicates: qs = qs.filter(pk=OuterRef("pk")) qs = self.root_queryset.filter(Exists(qs)) # Set ordering. ordering = self.get_ordering(request, qs) qs = qs.order_by(*ordering) if not qs.query.select_related: qs = self.apply_select_related(qs) return qs def apply_select_related(self, qs): if self.list_select_related is True: return qs.select_related() if self.list_select_related is False: if self.has_related_field_in_list_display(): return qs.select_related() if self.list_select_related: return qs.select_related(*self.list_select_related) return qs def has_related_field_in_list_display(self): for field_name in self.list_display: try: field = self.lookup_opts.get_field(field_name) except FieldDoesNotExist: pass else: if isinstance(field.remote_field, ManyToOneRel): # <FK>_id field names don't require a join. if field_name != field.get_attname(): return True return False def url_for_result(self, result): pk = getattr(result, self.pk_attname) return reverse( "admin:%s_%s_change" % (self.opts.app_label, self.opts.model_name), args=(quote(pk),), current_app=self.model_admin.admin_site.name, )
849baff94a429ea3b9d1a6f621935979745b7401a181bccc6fcc68924b18df76
import datetime import decimal import enum import functools import math import os import pathlib import re import sys import time import uuid import zoneinfo from types import NoneType from unittest import mock import custom_migration_operations.more_operations import custom_migration_operations.operations from django import get_version from django.conf import SettingsReference, settings from django.core.validators import EmailValidator, RegexValidator from django.db import migrations, models from django.db.migrations.serializer import BaseSerializer from django.db.migrations.writer import MigrationWriter, OperationWriter from django.test import SimpleTestCase from django.utils.deconstruct import deconstructible from django.utils.functional import SimpleLazyObject from django.utils.timezone import get_default_timezone, get_fixed_timezone from django.utils.translation import gettext_lazy as _ from .models import FoodManager, FoodQuerySet class DeconstructibleInstances: def deconstruct(self): return ("DeconstructibleInstances", [], {}) class Money(decimal.Decimal): def deconstruct(self): return ( "%s.%s" % (self.__class__.__module__, self.__class__.__name__), [str(self)], {}, ) class TestModel1: def upload_to(self): return "/somewhere/dynamic/" thing = models.FileField(upload_to=upload_to) class TextEnum(enum.Enum): A = "a-value" B = "value-b" class TextTranslatedEnum(enum.Enum): A = _("a-value") B = _("value-b") class BinaryEnum(enum.Enum): A = b"a-value" B = b"value-b" class IntEnum(enum.IntEnum): A = 1 B = 2 class IntFlagEnum(enum.IntFlag): A = 1 B = 2 class OperationWriterTests(SimpleTestCase): def test_empty_signature(self): operation = custom_migration_operations.operations.TestOperation() buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.TestOperation(\n),", ) def test_args_signature(self): operation = custom_migration_operations.operations.ArgsOperation(1, 2) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsOperation(\n" " arg1=1,\n" " arg2=2,\n" "),", ) def test_kwargs_signature(self): operation = custom_migration_operations.operations.KwargsOperation(kwarg1=1) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.KwargsOperation(\n" " kwarg1=1,\n" "),", ) def test_args_kwargs_signature(self): operation = custom_migration_operations.operations.ArgsKwargsOperation( 1, 2, kwarg2=4 ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsKwargsOperation(\n" " arg1=1,\n" " arg2=2,\n" " kwarg2=4,\n" "),", ) def test_nested_args_signature(self): operation = custom_migration_operations.operations.ArgsOperation( custom_migration_operations.operations.ArgsOperation(1, 2), custom_migration_operations.operations.KwargsOperation(kwarg1=3, kwarg2=4), ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsOperation(\n" " arg1=custom_migration_operations.operations.ArgsOperation(\n" " arg1=1,\n" " arg2=2,\n" " ),\n" " arg2=custom_migration_operations.operations.KwargsOperation(\n" " kwarg1=3,\n" " kwarg2=4,\n" " ),\n" "),", ) def test_multiline_args_signature(self): operation = custom_migration_operations.operations.ArgsOperation( "test\n arg1", "test\narg2" ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsOperation(\n" " arg1='test\\n arg1',\n" " arg2='test\\narg2',\n" "),", ) def test_expand_args_signature(self): operation = custom_migration_operations.operations.ExpandArgsOperation([1, 2]) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ExpandArgsOperation(\n" " arg=[\n" " 1,\n" " 2,\n" " ],\n" "),", ) def test_nested_operation_expand_args_signature(self): operation = custom_migration_operations.operations.ExpandArgsOperation( arg=[ custom_migration_operations.operations.KwargsOperation( kwarg1=1, kwarg2=2, ), ] ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ExpandArgsOperation(\n" " arg=[\n" " custom_migration_operations.operations.KwargsOperation(\n" " kwarg1=1,\n" " kwarg2=2,\n" " ),\n" " ],\n" "),", ) class WriterTests(SimpleTestCase): """ Tests the migration writer (makes migration files from Migration instances) """ class NestedEnum(enum.IntEnum): A = 1 B = 2 class NestedChoices(models.TextChoices): X = "X", "X value" Y = "Y", "Y value" def safe_exec(self, string, value=None): d = {} try: exec(string, globals(), d) except Exception as e: if value: self.fail( "Could not exec %r (from value %r): %s" % (string.strip(), value, e) ) else: self.fail("Could not exec %r: %s" % (string.strip(), e)) return d def serialize_round_trip(self, value): string, imports = MigrationWriter.serialize(value) return self.safe_exec( "%s\ntest_value_result = %s" % ("\n".join(imports), string), value )["test_value_result"] def assertSerializedEqual(self, value): self.assertEqual(self.serialize_round_trip(value), value) def assertSerializedResultEqual(self, value, target): self.assertEqual(MigrationWriter.serialize(value), target) def assertSerializedFieldEqual(self, value): new_value = self.serialize_round_trip(value) self.assertEqual(value.__class__, new_value.__class__) self.assertEqual(value.max_length, new_value.max_length) self.assertEqual(value.null, new_value.null) self.assertEqual(value.unique, new_value.unique) def test_serialize_numbers(self): self.assertSerializedEqual(1) self.assertSerializedEqual(1.2) self.assertTrue(math.isinf(self.serialize_round_trip(float("inf")))) self.assertTrue(math.isinf(self.serialize_round_trip(float("-inf")))) self.assertTrue(math.isnan(self.serialize_round_trip(float("nan")))) self.assertSerializedEqual(decimal.Decimal("1.3")) self.assertSerializedResultEqual( decimal.Decimal("1.3"), ("Decimal('1.3')", {"from decimal import Decimal"}) ) self.assertSerializedEqual(Money("1.3")) self.assertSerializedResultEqual( Money("1.3"), ("migrations.test_writer.Money('1.3')", {"import migrations.test_writer"}), ) def test_serialize_constants(self): self.assertSerializedEqual(None) self.assertSerializedEqual(True) self.assertSerializedEqual(False) def test_serialize_strings(self): self.assertSerializedEqual(b"foobar") string, imports = MigrationWriter.serialize(b"foobar") self.assertEqual(string, "b'foobar'") self.assertSerializedEqual("föobár") string, imports = MigrationWriter.serialize("foobar") self.assertEqual(string, "'foobar'") def test_serialize_multiline_strings(self): self.assertSerializedEqual(b"foo\nbar") string, imports = MigrationWriter.serialize(b"foo\nbar") self.assertEqual(string, "b'foo\\nbar'") self.assertSerializedEqual("föo\nbár") string, imports = MigrationWriter.serialize("foo\nbar") self.assertEqual(string, "'foo\\nbar'") def test_serialize_collections(self): self.assertSerializedEqual({1: 2}) self.assertSerializedEqual(["a", 2, True, None]) self.assertSerializedEqual({2, 3, "eighty"}) self.assertSerializedEqual({"lalalala": ["yeah", "no", "maybe"]}) self.assertSerializedEqual(_("Hello")) def test_serialize_builtin_types(self): self.assertSerializedEqual([list, tuple, dict, set, frozenset]) self.assertSerializedResultEqual( [list, tuple, dict, set, frozenset], ("[list, tuple, dict, set, frozenset]", set()), ) def test_serialize_lazy_objects(self): pattern = re.compile(r"^foo$") lazy_pattern = SimpleLazyObject(lambda: pattern) self.assertEqual(self.serialize_round_trip(lazy_pattern), pattern) def test_serialize_enums(self): self.assertSerializedResultEqual( TextEnum.A, ("migrations.test_writer.TextEnum['A']", {"import migrations.test_writer"}), ) self.assertSerializedResultEqual( TextTranslatedEnum.A, ( "migrations.test_writer.TextTranslatedEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedResultEqual( BinaryEnum.A, ( "migrations.test_writer.BinaryEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedResultEqual( IntEnum.B, ("migrations.test_writer.IntEnum['B']", {"import migrations.test_writer"}), ) self.assertSerializedResultEqual( self.NestedEnum.A, ( "migrations.test_writer.WriterTests.NestedEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedEqual(self.NestedEnum.A) field = models.CharField( default=TextEnum.B, choices=[(m.value, m) for m in TextEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[" "('a-value', migrations.test_writer.TextEnum['A']), " "('value-b', migrations.test_writer.TextEnum['B'])], " "default=migrations.test_writer.TextEnum['B'])", ) field = models.CharField( default=TextTranslatedEnum.A, choices=[(m.value, m) for m in TextTranslatedEnum], ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[" "('a-value', migrations.test_writer.TextTranslatedEnum['A']), " "('value-b', migrations.test_writer.TextTranslatedEnum['B'])], " "default=migrations.test_writer.TextTranslatedEnum['A'])", ) field = models.CharField( default=BinaryEnum.B, choices=[(m.value, m) for m in BinaryEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[" "(b'a-value', migrations.test_writer.BinaryEnum['A']), " "(b'value-b', migrations.test_writer.BinaryEnum['B'])], " "default=migrations.test_writer.BinaryEnum['B'])", ) field = models.IntegerField( default=IntEnum.A, choices=[(m.value, m) for m in IntEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.IntegerField(choices=[" "(1, migrations.test_writer.IntEnum['A']), " "(2, migrations.test_writer.IntEnum['B'])], " "default=migrations.test_writer.IntEnum['A'])", ) def test_serialize_enum_flags(self): self.assertSerializedResultEqual( IntFlagEnum.A, ( "migrations.test_writer.IntFlagEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedResultEqual( IntFlagEnum.B, ( "migrations.test_writer.IntFlagEnum['B']", {"import migrations.test_writer"}, ), ) field = models.IntegerField( default=IntFlagEnum.A, choices=[(m.value, m) for m in IntFlagEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.IntegerField(choices=[" "(1, migrations.test_writer.IntFlagEnum['A']), " "(2, migrations.test_writer.IntFlagEnum['B'])], " "default=migrations.test_writer.IntFlagEnum['A'])", ) self.assertSerializedResultEqual( IntFlagEnum.A | IntFlagEnum.B, ( "migrations.test_writer.IntFlagEnum['A'] | " "migrations.test_writer.IntFlagEnum['B']", {"import migrations.test_writer"}, ), ) def test_serialize_choices(self): class TextChoices(models.TextChoices): A = "A", "A value" B = "B", "B value" class IntegerChoices(models.IntegerChoices): A = 1, "One" B = 2, "Two" class DateChoices(datetime.date, models.Choices): DATE_1 = 1969, 7, 20, "First date" DATE_2 = 1969, 11, 19, "Second date" self.assertSerializedResultEqual(TextChoices.A, ("'A'", set())) self.assertSerializedResultEqual(IntegerChoices.A, ("1", set())) self.assertSerializedResultEqual( DateChoices.DATE_1, ("datetime.date(1969, 7, 20)", {"import datetime"}), ) field = models.CharField(default=TextChoices.B, choices=TextChoices) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[('A', 'A value'), ('B', 'B value')], " "default='B')", ) field = models.IntegerField(default=IntegerChoices.B, choices=IntegerChoices) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.IntegerField(choices=[(1, 'One'), (2, 'Two')], default=2)", ) field = models.DateField(default=DateChoices.DATE_2, choices=DateChoices) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.DateField(choices=[" "(datetime.date(1969, 7, 20), 'First date'), " "(datetime.date(1969, 11, 19), 'Second date')], " "default=datetime.date(1969, 11, 19))", ) def test_serialize_nested_class(self): for nested_cls in [self.NestedEnum, self.NestedChoices]: cls_name = nested_cls.__name__ with self.subTest(cls_name): self.assertSerializedResultEqual( nested_cls, ( "migrations.test_writer.WriterTests.%s" % cls_name, {"import migrations.test_writer"}, ), ) def test_serialize_uuid(self): self.assertSerializedEqual(uuid.uuid1()) self.assertSerializedEqual(uuid.uuid4()) uuid_a = uuid.UUID("5c859437-d061-4847-b3f7-e6b78852f8c8") uuid_b = uuid.UUID("c7853ec1-2ea3-4359-b02d-b54e8f1bcee2") self.assertSerializedResultEqual( uuid_a, ("uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8')", {"import uuid"}), ) self.assertSerializedResultEqual( uuid_b, ("uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2')", {"import uuid"}), ) field = models.UUIDField( choices=((uuid_a, "UUID A"), (uuid_b, "UUID B")), default=uuid_a ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.UUIDField(choices=[" "(uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'), 'UUID A'), " "(uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2'), 'UUID B')], " "default=uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'))", ) def test_serialize_pathlib(self): # Pure path objects work in all platforms. self.assertSerializedEqual(pathlib.PurePosixPath()) self.assertSerializedEqual(pathlib.PureWindowsPath()) path = pathlib.PurePosixPath("/path/file.txt") expected = ("pathlib.PurePosixPath('/path/file.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) path = pathlib.PureWindowsPath("A:\\File.txt") expected = ("pathlib.PureWindowsPath('A:/File.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) # Concrete path objects work on supported platforms. if sys.platform == "win32": self.assertSerializedEqual(pathlib.WindowsPath.cwd()) path = pathlib.WindowsPath("A:\\File.txt") expected = ("pathlib.PureWindowsPath('A:/File.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) else: self.assertSerializedEqual(pathlib.PosixPath.cwd()) path = pathlib.PosixPath("/path/file.txt") expected = ("pathlib.PurePosixPath('/path/file.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) field = models.FilePathField(path=pathlib.PurePosixPath("/home/user")) string, imports = MigrationWriter.serialize(field) self.assertEqual( string, "models.FilePathField(path=pathlib.PurePosixPath('/home/user'))", ) self.assertIn("import pathlib", imports) def test_serialize_path_like(self): with os.scandir(os.path.dirname(__file__)) as entries: path_like = list(entries)[0] expected = (repr(path_like.path), {}) self.assertSerializedResultEqual(path_like, expected) field = models.FilePathField(path=path_like) string = MigrationWriter.serialize(field)[0] self.assertEqual(string, "models.FilePathField(path=%r)" % path_like.path) def test_serialize_functions(self): with self.assertRaisesMessage(ValueError, "Cannot serialize function: lambda"): self.assertSerializedEqual(lambda x: 42) self.assertSerializedEqual(models.SET_NULL) string, imports = MigrationWriter.serialize(models.SET(42)) self.assertEqual(string, "models.SET(42)") self.serialize_round_trip(models.SET(42)) def test_serialize_datetime(self): self.assertSerializedEqual(datetime.datetime.now()) self.assertSerializedEqual(datetime.datetime.now) self.assertSerializedEqual(datetime.datetime.today()) self.assertSerializedEqual(datetime.datetime.today) self.assertSerializedEqual(datetime.date.today()) self.assertSerializedEqual(datetime.date.today) self.assertSerializedEqual(datetime.datetime.now().time()) self.assertSerializedEqual( datetime.datetime(2014, 1, 1, 1, 1, tzinfo=get_default_timezone()) ) self.assertSerializedEqual( datetime.datetime(2013, 12, 31, 22, 1, tzinfo=get_fixed_timezone(180)) ) self.assertSerializedResultEqual( datetime.datetime(2014, 1, 1, 1, 1), ("datetime.datetime(2014, 1, 1, 1, 1)", {"import datetime"}), ) self.assertSerializedResultEqual( datetime.datetime(2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc), ( "datetime.datetime(2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc)", {"import datetime"}, ), ) self.assertSerializedResultEqual( datetime.datetime( 2012, 1, 1, 2, 1, tzinfo=zoneinfo.ZoneInfo("Europe/Paris") ), ( "datetime.datetime(2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc)", {"import datetime"}, ), ) def test_serialize_fields(self): self.assertSerializedFieldEqual(models.CharField(max_length=255)) self.assertSerializedResultEqual( models.CharField(max_length=255), ("models.CharField(max_length=255)", {"from django.db import models"}), ) self.assertSerializedFieldEqual(models.TextField(null=True, blank=True)) self.assertSerializedResultEqual( models.TextField(null=True, blank=True), ( "models.TextField(blank=True, null=True)", {"from django.db import models"}, ), ) def test_serialize_settings(self): self.assertSerializedEqual( SettingsReference(settings.AUTH_USER_MODEL, "AUTH_USER_MODEL") ) self.assertSerializedResultEqual( SettingsReference("someapp.model", "AUTH_USER_MODEL"), ("settings.AUTH_USER_MODEL", {"from django.conf import settings"}), ) def test_serialize_iterators(self): self.assertSerializedResultEqual( ((x, x * x) for x in range(3)), ("((0, 0), (1, 1), (2, 4))", set()) ) def test_serialize_compiled_regex(self): """ Make sure compiled regex can be serialized. """ regex = re.compile(r"^\w+$") self.assertSerializedEqual(regex) def test_serialize_class_based_validators(self): """ Ticket #22943: Test serialization of class-based validators, including compiled regexes. """ validator = RegexValidator(message="hello") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator(message='hello')" ) self.serialize_round_trip(validator) # Test with a compiled regex. validator = RegexValidator(regex=re.compile(r"^\w+$")) string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator(regex=re.compile('^\\\\w+$'))", ) self.serialize_round_trip(validator) # Test a string regex with flag validator = RegexValidator(r"^[0-9]+$", flags=re.S) string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator('^[0-9]+$', " "flags=re.RegexFlag['DOTALL'])", ) self.serialize_round_trip(validator) # Test message and code validator = RegexValidator("^[-a-zA-Z0-9_]+$", "Invalid", "invalid") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', " "'invalid')", ) self.serialize_round_trip(validator) # Test with a subclass. validator = EmailValidator(message="hello") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.EmailValidator(message='hello')" ) self.serialize_round_trip(validator) validator = deconstructible(path="migrations.test_writer.EmailValidator")( EmailValidator )(message="hello") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "migrations.test_writer.EmailValidator(message='hello')" ) validator = deconstructible(path="custom.EmailValidator")(EmailValidator)( message="hello" ) with self.assertRaisesMessage(ImportError, "No module named 'custom'"): MigrationWriter.serialize(validator) validator = deconstructible(path="django.core.validators.EmailValidator2")( EmailValidator )(message="hello") with self.assertRaisesMessage( ValueError, "Could not find object EmailValidator2 in django.core.validators.", ): MigrationWriter.serialize(validator) def test_serialize_complex_func_index(self): index = models.Index( models.Func("rating", function="ABS"), models.Case( models.When(name="special", then=models.Value("X")), default=models.Value("other"), ), models.ExpressionWrapper( models.F("pages"), output_field=models.IntegerField(), ), models.OrderBy(models.F("name").desc()), name="complex_func_index", ) string, imports = MigrationWriter.serialize(index) self.assertEqual( string, "models.Index(models.Func('rating', function='ABS'), " "models.Case(models.When(name='special', then=models.Value('X')), " "default=models.Value('other')), " "models.ExpressionWrapper(" "models.F('pages'), output_field=models.IntegerField()), " "models.OrderBy(models.OrderBy(models.F('name'), descending=True)), " "name='complex_func_index')", ) self.assertEqual(imports, {"from django.db import models"}) def test_serialize_empty_nonempty_tuple(self): """ Ticket #22679: makemigrations generates invalid code for (an empty tuple) default_permissions = () """ empty_tuple = () one_item_tuple = ("a",) many_items_tuple = ("a", "b", "c") self.assertSerializedEqual(empty_tuple) self.assertSerializedEqual(one_item_tuple) self.assertSerializedEqual(many_items_tuple) def test_serialize_range(self): string, imports = MigrationWriter.serialize(range(1, 5)) self.assertEqual(string, "range(1, 5)") self.assertEqual(imports, set()) def test_serialize_builtins(self): string, imports = MigrationWriter.serialize(range) self.assertEqual(string, "range") self.assertEqual(imports, set()) def test_serialize_unbound_method_reference(self): """An unbound method used within a class body can be serialized.""" self.serialize_round_trip(TestModel1.thing) def test_serialize_local_function_reference(self): """A reference in a local scope can't be serialized.""" class TestModel2: def upload_to(self): return "somewhere dynamic" thing = models.FileField(upload_to=upload_to) with self.assertRaisesMessage( ValueError, "Could not find function upload_to in migrations.test_writer" ): self.serialize_round_trip(TestModel2.thing) def test_serialize_managers(self): self.assertSerializedEqual(models.Manager()) self.assertSerializedResultEqual( FoodQuerySet.as_manager(), ( "migrations.models.FoodQuerySet.as_manager()", {"import migrations.models"}, ), ) self.assertSerializedEqual(FoodManager("a", "b")) self.assertSerializedEqual(FoodManager("x", "y", c=3, d=4)) def test_serialize_frozensets(self): self.assertSerializedEqual(frozenset()) self.assertSerializedEqual(frozenset("let it go")) def test_serialize_set(self): self.assertSerializedEqual(set()) self.assertSerializedResultEqual(set(), ("set()", set())) self.assertSerializedEqual({"a"}) self.assertSerializedResultEqual({"a"}, ("{'a'}", set())) def test_serialize_timedelta(self): self.assertSerializedEqual(datetime.timedelta()) self.assertSerializedEqual(datetime.timedelta(minutes=42)) def test_serialize_functools_partial(self): value = functools.partial(datetime.timedelta, 1, seconds=2) result = self.serialize_round_trip(value) self.assertEqual(result.func, value.func) self.assertEqual(result.args, value.args) self.assertEqual(result.keywords, value.keywords) def test_serialize_functools_partialmethod(self): value = functools.partialmethod(datetime.timedelta, 1, seconds=2) result = self.serialize_round_trip(value) self.assertIsInstance(result, functools.partialmethod) self.assertEqual(result.func, value.func) self.assertEqual(result.args, value.args) self.assertEqual(result.keywords, value.keywords) def test_serialize_type_none(self): self.assertSerializedEqual(NoneType) def test_serialize_type_model(self): self.assertSerializedEqual(models.Model) self.assertSerializedResultEqual( MigrationWriter.serialize(models.Model), ("('models.Model', {'from django.db import models'})", set()), ) def test_simple_migration(self): """ Tests serializing a simple migration. """ fields = { "charfield": models.DateTimeField(default=datetime.datetime.now), "datetimefield": models.DateTimeField(default=datetime.datetime.now), } options = { "verbose_name": "My model", "verbose_name_plural": "My models", } migration = type( "Migration", (migrations.Migration,), { "operations": [ migrations.CreateModel( "MyModel", tuple(fields.items()), options, (models.Model,) ), migrations.CreateModel( "MyModel2", tuple(fields.items()), bases=(models.Model,) ), migrations.CreateModel( name="MyModel3", fields=tuple(fields.items()), options=options, bases=(models.Model,), ), migrations.DeleteModel("MyModel"), migrations.AddField( "OtherModel", "datetimefield", fields["datetimefield"] ), ], "dependencies": [("testapp", "some_other_one")], }, ) writer = MigrationWriter(migration) output = writer.as_string() # We don't test the output formatting - that's too fragile. # Just make sure it runs for now, and that things look alright. result = self.safe_exec(output) self.assertIn("Migration", result) def test_migration_path(self): test_apps = [ "migrations.migrations_test_apps.normal", "migrations.migrations_test_apps.with_package_model", "migrations.migrations_test_apps.without_init_file", ] base_dir = os.path.dirname(os.path.dirname(__file__)) for app in test_apps: with self.modify_settings(INSTALLED_APPS={"append": app}): migration = migrations.Migration("0001_initial", app.split(".")[-1]) expected_path = os.path.join( base_dir, *(app.split(".") + ["migrations", "0001_initial.py"]) ) writer = MigrationWriter(migration) self.assertEqual(writer.path, expected_path) def test_custom_operation(self): migration = type( "Migration", (migrations.Migration,), { "operations": [ custom_migration_operations.operations.TestOperation(), custom_migration_operations.operations.CreateModel(), migrations.CreateModel("MyModel", (), {}, (models.Model,)), custom_migration_operations.more_operations.TestOperation(), ], "dependencies": [], }, ) writer = MigrationWriter(migration) output = writer.as_string() result = self.safe_exec(output) self.assertIn("custom_migration_operations", result) self.assertNotEqual( result["custom_migration_operations"].operations.TestOperation, result["custom_migration_operations"].more_operations.TestOperation, ) def test_sorted_imports(self): """ #24155 - Tests ordering of imports. """ migration = type( "Migration", (migrations.Migration,), { "operations": [ migrations.AddField( "mymodel", "myfield", models.DateTimeField( default=datetime.datetime( 2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc ), ), ), migrations.AddField( "mymodel", "myfield2", models.FloatField(default=time.time), ), ] }, ) writer = MigrationWriter(migration) output = writer.as_string() self.assertIn( "import datetime\nimport time\nfrom django.db import migrations, models\n", output, ) def test_migration_file_header_comments(self): """ Test comments at top of file. """ migration = type("Migration", (migrations.Migration,), {"operations": []}) dt = datetime.datetime(2015, 7, 31, 4, 40, 0, 0, tzinfo=datetime.timezone.utc) with mock.patch("django.db.migrations.writer.now", lambda: dt): for include_header in (True, False): with self.subTest(include_header=include_header): writer = MigrationWriter(migration, include_header) output = writer.as_string() self.assertEqual( include_header, output.startswith( "# Generated by Django %s on 2015-07-31 04:40\n\n" % get_version() ), ) if not include_header: # Make sure the output starts with something that's not # a comment or indentation or blank line self.assertRegex( output.splitlines(keepends=True)[0], r"^[^#\s]+" ) def test_models_import_omitted(self): """ django.db.models shouldn't be imported if unused. """ migration = type( "Migration", (migrations.Migration,), { "operations": [ migrations.AlterModelOptions( name="model", options={ "verbose_name": "model", "verbose_name_plural": "models", }, ), ] }, ) writer = MigrationWriter(migration) output = writer.as_string() self.assertIn("from django.db import migrations\n", output) def test_deconstruct_class_arguments(self): # Yes, it doesn't make sense to use a class as a default for a # CharField. It does make sense for custom fields though, for example # an enumfield that takes the enum class as an argument. string = MigrationWriter.serialize( models.CharField(default=DeconstructibleInstances) )[0] self.assertEqual( string, "models.CharField(default=migrations.test_writer.DeconstructibleInstances)", ) def test_register_serializer(self): class ComplexSerializer(BaseSerializer): def serialize(self): return "complex(%r)" % self.value, {} MigrationWriter.register_serializer(complex, ComplexSerializer) self.assertSerializedEqual(complex(1, 2)) MigrationWriter.unregister_serializer(complex) with self.assertRaisesMessage(ValueError, "Cannot serialize: (1+2j)"): self.assertSerializedEqual(complex(1, 2)) def test_register_non_serializer(self): with self.assertRaisesMessage( ValueError, "'TestModel1' must inherit from 'BaseSerializer'." ): MigrationWriter.register_serializer(complex, TestModel1)
24194fae8769867187e1d519f96ecd33eade9a8ebff8d68bc72923e61f87e559
from unittest import mock, skipUnless from django.conf.global_settings import PASSWORD_HASHERS from django.contrib.auth.hashers import ( UNUSABLE_PASSWORD_PREFIX, UNUSABLE_PASSWORD_SUFFIX_LENGTH, BasePasswordHasher, BCryptPasswordHasher, BCryptSHA256PasswordHasher, MD5PasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1PasswordHasher, ScryptPasswordHasher, check_password, get_hasher, identify_hasher, is_password_usable, make_password, ) from django.test import SimpleTestCase, ignore_warnings from django.test.utils import override_settings from django.utils.deprecation import RemovedInDjango51Warning try: import bcrypt except ImportError: bcrypt = None try: import argon2 except ImportError: argon2 = None # scrypt requires OpenSSL 1.1+ try: import hashlib scrypt = hashlib.scrypt except ImportError: scrypt = None class PBKDF2SingleIterationHasher(PBKDF2PasswordHasher): iterations = 1 @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) class TestUtilsHashPass(SimpleTestCase): def test_simple(self): encoded = make_password("lètmein") self.assertTrue(encoded.startswith("pbkdf2_sha256$")) self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) # Blank passwords blank_encoded = make_password("") self.assertTrue(blank_encoded.startswith("pbkdf2_sha256$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) def test_bytes(self): encoded = make_password(b"bytes_password") self.assertTrue(encoded.startswith("pbkdf2_sha256$")) self.assertIs(is_password_usable(encoded), True) self.assertIs(check_password(b"bytes_password", encoded), True) def test_invalid_password(self): msg = "Password must be a string or bytes, got int." with self.assertRaisesMessage(TypeError, msg): make_password(1) def test_pbkdf2(self): encoded = make_password("lètmein", "seasalt", "pbkdf2_sha256") self.assertEqual( encoded, "pbkdf2_sha256$720000$seasalt$eDupbcisD1UuIiou3hMuMu8oe/XwnpDw45r6AA5iv0E=", ) self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "pbkdf2_sha256") # Blank passwords blank_encoded = make_password("", "seasalt", "pbkdf2_sha256") self.assertTrue(blank_encoded.startswith("pbkdf2_sha256$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) # Salt entropy check. hasher = get_hasher("pbkdf2_sha256") encoded_weak_salt = make_password("lètmein", "iodizedsalt", "pbkdf2_sha256") encoded_strong_salt = make_password("lètmein", hasher.salt(), "pbkdf2_sha256") self.assertIs(hasher.must_update(encoded_weak_salt), True) self.assertIs(hasher.must_update(encoded_strong_salt), False) @ignore_warnings(category=RemovedInDjango51Warning) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.SHA1PasswordHasher"] ) def test_sha1(self): encoded = make_password("lètmein", "seasalt", "sha1") self.assertEqual( encoded, "sha1$seasalt$cff36ea83f5706ce9aa7454e63e431fc726b2dc8" ) self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "sha1") # Blank passwords blank_encoded = make_password("", "seasalt", "sha1") self.assertTrue(blank_encoded.startswith("sha1$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) # Salt entropy check. hasher = get_hasher("sha1") encoded_weak_salt = make_password("lètmein", "iodizedsalt", "sha1") encoded_strong_salt = make_password("lètmein", hasher.salt(), "sha1") self.assertIs(hasher.must_update(encoded_weak_salt), True) self.assertIs(hasher.must_update(encoded_strong_salt), False) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.SHA1PasswordHasher"] ) def test_sha1_deprecation_warning(self): msg = "django.contrib.auth.hashers.SHA1PasswordHasher is deprecated." with self.assertRaisesMessage(RemovedInDjango51Warning, msg): get_hasher("sha1") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.MD5PasswordHasher"] ) def test_md5(self): encoded = make_password("lètmein", "seasalt", "md5") self.assertEqual(encoded, "md5$seasalt$3f86d0d3d465b7b458c231bf3555c0e3") self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "md5") # Blank passwords blank_encoded = make_password("", "seasalt", "md5") self.assertTrue(blank_encoded.startswith("md5$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) # Salt entropy check. hasher = get_hasher("md5") encoded_weak_salt = make_password("lètmein", "iodizedsalt", "md5") encoded_strong_salt = make_password("lètmein", hasher.salt(), "md5") self.assertIs(hasher.must_update(encoded_weak_salt), True) self.assertIs(hasher.must_update(encoded_strong_salt), False) @ignore_warnings(category=RemovedInDjango51Warning) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedMD5PasswordHasher"] ) def test_unsalted_md5(self): encoded = make_password("lètmein", "", "unsalted_md5") self.assertEqual(encoded, "88a434c88cca4e900f7874cd98123f43") self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "unsalted_md5") # Alternate unsalted syntax alt_encoded = "md5$$%s" % encoded self.assertTrue(is_password_usable(alt_encoded)) self.assertTrue(check_password("lètmein", alt_encoded)) self.assertFalse(check_password("lètmeinz", alt_encoded)) # Blank passwords blank_encoded = make_password("", "", "unsalted_md5") self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) @ignore_warnings(category=RemovedInDjango51Warning) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedMD5PasswordHasher"] ) def test_unsalted_md5_encode_invalid_salt(self): hasher = get_hasher("unsalted_md5") msg = "salt must be empty." with self.assertRaisesMessage(ValueError, msg): hasher.encode("password", salt="salt") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedMD5PasswordHasher"] ) def test_unsalted_md5_deprecation_warning(self): msg = "django.contrib.auth.hashers.UnsaltedMD5PasswordHasher is deprecated." with self.assertRaisesMessage(RemovedInDjango51Warning, msg): get_hasher("unsalted_md5") @ignore_warnings(category=RemovedInDjango51Warning) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher"] ) def test_unsalted_sha1(self): encoded = make_password("lètmein", "", "unsalted_sha1") self.assertEqual(encoded, "sha1$$6d138ca3ae545631b3abd71a4f076ce759c5700b") self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "unsalted_sha1") # Raw SHA1 isn't acceptable alt_encoded = encoded[6:] self.assertFalse(check_password("lètmein", alt_encoded)) # Blank passwords blank_encoded = make_password("", "", "unsalted_sha1") self.assertTrue(blank_encoded.startswith("sha1$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) @ignore_warnings(category=RemovedInDjango51Warning) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher"] ) def test_unsalted_sha1_encode_invalid_salt(self): hasher = get_hasher("unsalted_sha1") msg = "salt must be empty." with self.assertRaisesMessage(ValueError, msg): hasher.encode("password", salt="salt") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher"] ) def test_unsalted_sha1_deprecation_warning(self): msg = "django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher is deprecated." with self.assertRaisesMessage(RemovedInDjango51Warning, msg): get_hasher("unsalted_sha1") @skipUnless(bcrypt, "bcrypt not installed") def test_bcrypt_sha256(self): encoded = make_password("lètmein", hasher="bcrypt_sha256") self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith("bcrypt_sha256$")) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt_sha256") # password truncation no longer works password = ( "VSK0UYV6FFQVZ0KG88DYN9WADAADZO1CTSIVDJUNZSUML6IBX7LN7ZS3R5" "JGB3RGZ7VI7G7DJQ9NI8BQFSRPTG6UWTTVESA5ZPUN" ) encoded = make_password(password, hasher="bcrypt_sha256") self.assertTrue(check_password(password, encoded)) self.assertFalse(check_password(password[:72], encoded)) # Blank passwords blank_encoded = make_password("", hasher="bcrypt_sha256") self.assertTrue(blank_encoded.startswith("bcrypt_sha256$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) @skipUnless(bcrypt, "bcrypt not installed") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.BCryptPasswordHasher"] ) def test_bcrypt(self): encoded = make_password("lètmein", hasher="bcrypt") self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith("bcrypt$")) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt") # Blank passwords blank_encoded = make_password("", hasher="bcrypt") self.assertTrue(blank_encoded.startswith("bcrypt$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) @skipUnless(bcrypt, "bcrypt not installed") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.BCryptPasswordHasher"] ) def test_bcrypt_upgrade(self): hasher = get_hasher("bcrypt") self.assertEqual("bcrypt", hasher.algorithm) self.assertNotEqual(hasher.rounds, 4) old_rounds = hasher.rounds try: # Generate a password with 4 rounds. hasher.rounds = 4 encoded = make_password("letmein", hasher="bcrypt") rounds = hasher.safe_summary(encoded)["work factor"] self.assertEqual(rounds, 4) state = {"upgraded": False} def setter(password): state["upgraded"] = True # No upgrade is triggered. self.assertTrue(check_password("letmein", encoded, setter, "bcrypt")) self.assertFalse(state["upgraded"]) # Revert to the old rounds count and ... hasher.rounds = old_rounds # ... check if the password would get updated to the new count. self.assertTrue(check_password("letmein", encoded, setter, "bcrypt")) self.assertTrue(state["upgraded"]) finally: hasher.rounds = old_rounds @skipUnless(bcrypt, "bcrypt not installed") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.BCryptPasswordHasher"] ) def test_bcrypt_harden_runtime(self): hasher = get_hasher("bcrypt") self.assertEqual("bcrypt", hasher.algorithm) with mock.patch.object(hasher, "rounds", 4): encoded = make_password("letmein", hasher="bcrypt") with mock.patch.object(hasher, "rounds", 6), mock.patch.object( hasher, "encode", side_effect=hasher.encode ): hasher.harden_runtime("wrong_password", encoded) # Increasing rounds from 4 to 6 means an increase of 4 in workload, # therefore hardening should run 3 times to make the timing the # same (the original encode() call already ran once). self.assertEqual(hasher.encode.call_count, 3) # Get the original salt (includes the original workload factor) algorithm, data = encoded.split("$", 1) expected_call = (("wrong_password", data[:29].encode()),) self.assertEqual(hasher.encode.call_args_list, [expected_call] * 3) def test_unusable(self): encoded = make_password(None) self.assertEqual( len(encoded), len(UNUSABLE_PASSWORD_PREFIX) + UNUSABLE_PASSWORD_SUFFIX_LENGTH, ) self.assertFalse(is_password_usable(encoded)) self.assertFalse(check_password(None, encoded)) self.assertFalse(check_password(encoded, encoded)) self.assertFalse(check_password(UNUSABLE_PASSWORD_PREFIX, encoded)) self.assertFalse(check_password("", encoded)) self.assertFalse(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) with self.assertRaisesMessage(ValueError, "Unknown password hashing algorithm"): identify_hasher(encoded) # Assert that the unusable passwords actually contain a random part. # This might fail one day due to a hash collision. self.assertNotEqual(encoded, make_password(None), "Random password collision?") def test_unspecified_password(self): """ Makes sure specifying no plain password with a valid encoded password returns `False`. """ self.assertFalse(check_password(None, make_password("lètmein"))) def test_bad_algorithm(self): msg = ( "Unknown password hashing algorithm '%s'. Did you specify it in " "the PASSWORD_HASHERS setting?" ) with self.assertRaisesMessage(ValueError, msg % "lolcat"): make_password("lètmein", hasher="lolcat") with self.assertRaisesMessage(ValueError, msg % "lolcat"): identify_hasher("lolcat$salt$hash") def test_is_password_usable(self): passwords = ("lètmein_badencoded", "", None) for password in passwords: with self.subTest(password=password): self.assertIs(is_password_usable(password), True) def test_low_level_pbkdf2(self): hasher = PBKDF2PasswordHasher() encoded = hasher.encode("lètmein", "seasalt2") self.assertEqual( encoded, "pbkdf2_sha256$720000$" "seasalt2$e8hbsPnTo9qWhT3xYfKWoRth0h0J3360yb/tipPhPtY=", ) self.assertTrue(hasher.verify("lètmein", encoded)) def test_low_level_pbkdf2_sha1(self): hasher = PBKDF2SHA1PasswordHasher() encoded = hasher.encode("lètmein", "seasalt2") self.assertEqual( encoded, "pbkdf2_sha1$720000$seasalt2$2DDbzziqCtfldrRSNAaF8oA9OMw=" ) self.assertTrue(hasher.verify("lètmein", encoded)) @skipUnless(bcrypt, "bcrypt not installed") def test_bcrypt_salt_check(self): hasher = BCryptPasswordHasher() encoded = hasher.encode("lètmein", hasher.salt()) self.assertIs(hasher.must_update(encoded), False) @skipUnless(bcrypt, "bcrypt not installed") def test_bcryptsha256_salt_check(self): hasher = BCryptSHA256PasswordHasher() encoded = hasher.encode("lètmein", hasher.salt()) self.assertIs(hasher.must_update(encoded), False) @override_settings( PASSWORD_HASHERS=[ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.MD5PasswordHasher", ], ) def test_upgrade(self): self.assertEqual("pbkdf2_sha256", get_hasher("default").algorithm) for algo in ("pbkdf2_sha1", "md5"): with self.subTest(algo=algo): encoded = make_password("lètmein", hasher=algo) state = {"upgraded": False} def setter(password): state["upgraded"] = True self.assertTrue(check_password("lètmein", encoded, setter)) self.assertTrue(state["upgraded"]) def test_no_upgrade(self): encoded = make_password("lètmein") state = {"upgraded": False} def setter(): state["upgraded"] = True self.assertFalse(check_password("WRONG", encoded, setter)) self.assertFalse(state["upgraded"]) @override_settings( PASSWORD_HASHERS=[ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher", "django.contrib.auth.hashers.MD5PasswordHasher", ], ) def test_no_upgrade_on_incorrect_pass(self): self.assertEqual("pbkdf2_sha256", get_hasher("default").algorithm) for algo in ("pbkdf2_sha1", "md5"): with self.subTest(algo=algo): encoded = make_password("lètmein", hasher=algo) state = {"upgraded": False} def setter(): state["upgraded"] = True self.assertFalse(check_password("WRONG", encoded, setter)) self.assertFalse(state["upgraded"]) def test_pbkdf2_upgrade(self): hasher = get_hasher("default") self.assertEqual("pbkdf2_sha256", hasher.algorithm) self.assertNotEqual(hasher.iterations, 1) old_iterations = hasher.iterations try: # Generate a password with 1 iteration. hasher.iterations = 1 encoded = make_password("letmein") algo, iterations, salt, hash = encoded.split("$", 3) self.assertEqual(iterations, "1") state = {"upgraded": False} def setter(password): state["upgraded"] = True # No upgrade is triggered self.assertTrue(check_password("letmein", encoded, setter)) self.assertFalse(state["upgraded"]) # Revert to the old iteration count and ... hasher.iterations = old_iterations # ... check if the password would get updated to the new iteration count. self.assertTrue(check_password("letmein", encoded, setter)) self.assertTrue(state["upgraded"]) finally: hasher.iterations = old_iterations def test_pbkdf2_harden_runtime(self): hasher = get_hasher("default") self.assertEqual("pbkdf2_sha256", hasher.algorithm) with mock.patch.object(hasher, "iterations", 1): encoded = make_password("letmein") with mock.patch.object(hasher, "iterations", 6), mock.patch.object( hasher, "encode", side_effect=hasher.encode ): hasher.harden_runtime("wrong_password", encoded) # Encode should get called once ... self.assertEqual(hasher.encode.call_count, 1) # ... with the original salt and 5 iterations. algorithm, iterations, salt, hash = encoded.split("$", 3) expected_call = (("wrong_password", salt, 5),) self.assertEqual(hasher.encode.call_args, expected_call) def test_pbkdf2_upgrade_new_hasher(self): hasher = get_hasher("default") self.assertEqual("pbkdf2_sha256", hasher.algorithm) self.assertNotEqual(hasher.iterations, 1) state = {"upgraded": False} def setter(password): state["upgraded"] = True with self.settings( PASSWORD_HASHERS=["auth_tests.test_hashers.PBKDF2SingleIterationHasher"] ): encoded = make_password("letmein") algo, iterations, salt, hash = encoded.split("$", 3) self.assertEqual(iterations, "1") # No upgrade is triggered self.assertTrue(check_password("letmein", encoded, setter)) self.assertFalse(state["upgraded"]) # Revert to the old iteration count and check if the password would get # updated to the new iteration count. with self.settings( PASSWORD_HASHERS=[ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "auth_tests.test_hashers.PBKDF2SingleIterationHasher", ] ): self.assertTrue(check_password("letmein", encoded, setter)) self.assertTrue(state["upgraded"]) def test_check_password_calls_harden_runtime(self): hasher = get_hasher("default") encoded = make_password("letmein") with mock.patch.object(hasher, "harden_runtime"), mock.patch.object( hasher, "must_update", return_value=True ): # Correct password supplied, no hardening needed check_password("letmein", encoded) self.assertEqual(hasher.harden_runtime.call_count, 0) # Wrong password supplied, hardening needed check_password("wrong_password", encoded) self.assertEqual(hasher.harden_runtime.call_count, 1) def test_encode_invalid_salt(self): hasher_classes = [ MD5PasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1PasswordHasher, ScryptPasswordHasher, ] msg = "salt must be provided and cannot contain $." for hasher_class in hasher_classes: hasher = hasher_class() for salt in [None, "", "sea$salt"]: with self.subTest(hasher_class.__name__, salt=salt): with self.assertRaisesMessage(ValueError, msg): hasher.encode("password", salt) def test_encode_password_required(self): hasher_classes = [ MD5PasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1PasswordHasher, ScryptPasswordHasher, ] msg = "password must be provided." for hasher_class in hasher_classes: hasher = hasher_class() with self.subTest(hasher_class.__name__): with self.assertRaisesMessage(TypeError, msg): hasher.encode(None, "seasalt") class BasePasswordHasherTests(SimpleTestCase): not_implemented_msg = "subclasses of BasePasswordHasher must provide %s() method" def setUp(self): self.hasher = BasePasswordHasher() def test_load_library_no_algorithm(self): msg = "Hasher 'BasePasswordHasher' doesn't specify a library attribute" with self.assertRaisesMessage(ValueError, msg): self.hasher._load_library() def test_load_library_importerror(self): PlainHasher = type( "PlainHasher", (BasePasswordHasher,), {"algorithm": "plain", "library": "plain"}, ) msg = "Couldn't load 'PlainHasher' algorithm library: No module named 'plain'" with self.assertRaisesMessage(ValueError, msg): PlainHasher()._load_library() def test_attributes(self): self.assertIsNone(self.hasher.algorithm) self.assertIsNone(self.hasher.library) def test_encode(self): msg = self.not_implemented_msg % "an encode" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.encode("password", "salt") def test_decode(self): msg = self.not_implemented_msg % "a decode" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.decode("encoded") def test_harden_runtime(self): msg = ( "subclasses of BasePasswordHasher should provide a harden_runtime() method" ) with self.assertWarnsMessage(Warning, msg): self.hasher.harden_runtime("password", "encoded") def test_must_update(self): self.assertIs(self.hasher.must_update("encoded"), False) def test_safe_summary(self): msg = self.not_implemented_msg % "a safe_summary" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.safe_summary("encoded") def test_verify(self): msg = self.not_implemented_msg % "a verify" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.verify("password", "encoded") @skipUnless(argon2, "argon2-cffi not installed") @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) class TestUtilsHashPassArgon2(SimpleTestCase): def test_argon2(self): encoded = make_password("lètmein", hasher="argon2") self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith("argon2$argon2id$")) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "argon2") # Blank passwords blank_encoded = make_password("", hasher="argon2") self.assertTrue(blank_encoded.startswith("argon2$argon2id$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) # Old hashes without version attribute encoded = ( "argon2$argon2i$m=8,t=1,p=1$c29tZXNhbHQ$gwQOXSNhxiOxPOA0+PY10P9QFO" "4NAYysnqRt1GSQLE55m+2GYDt9FEjPMHhP2Cuf0nOEXXMocVrsJAtNSsKyfg" ) self.assertTrue(check_password("secret", encoded)) self.assertFalse(check_password("wrong", encoded)) # Old hashes with version attribute. encoded = "argon2$argon2i$v=19$m=8,t=1,p=1$c2FsdHNhbHQ$YC9+jJCrQhs5R6db7LlN8Q" self.assertIs(check_password("secret", encoded), True) self.assertIs(check_password("wrong", encoded), False) # Salt entropy check. hasher = get_hasher("argon2") encoded_weak_salt = make_password("lètmein", "iodizedsalt", "argon2") encoded_strong_salt = make_password("lètmein", hasher.salt(), "argon2") self.assertIs(hasher.must_update(encoded_weak_salt), True) self.assertIs(hasher.must_update(encoded_strong_salt), False) def test_argon2_decode(self): salt = "abcdefghijk" encoded = make_password("lètmein", salt=salt, hasher="argon2") hasher = get_hasher("argon2") decoded = hasher.decode(encoded) self.assertEqual(decoded["memory_cost"], hasher.memory_cost) self.assertEqual(decoded["parallelism"], hasher.parallelism) self.assertEqual(decoded["salt"], salt) self.assertEqual(decoded["time_cost"], hasher.time_cost) def test_argon2_upgrade(self): self._test_argon2_upgrade("time_cost", "time cost", 1) self._test_argon2_upgrade("memory_cost", "memory cost", 64) self._test_argon2_upgrade("parallelism", "parallelism", 1) def test_argon2_version_upgrade(self): hasher = get_hasher("argon2") state = {"upgraded": False} encoded = ( "argon2$argon2id$v=19$m=102400,t=2,p=8$Y041dExhNkljRUUy$TMa6A8fPJh" "CAUXRhJXCXdw" ) def setter(password): state["upgraded"] = True old_m = hasher.memory_cost old_t = hasher.time_cost old_p = hasher.parallelism try: hasher.memory_cost = 8 hasher.time_cost = 1 hasher.parallelism = 1 self.assertTrue(check_password("secret", encoded, setter, "argon2")) self.assertTrue(state["upgraded"]) finally: hasher.memory_cost = old_m hasher.time_cost = old_t hasher.parallelism = old_p def _test_argon2_upgrade(self, attr, summary_key, new_value): hasher = get_hasher("argon2") self.assertEqual("argon2", hasher.algorithm) self.assertNotEqual(getattr(hasher, attr), new_value) old_value = getattr(hasher, attr) try: # Generate hash with attr set to 1 setattr(hasher, attr, new_value) encoded = make_password("letmein", hasher="argon2") attr_value = hasher.safe_summary(encoded)[summary_key] self.assertEqual(attr_value, new_value) state = {"upgraded": False} def setter(password): state["upgraded"] = True # No upgrade is triggered. self.assertTrue(check_password("letmein", encoded, setter, "argon2")) self.assertFalse(state["upgraded"]) # Revert to the old rounds count and ... setattr(hasher, attr, old_value) # ... check if the password would get updated to the new count. self.assertTrue(check_password("letmein", encoded, setter, "argon2")) self.assertTrue(state["upgraded"]) finally: setattr(hasher, attr, old_value) @skipUnless(scrypt, "scrypt not available") @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) class TestUtilsHashPassScrypt(SimpleTestCase): def test_scrypt(self): encoded = make_password("lètmein", "seasalt", "scrypt") self.assertEqual( encoded, "scrypt$16384$seasalt$8$1$Qj3+9PPyRjSJIebHnG81TMjsqtaIGxNQG/aEB/NY" "afTJ7tibgfYz71m0ldQESkXFRkdVCBhhY8mx7rQwite/Pw==", ) self.assertIs(is_password_usable(encoded), True) self.assertIs(check_password("lètmein", encoded), True) self.assertIs(check_password("lètmeinz", encoded), False) self.assertEqual(identify_hasher(encoded).algorithm, "scrypt") # Blank passwords. blank_encoded = make_password("", "seasalt", "scrypt") self.assertIs(blank_encoded.startswith("scrypt$"), True) self.assertIs(is_password_usable(blank_encoded), True) self.assertIs(check_password("", blank_encoded), True) self.assertIs(check_password(" ", blank_encoded), False) def test_scrypt_decode(self): encoded = make_password("lètmein", "seasalt", "scrypt") hasher = get_hasher("scrypt") decoded = hasher.decode(encoded) tests = [ ("block_size", hasher.block_size), ("parallelism", hasher.parallelism), ("salt", "seasalt"), ("work_factor", hasher.work_factor), ] for key, excepted in tests: with self.subTest(key=key): self.assertEqual(decoded[key], excepted) def _test_scrypt_upgrade(self, attr, summary_key, new_value): hasher = get_hasher("scrypt") self.assertEqual(hasher.algorithm, "scrypt") self.assertNotEqual(getattr(hasher, attr), new_value) old_value = getattr(hasher, attr) try: # Generate hash with attr set to the new value. setattr(hasher, attr, new_value) encoded = make_password("lètmein", "seasalt", "scrypt") attr_value = hasher.safe_summary(encoded)[summary_key] self.assertEqual(attr_value, new_value) state = {"upgraded": False} def setter(password): state["upgraded"] = True # No update is triggered. self.assertIs(check_password("lètmein", encoded, setter, "scrypt"), True) self.assertIs(state["upgraded"], False) # Revert to the old value. setattr(hasher, attr, old_value) # Password is updated. self.assertIs(check_password("lètmein", encoded, setter, "scrypt"), True) self.assertIs(state["upgraded"], True) finally: setattr(hasher, attr, old_value) def test_scrypt_upgrade(self): tests = [ ("work_factor", "work factor", 2**11), ("block_size", "block size", 10), ("parallelism", "parallelism", 2), ] for attr, summary_key, new_value in tests: with self.subTest(attr=attr): self._test_scrypt_upgrade(attr, summary_key, new_value)
ffbbecd410db241ce907f6a685a2332b5c31348d716e50b2a379de1cdb0cb16b
import os import sys import time import unittest from django.core.files.base import ContentFile from django.core.files.storage import InMemoryStorage from django.core.files.uploadedfile import TemporaryUploadedFile from django.test import SimpleTestCase, override_settings class MemoryStorageIOTests(unittest.TestCase): def setUp(self): self.storage = InMemoryStorage() def test_write_string(self): with self.storage.open("file.txt", "w") as fd: fd.write("hello") with self.storage.open("file.txt", "r") as fd: self.assertEqual(fd.read(), "hello") with self.storage.open("file.dat", "wb") as fd: fd.write(b"hello") with self.storage.open("file.dat", "rb") as fd: self.assertEqual(fd.read(), b"hello") def test_convert_str_to_bytes_and_back(self): """InMemoryStorage handles conversion from str to bytes and back.""" with self.storage.open("file.txt", "w") as fd: fd.write("hello") with self.storage.open("file.txt", "rb") as fd: self.assertEqual(fd.read(), b"hello") with self.storage.open("file.dat", "wb") as fd: fd.write(b"hello") with self.storage.open("file.dat", "r") as fd: self.assertEqual(fd.read(), "hello") def test_open_missing_file(self): self.assertRaises(FileNotFoundError, self.storage.open, "missing.txt") def test_open_dir_as_file(self): with self.storage.open("a/b/file.txt", "w") as fd: fd.write("hello") self.assertRaises(IsADirectoryError, self.storage.open, "a/b") def test_file_saving(self): self.storage.save("file.txt", ContentFile("test")) self.assertEqual(self.storage.open("file.txt", "r").read(), "test") self.storage.save("file.dat", ContentFile(b"test")) self.assertEqual(self.storage.open("file.dat", "rb").read(), b"test") @unittest.skipIf( sys.platform == "win32", "Windows doesn't support moving open files." ) def test_removing_temporary_file_after_save(self): """A temporary file is removed when saved into storage.""" with TemporaryUploadedFile("test", "text/plain", 1, "utf8") as file: self.storage.save("test.txt", file) self.assertFalse(os.path.exists(file.temporary_file_path())) def test_large_file_saving(self): large_file = ContentFile("A" * ContentFile.DEFAULT_CHUNK_SIZE * 3) self.storage.save("file.txt", large_file) def test_file_size(self): """ File size is equal to the size of bytes-encoded version of the saved data. """ self.storage.save("file.txt", ContentFile("test")) self.assertEqual(self.storage.size("file.txt"), 4) # A unicode char encoded to UTF-8 takes 2 bytes. self.storage.save("unicode_file.txt", ContentFile("è")) self.assertEqual(self.storage.size("unicode_file.txt"), 2) self.storage.save("file.dat", ContentFile(b"\xf1\xf1")) self.assertEqual(self.storage.size("file.dat"), 2) def test_listdir(self): self.assertEqual(self.storage.listdir(""), ([], [])) self.storage.save("file_a.txt", ContentFile("test")) self.storage.save("file_b.txt", ContentFile("test")) self.storage.save("dir/file_c.txt", ContentFile("test")) dirs, files = self.storage.listdir("") self.assertEqual(sorted(files), ["file_a.txt", "file_b.txt"]) self.assertEqual(dirs, ["dir"]) def test_list_relative_path(self): self.storage.save("a/file.txt", ContentFile("test")) _dirs, files = self.storage.listdir("./a/./.") self.assertEqual(files, ["file.txt"]) def test_exists(self): self.storage.save("dir/subdir/file.txt", ContentFile("test")) self.assertTrue(self.storage.exists("dir")) self.assertTrue(self.storage.exists("dir/subdir")) self.assertTrue(self.storage.exists("dir/subdir/file.txt")) def test_delete(self): """Deletion handles both files and directory trees.""" self.storage.save("dir/subdir/file.txt", ContentFile("test")) self.storage.save("dir/subdir/other_file.txt", ContentFile("test")) self.assertTrue(self.storage.exists("dir/subdir/file.txt")) self.assertTrue(self.storage.exists("dir/subdir/other_file.txt")) self.storage.delete("dir/subdir/other_file.txt") self.assertFalse(self.storage.exists("dir/subdir/other_file.txt")) self.storage.delete("dir/subdir") self.assertFalse(self.storage.exists("dir/subdir/file.txt")) self.assertFalse(self.storage.exists("dir/subdir")) def test_delete_missing_file(self): self.storage.delete("missing_file.txt") self.storage.delete("missing_dir/missing_file.txt") def test_file_node_cannot_have_children(self): """Navigate to children of a file node raises FileExistsError.""" self.storage.save("file.txt", ContentFile("test")) self.assertRaises(FileExistsError, self.storage.listdir, "file.txt/child_dir") self.assertRaises( FileExistsError, self.storage.save, "file.txt/child_file.txt", ContentFile("test"), ) @override_settings(MEDIA_URL=None) def test_url(self): self.assertRaises(ValueError, self.storage.url, ("file.txt",)) storage = InMemoryStorage(base_url="http://www.example.com") self.assertEqual(storage.url("file.txt"), "http://www.example.com/file.txt") def test_url_with_none_filename(self): storage = InMemoryStorage(base_url="/test_media_url/") self.assertEqual(storage.url(None), "/test_media_url/") class MemoryStorageTimesTests(unittest.TestCase): def setUp(self): self.storage = InMemoryStorage() def test_file_modified_time(self): """ File modified time should change after file changing """ self.storage.save("file.txt", ContentFile("test")) modified_time = self.storage.get_modified_time("file.txt") time.sleep(0.1) with self.storage.open("file.txt", "w") as fd: fd.write("new content") new_modified_time = self.storage.get_modified_time("file.txt") self.assertTrue(new_modified_time > modified_time) def test_file_accessed_time(self): """File accessed time should change after consecutive opening.""" self.storage.save("file.txt", ContentFile("test")) accessed_time = self.storage.get_accessed_time("file.txt") time.sleep(0.1) self.storage.open("file.txt", "r") new_accessed_time = self.storage.get_accessed_time("file.txt") self.assertGreater(new_accessed_time, accessed_time) def test_file_created_time(self): """File creation time should not change after I/O operations.""" self.storage.save("file.txt", ContentFile("test")) created_time = self.storage.get_created_time("file.txt") time.sleep(0.1) # File opening doesn't change creation time. file = self.storage.open("file.txt", "r") after_open_created_time = self.storage.get_created_time("file.txt") self.assertEqual(after_open_created_time, created_time) # Writing to a file doesn't change its creation time. file.write("New test") self.storage.save("file.txt", file) after_write_created_time = self.storage.get_created_time("file.txt") self.assertEqual(after_write_created_time, created_time) def test_directory_times_changing_after_file_creation(self): """ Directory modified and accessed time should change when a new file is created inside. """ self.storage.save("dir/file1.txt", ContentFile("test")) created_time = self.storage.get_created_time("dir") modified_time = self.storage.get_modified_time("dir") accessed_time = self.storage.get_accessed_time("dir") time.sleep(0.1) self.storage.save("dir/file2.txt", ContentFile("test")) new_modified_time = self.storage.get_modified_time("dir") new_accessed_time = self.storage.get_accessed_time("dir") after_file_creation_created_time = self.storage.get_created_time("dir") self.assertGreater(new_modified_time, modified_time) self.assertGreater(new_accessed_time, accessed_time) self.assertEqual(created_time, after_file_creation_created_time) def test_directory_times_changing_after_file_deletion(self): """ Directory modified and accessed time should change when a new file is deleted inside. """ self.storage.save("dir/file.txt", ContentFile("test")) created_time = self.storage.get_created_time("dir") modified_time = self.storage.get_modified_time("dir") accessed_time = self.storage.get_accessed_time("dir") time.sleep(0.1) self.storage.delete("dir/file.txt") new_modified_time = self.storage.get_modified_time("dir") new_accessed_time = self.storage.get_accessed_time("dir") after_file_deletion_created_time = self.storage.get_created_time("dir") self.assertGreater(new_modified_time, modified_time) self.assertGreater(new_accessed_time, accessed_time) self.assertEqual(created_time, after_file_deletion_created_time) class InMemoryStorageTests(SimpleTestCase): def test_deconstruction(self): storage = InMemoryStorage() path, args, kwargs = storage.deconstruct() self.assertEqual(path, "django.core.files.storage.InMemoryStorage") self.assertEqual(args, ()) self.assertEqual(kwargs, {}) kwargs_orig = { "location": "/custom_path", "base_url": "http://myfiles.example.com/", "file_permissions_mode": "0o755", "directory_permissions_mode": "0o600", } storage = InMemoryStorage(**kwargs_orig) path, args, kwargs = storage.deconstruct() self.assertEqual(kwargs, kwargs_orig) @override_settings( MEDIA_ROOT="media_root", MEDIA_URL="media_url/", FILE_UPLOAD_PERMISSIONS=0o777, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o777, ) def test_setting_changed(self): """ Properties using settings values as defaults should be updated on referenced settings change while specified values should be unchanged. """ storage = InMemoryStorage( location="explicit_location", base_url="explicit_base_url/", file_permissions_mode=0o666, directory_permissions_mode=0o666, ) defaults_storage = InMemoryStorage() settings = { "MEDIA_ROOT": "overridden_media_root", "MEDIA_URL": "/overridden_media_url/", "FILE_UPLOAD_PERMISSIONS": 0o333, "FILE_UPLOAD_DIRECTORY_PERMISSIONS": 0o333, } with self.settings(**settings): self.assertEqual(storage.base_location, "explicit_location") self.assertIn("explicit_location", storage.location) self.assertEqual(storage.base_url, "explicit_base_url/") self.assertEqual(storage.file_permissions_mode, 0o666) self.assertEqual(storage.directory_permissions_mode, 0o666) self.assertEqual(defaults_storage.base_location, settings["MEDIA_ROOT"]) self.assertIn(settings["MEDIA_ROOT"], defaults_storage.location) self.assertEqual(defaults_storage.base_url, settings["MEDIA_URL"]) self.assertEqual( defaults_storage.file_permissions_mode, settings["FILE_UPLOAD_PERMISSIONS"], ) self.assertEqual( defaults_storage.directory_permissions_mode, settings["FILE_UPLOAD_DIRECTORY_PERMISSIONS"], )
5fc39382ad44bc3f704d0cc079434390f8040e68736cad9e589f14e661489e76
import datetime import os import re import unittest import zoneinfo from unittest import mock from urllib.parse import parse_qsl, urljoin, urlparse from django.contrib import admin from django.contrib.admin import AdminSite, ModelAdmin from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.models import ADDITION, DELETION, LogEntry from django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.admin.utils import quote from django.contrib.admin.views.main import IS_POPUP_VAR from django.contrib.auth import REDIRECT_FIELD_NAME, get_permission_codename from django.contrib.auth.models import Group, Permission, User from django.contrib.contenttypes.models import ContentType from django.core import mail from django.core.checks import Error from django.core.files import temp as tempfile from django.db import connection from django.forms.utils import ErrorList from django.template.response import TemplateResponse from django.test import ( TestCase, modify_settings, override_settings, skipUnlessDBFeature, ) from django.test.utils import override_script_prefix from django.urls import NoReverseMatch, resolve, reverse from django.utils import formats, translation from django.utils.cache import get_max_age from django.utils.encoding import iri_to_uri from django.utils.html import escape from django.utils.http import urlencode from . import customadmin from .admin import CityAdmin, site, site2 from .models import ( Actor, AdminOrderedAdminMethod, AdminOrderedCallable, AdminOrderedField, AdminOrderedModelMethod, Album, Answer, Answer2, Article, BarAccount, Book, Bookmark, Box, Category, Chapter, ChapterXtra1, ChapterXtra2, Character, Child, Choice, City, Collector, Color, ComplexSortedPerson, CoverLetter, CustomArticle, CyclicOne, CyclicTwo, DooHickey, Employee, EmptyModel, Fabric, FancyDoodad, FieldOverridePost, FilteredManager, FooAccount, FoodDelivery, FunkyTag, Gallery, Grommet, Inquisition, Language, Link, MainPrepopulated, Media, ModelWithStringPrimaryKey, OtherStory, Paper, Parent, ParentWithDependentChildren, ParentWithUUIDPK, Person, Persona, Picture, Pizza, Plot, PlotDetails, PluggableSearchPerson, Podcast, Post, PrePopulatedPost, Promo, Question, ReadablePizza, ReadOnlyPizza, ReadOnlyRelatedField, Recommendation, Recommender, RelatedPrepopulated, RelatedWithUUIDPKModel, Report, Restaurant, RowLevelChangePermissionModel, SecretHideout, Section, ShortMessage, Simple, Song, State, Story, SuperSecretHideout, SuperVillain, Telegram, TitleTranslation, Topping, Traveler, UnchangeableObject, UndeletableObject, UnorderedObject, UserProxy, Villain, Vodcast, Whatsit, Widget, Worker, WorkHour, ) ERROR_MESSAGE = "Please enter the correct username and password \ for a staff account. Note that both fields may be case-sensitive." MULTIPART_ENCTYPE = 'enctype="multipart/form-data"' def make_aware_datetimes(dt, iana_key): """Makes one aware datetime for each supported time zone provider.""" yield dt.replace(tzinfo=zoneinfo.ZoneInfo(iana_key)) class AdminFieldExtractionMixin: """ Helper methods for extracting data from AdminForm. """ def get_admin_form_fields(self, response): """ Return a list of AdminFields for the AdminForm in the response. """ fields = [] for fieldset in response.context["adminform"]: for field_line in fieldset: fields.extend(field_line) return fields def get_admin_readonly_fields(self, response): """ Return the readonly fields for the response's AdminForm. """ return [f for f in self.get_admin_form_fields(response) if f.is_readonly] def get_admin_readonly_field(self, response, field_name): """ Return the readonly field for the given field_name. """ admin_readonly_fields = self.get_admin_readonly_fields(response) for field in admin_readonly_fields: if field.field["name"] == field_name: return field @override_settings(ROOT_URLCONF="admin_views.urls", USE_I18N=True, LANGUAGE_CODE="en") class AdminViewBasicTestCase(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, title="Article 1", ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, title="Article 2", ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.color1 = Color.objects.create(value="Red", warm=True) cls.color2 = Color.objects.create(value="Orange", warm=True) cls.color3 = Color.objects.create(value="Blue", warm=False) cls.color4 = Color.objects.create(value="Green", warm=False) cls.fab1 = Fabric.objects.create(surface="x") cls.fab2 = Fabric.objects.create(surface="y") cls.fab3 = Fabric.objects.create(surface="plain") cls.b1 = Book.objects.create(name="Book 1") cls.b2 = Book.objects.create(name="Book 2") cls.pro1 = Promo.objects.create(name="Promo 1", book=cls.b1) cls.pro1 = Promo.objects.create(name="Promo 2", book=cls.b2) cls.chap1 = Chapter.objects.create( title="Chapter 1", content="[ insert contents here ]", book=cls.b1 ) cls.chap2 = Chapter.objects.create( title="Chapter 2", content="[ insert contents here ]", book=cls.b1 ) cls.chap3 = Chapter.objects.create( title="Chapter 1", content="[ insert contents here ]", book=cls.b2 ) cls.chap4 = Chapter.objects.create( title="Chapter 2", content="[ insert contents here ]", book=cls.b2 ) cls.cx1 = ChapterXtra1.objects.create(chap=cls.chap1, xtra="ChapterXtra1 1") cls.cx2 = ChapterXtra1.objects.create(chap=cls.chap3, xtra="ChapterXtra1 2") Actor.objects.create(name="Palin", age=27) # Post data for edit inline cls.inline_post_data = { "name": "Test section", # inline data "article_set-TOTAL_FORMS": "6", "article_set-INITIAL_FORMS": "3", "article_set-MAX_NUM_FORMS": "0", "article_set-0-id": cls.a1.pk, # there is no title in database, give one here or formset will fail. "article_set-0-title": "Norske bostaver æøå skaper problemer", "article_set-0-content": "&lt;p&gt;Middle content&lt;/p&gt;", "article_set-0-date_0": "2008-03-18", "article_set-0-date_1": "11:54:58", "article_set-0-section": cls.s1.pk, "article_set-1-id": cls.a2.pk, "article_set-1-title": "Need a title.", "article_set-1-content": "&lt;p&gt;Oldest content&lt;/p&gt;", "article_set-1-date_0": "2000-03-18", "article_set-1-date_1": "11:54:58", "article_set-2-id": cls.a3.pk, "article_set-2-title": "Need a title.", "article_set-2-content": "&lt;p&gt;Newest content&lt;/p&gt;", "article_set-2-date_0": "2009-03-18", "article_set-2-date_1": "11:54:58", "article_set-3-id": "", "article_set-3-title": "", "article_set-3-content": "", "article_set-3-date_0": "", "article_set-3-date_1": "", "article_set-4-id": "", "article_set-4-title": "", "article_set-4-content": "", "article_set-4-date_0": "", "article_set-4-date_1": "", "article_set-5-id": "", "article_set-5-title": "", "article_set-5-content": "", "article_set-5-date_0": "", "article_set-5-date_1": "", } def setUp(self): self.client.force_login(self.superuser) def assertContentBefore(self, response, text1, text2, failing_msg=None): """ Testing utility asserting that text1 appears before text2 in response content. """ self.assertEqual(response.status_code, 200) self.assertLess( response.content.index(text1.encode()), response.content.index(text2.encode()), (failing_msg or "") + "\nResponse:\n" + response.content.decode(response.charset), ) class AdminViewBasicTest(AdminViewBasicTestCase): def test_trailing_slash_required(self): """ If you leave off the trailing slash, app should redirect and add it. """ add_url = reverse("admin:admin_views_article_add") response = self.client.get(add_url[:-1]) self.assertRedirects(response, add_url, status_code=301) def test_basic_add_GET(self): """ A smoke test to ensure GET on the add_view works. """ response = self.client.get(reverse("admin:admin_views_section_add")) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def test_add_with_GET_args(self): response = self.client.get( reverse("admin:admin_views_section_add"), {"name": "My Section"} ) self.assertContains( response, 'value="My Section"', msg_prefix="Couldn't find an input with the right value in the response", ) def test_basic_edit_GET(self): """ A smoke test to ensure GET on the change_view works. """ response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def test_basic_edit_GET_string_PK(self): """ GET on the change_view (when passing a string as the PK argument for a model with an integer PK field) redirects to the index page with a message saying the object doesn't exist. """ response = self.client.get( reverse("admin:admin_views_section_change", args=(quote("abc/<b>"),)), follow=True, ) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["section with ID “abc/<b>” doesn’t exist. Perhaps it was deleted?"], ) def test_basic_edit_GET_old_url_redirect(self): """ The change URL changed in Django 1.9, but the old one still redirects. """ response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)).replace( "change/", "" ) ) self.assertRedirects( response, reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) def test_basic_inheritance_GET_string_PK(self): """ GET on the change_view (for inherited models) redirects to the index page with a message saying the object doesn't exist. """ response = self.client.get( reverse("admin:admin_views_supervillain_change", args=("abc",)), follow=True ) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["super villain with ID “abc” doesn’t exist. Perhaps it was deleted?"], ) def test_basic_add_POST(self): """ A smoke test to ensure POST on add_view works. """ post_data = { "name": "Another Section", # inline data "article_set-TOTAL_FORMS": "3", "article_set-INITIAL_FORMS": "0", "article_set-MAX_NUM_FORMS": "0", } response = self.client.post(reverse("admin:admin_views_section_add"), post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def test_popup_add_POST(self): """HTTP response from a popup is properly escaped.""" post_data = { IS_POPUP_VAR: "1", "title": "title with a new\nline", "content": "some content", "date_0": "2010-09-10", "date_1": "14:55:39", } response = self.client.post(reverse("admin:admin_views_article_add"), post_data) self.assertContains(response, "title with a new\\nline") def test_basic_edit_POST(self): """ A smoke test to ensure POST on edit_view works. """ url = reverse("admin:admin_views_section_change", args=(self.s1.pk,)) response = self.client.post(url, self.inline_post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def test_edit_save_as(self): """ Test "save as". """ post_data = self.inline_post_data.copy() post_data.update( { "_saveasnew": "Save+as+new", "article_set-1-section": "1", "article_set-2-section": "1", "article_set-3-section": "1", "article_set-4-section": "1", "article_set-5-section": "1", } ) response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), post_data ) self.assertEqual(response.status_code, 302) # redirect somewhere def test_edit_save_as_delete_inline(self): """ Should be able to "Save as new" while also deleting an inline. """ post_data = self.inline_post_data.copy() post_data.update( { "_saveasnew": "Save+as+new", "article_set-1-section": "1", "article_set-2-section": "1", "article_set-2-DELETE": "1", "article_set-3-section": "1", } ) response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), post_data ) self.assertEqual(response.status_code, 302) # started with 3 articles, one was deleted. self.assertEqual(Section.objects.latest("id").article_set.count(), 2) def test_change_list_column_field_classes(self): response = self.client.get(reverse("admin:admin_views_article_changelist")) # callables display the callable name. self.assertContains(response, "column-callable_year") self.assertContains(response, "field-callable_year") # lambdas display as "lambda" + index that they appear in list_display. self.assertContains(response, "column-lambda8") self.assertContains(response, "field-lambda8") def test_change_list_sorting_callable(self): """ Ensure we can sort on a list_display field that is a callable (column 2 is callable_year in ArticleAdmin) """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": 2} ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on callable are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on callable are out of order.", ) def test_change_list_sorting_property(self): """ Sort on a list_display field that is a property (column 10 is a property in Article model). """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": 10} ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on property are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on property are out of order.", ) def test_change_list_sorting_callable_query_expression(self): """Query expressions may be used for admin_order_field.""" tests = [ ("order_by_expression", 9), ("order_by_f_expression", 12), ("order_by_orderby_expression", 13), ] for admin_order_field, index in tests: with self.subTest(admin_order_field): response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": index}, ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on callable are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on callable are out of order.", ) def test_change_list_sorting_callable_query_expression_reverse(self): tests = [ ("order_by_expression", -9), ("order_by_f_expression", -12), ("order_by_orderby_expression", -13), ] for admin_order_field, index in tests: with self.subTest(admin_order_field): response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": index}, ) self.assertContentBefore( response, "Middle content", "Oldest content", "Results of sorting on callable are out of order.", ) self.assertContentBefore( response, "Newest content", "Middle content", "Results of sorting on callable are out of order.", ) def test_change_list_sorting_model(self): """ Ensure we can sort on a list_display field that is a Model method (column 3 is 'model_year' in ArticleAdmin) """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "-3"} ) self.assertContentBefore( response, "Newest content", "Middle content", "Results of sorting on Model method are out of order.", ) self.assertContentBefore( response, "Middle content", "Oldest content", "Results of sorting on Model method are out of order.", ) def test_change_list_sorting_model_admin(self): """ Ensure we can sort on a list_display field that is a ModelAdmin method (column 4 is 'modeladmin_year' in ArticleAdmin) """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "4"} ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on ModelAdmin method are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on ModelAdmin method are out of order.", ) def test_change_list_sorting_model_admin_reverse(self): """ Ensure we can sort on a list_display field that is a ModelAdmin method in reverse order (i.e. admin_order_field uses the '-' prefix) (column 6 is 'model_year_reverse' in ArticleAdmin) """ td = '<td class="field-model_property_year">%s</td>' td_2000, td_2008, td_2009 = td % 2000, td % 2008, td % 2009 response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "6"} ) self.assertContentBefore( response, td_2009, td_2008, "Results of sorting on ModelAdmin method are out of order.", ) self.assertContentBefore( response, td_2008, td_2000, "Results of sorting on ModelAdmin method are out of order.", ) # Let's make sure the ordering is right and that we don't get a # FieldError when we change to descending order response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "-6"} ) self.assertContentBefore( response, td_2000, td_2008, "Results of sorting on ModelAdmin method are out of order.", ) self.assertContentBefore( response, td_2008, td_2009, "Results of sorting on ModelAdmin method are out of order.", ) def test_change_list_sorting_multiple(self): p1 = Person.objects.create(name="Chris", gender=1, alive=True) p2 = Person.objects.create(name="Chris", gender=2, alive=True) p3 = Person.objects.create(name="Bob", gender=1, alive=True) link1 = reverse("admin:admin_views_person_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_person_change", args=(p2.pk,)) link3 = reverse("admin:admin_views_person_change", args=(p3.pk,)) # Sort by name, gender response = self.client.get( reverse("admin:admin_views_person_changelist"), {"o": "1.2"} ) self.assertContentBefore(response, link3, link1) self.assertContentBefore(response, link1, link2) # Sort by gender descending, name response = self.client.get( reverse("admin:admin_views_person_changelist"), {"o": "-2.1"} ) self.assertContentBefore(response, link2, link3) self.assertContentBefore(response, link3, link1) def test_change_list_sorting_preserve_queryset_ordering(self): """ If no ordering is defined in `ModelAdmin.ordering` or in the query string, then the underlying order of the queryset should not be changed, even if it is defined in `Modeladmin.get_queryset()`. Refs #11868, #7309. """ p1 = Person.objects.create(name="Amy", gender=1, alive=True, age=80) p2 = Person.objects.create(name="Bob", gender=1, alive=True, age=70) p3 = Person.objects.create(name="Chris", gender=2, alive=False, age=60) link1 = reverse("admin:admin_views_person_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_person_change", args=(p2.pk,)) link3 = reverse("admin:admin_views_person_change", args=(p3.pk,)) response = self.client.get(reverse("admin:admin_views_person_changelist"), {}) self.assertContentBefore(response, link3, link2) self.assertContentBefore(response, link2, link1) def test_change_list_sorting_model_meta(self): # Test ordering on Model Meta is respected l1 = Language.objects.create(iso="ur", name="Urdu") l2 = Language.objects.create(iso="ar", name="Arabic") link1 = reverse("admin:admin_views_language_change", args=(quote(l1.pk),)) link2 = reverse("admin:admin_views_language_change", args=(quote(l2.pk),)) response = self.client.get(reverse("admin:admin_views_language_changelist"), {}) self.assertContentBefore(response, link2, link1) # Test we can override with query string response = self.client.get( reverse("admin:admin_views_language_changelist"), {"o": "-1"} ) self.assertContentBefore(response, link1, link2) def test_change_list_sorting_override_model_admin(self): # Test ordering on Model Admin is respected, and overrides Model Meta dt = datetime.datetime.now() p1 = Podcast.objects.create(name="A", release_date=dt) p2 = Podcast.objects.create(name="B", release_date=dt - datetime.timedelta(10)) link1 = reverse("admin:admin_views_podcast_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_podcast_change", args=(p2.pk,)) response = self.client.get(reverse("admin:admin_views_podcast_changelist"), {}) self.assertContentBefore(response, link1, link2) def test_multiple_sort_same_field(self): # The changelist displays the correct columns if two columns correspond # to the same ordering field. dt = datetime.datetime.now() p1 = Podcast.objects.create(name="A", release_date=dt) p2 = Podcast.objects.create(name="B", release_date=dt - datetime.timedelta(10)) link1 = reverse("admin:admin_views_podcast_change", args=(quote(p1.pk),)) link2 = reverse("admin:admin_views_podcast_change", args=(quote(p2.pk),)) response = self.client.get(reverse("admin:admin_views_podcast_changelist"), {}) self.assertContentBefore(response, link1, link2) p1 = ComplexSortedPerson.objects.create(name="Bob", age=10) p2 = ComplexSortedPerson.objects.create(name="Amy", age=20) link1 = reverse("admin:admin_views_complexsortedperson_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_complexsortedperson_change", args=(p2.pk,)) response = self.client.get( reverse("admin:admin_views_complexsortedperson_changelist"), {} ) # Should have 5 columns (including action checkbox col) self.assertContains(response, '<th scope="col"', count=5) self.assertContains(response, "Name") self.assertContains(response, "Colored name") # Check order self.assertContentBefore(response, "Name", "Colored name") # Check sorting - should be by name self.assertContentBefore(response, link2, link1) def test_sort_indicators_admin_order(self): """ The admin shows default sort indicators for all kinds of 'ordering' fields: field names, method on the model admin and model itself, and other callables. See #17252. """ models = [ (AdminOrderedField, "adminorderedfield"), (AdminOrderedModelMethod, "adminorderedmodelmethod"), (AdminOrderedAdminMethod, "adminorderedadminmethod"), (AdminOrderedCallable, "adminorderedcallable"), ] for model, url in models: model.objects.create(stuff="The Last Item", order=3) model.objects.create(stuff="The First Item", order=1) model.objects.create(stuff="The Middle Item", order=2) response = self.client.get( reverse("admin:admin_views_%s_changelist" % url), {} ) # Should have 3 columns including action checkbox col. self.assertContains(response, '<th scope="col"', count=3, msg_prefix=url) # Check if the correct column was selected. 2 is the index of the # 'order' column in the model admin's 'list_display' with 0 being # the implicit 'action_checkbox' and 1 being the column 'stuff'. self.assertEqual( response.context["cl"].get_ordering_field_columns(), {2: "asc"} ) # Check order of records. self.assertContentBefore(response, "The First Item", "The Middle Item") self.assertContentBefore(response, "The Middle Item", "The Last Item") def test_has_related_field_in_list_display_fk(self): """Joins shouldn't be performed for <FK>_id fields in list display.""" state = State.objects.create(name="Karnataka") City.objects.create(state=state, name="Bangalore") response = self.client.get(reverse("admin:admin_views_city_changelist"), {}) response.context["cl"].list_display = ["id", "name", "state"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), True) response.context["cl"].list_display = ["id", "name", "state_id"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), False) def test_has_related_field_in_list_display_o2o(self): """Joins shouldn't be performed for <O2O>_id fields in list display.""" media = Media.objects.create(name="Foo") Vodcast.objects.create(media=media) response = self.client.get(reverse("admin:admin_views_vodcast_changelist"), {}) response.context["cl"].list_display = ["media"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), True) response.context["cl"].list_display = ["media_id"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), False) def test_limited_filter(self): """ Admin changelist filters do not contain objects excluded via limit_choices_to. """ response = self.client.get(reverse("admin:admin_views_thing_changelist")) self.assertContains( response, '<div id="changelist-filter">', msg_prefix="Expected filter not found in changelist view", ) self.assertNotContains( response, '<a href="?color__id__exact=3">Blue</a>', msg_prefix="Changelist filter not correctly limited by limit_choices_to", ) def test_change_list_facet_toggle(self): # Toggle is visible when show_facet is the default of # admin.ShowFacets.ALLOW. admin_url = reverse("admin:admin_views_album_changelist") response = self.client.get(admin_url) self.assertContains( response, '<a href="?_facets=True" class="viewlink">Show counts</a>', msg_prefix="Expected facet filter toggle not found in changelist view", ) response = self.client.get(f"{admin_url}?_facets=True") self.assertContains( response, '<a href="?" class="hidelink">Hide counts</a>', msg_prefix="Expected facet filter toggle not found in changelist view", ) # Toggle is not visible when show_facet is admin.ShowFacets.ALWAYS. response = self.client.get(reverse("admin:admin_views_workhour_changelist")) self.assertNotContains( response, "Show counts", msg_prefix="Expected not to find facet filter toggle in changelist view", ) self.assertNotContains( response, "Hide counts", msg_prefix="Expected not to find facet filter toggle in changelist view", ) # Toggle is not visible when show_facet is admin.ShowFacets.NEVER. response = self.client.get(reverse("admin:admin_views_fooddelivery_changelist")) self.assertNotContains( response, "Show counts", msg_prefix="Expected not to find facet filter toggle in changelist view", ) self.assertNotContains( response, "Hide counts", msg_prefix="Expected not to find facet filter toggle in changelist view", ) def test_relation_spanning_filters(self): changelist_url = reverse("admin:admin_views_chapterxtra1_changelist") response = self.client.get(changelist_url) self.assertContains(response, '<div id="changelist-filter">') filters = { "chap__id__exact": { "values": [c.id for c in Chapter.objects.all()], "test": lambda obj, value: obj.chap.id == value, }, "chap__title": { "values": [c.title for c in Chapter.objects.all()], "test": lambda obj, value: obj.chap.title == value, }, "chap__book__id__exact": { "values": [b.id for b in Book.objects.all()], "test": lambda obj, value: obj.chap.book.id == value, }, "chap__book__name": { "values": [b.name for b in Book.objects.all()], "test": lambda obj, value: obj.chap.book.name == value, }, "chap__book__promo__id__exact": { "values": [p.id for p in Promo.objects.all()], "test": lambda obj, value: obj.chap.book.promo_set.filter( id=value ).exists(), }, "chap__book__promo__name": { "values": [p.name for p in Promo.objects.all()], "test": lambda obj, value: obj.chap.book.promo_set.filter( name=value ).exists(), }, # A forward relation (book) after a reverse relation (promo). "guest_author__promo__book__id__exact": { "values": [p.id for p in Book.objects.all()], "test": lambda obj, value: obj.guest_author.promo_set.filter( book=value ).exists(), }, } for filter_path, params in filters.items(): for value in params["values"]: query_string = urlencode({filter_path: value}) # ensure filter link exists self.assertContains(response, '<a href="?%s"' % query_string) # ensure link works filtered_response = self.client.get( "%s?%s" % (changelist_url, query_string) ) self.assertEqual(filtered_response.status_code, 200) # ensure changelist contains only valid objects for obj in filtered_response.context["cl"].queryset.all(): self.assertTrue(params["test"](obj, value)) def test_incorrect_lookup_parameters(self): """Ensure incorrect lookup parameters are handled gracefully.""" changelist_url = reverse("admin:admin_views_thing_changelist") response = self.client.get(changelist_url, {"notarealfield": "5"}) self.assertRedirects(response, "%s?e=1" % changelist_url) # Spanning relationships through a nonexistent related object (Refs #16716) response = self.client.get(changelist_url, {"notarealfield__whatever": "5"}) self.assertRedirects(response, "%s?e=1" % changelist_url) response = self.client.get( changelist_url, {"color__id__exact": "StringNotInteger!"} ) self.assertRedirects(response, "%s?e=1" % changelist_url) # Regression test for #18530 response = self.client.get(changelist_url, {"pub_date__gte": "foo"}) self.assertRedirects(response, "%s?e=1" % changelist_url) def test_isnull_lookups(self): """Ensure is_null is handled correctly.""" Article.objects.create( title="I Could Go Anywhere", content="Versatile", date=datetime.datetime.now(), ) changelist_url = reverse("admin:admin_views_article_changelist") response = self.client.get(changelist_url) self.assertContains(response, "4 articles") response = self.client.get(changelist_url, {"section__isnull": "false"}) self.assertContains(response, "3 articles") response = self.client.get(changelist_url, {"section__isnull": "0"}) self.assertContains(response, "3 articles") response = self.client.get(changelist_url, {"section__isnull": "true"}) self.assertContains(response, "1 article") response = self.client.get(changelist_url, {"section__isnull": "1"}) self.assertContains(response, "1 article") def test_logout_and_password_change_URLs(self): response = self.client.get(reverse("admin:admin_views_article_changelist")) self.assertContains( response, '<form id="logout-form" method="post" action="%s">' % reverse("admin:logout"), ) self.assertContains( response, '<a href="%s">' % reverse("admin:password_change") ) def test_named_group_field_choices_change_list(self): """ Ensures the admin changelist shows correct values in the relevant column for rows corresponding to instances of a model in which a named group has been used in the choices option of a field. """ link1 = reverse("admin:admin_views_fabric_change", args=(self.fab1.pk,)) link2 = reverse("admin:admin_views_fabric_change", args=(self.fab2.pk,)) response = self.client.get(reverse("admin:admin_views_fabric_changelist")) fail_msg = ( "Changelist table isn't showing the right human-readable values " "set by a model field 'choices' option named group." ) self.assertContains( response, '<a href="%s">Horizontal</a>' % link1, msg_prefix=fail_msg, html=True, ) self.assertContains( response, '<a href="%s">Vertical</a>' % link2, msg_prefix=fail_msg, html=True, ) def test_named_group_field_choices_filter(self): """ Ensures the filter UI shows correctly when at least one named group has been used in the choices option of a model field. """ response = self.client.get(reverse("admin:admin_views_fabric_changelist")) fail_msg = ( "Changelist filter isn't showing options contained inside a model " "field 'choices' option named group." ) self.assertContains(response, '<div id="changelist-filter">') self.assertContains( response, '<a href="?surface__exact=x">Horizontal</a>', msg_prefix=fail_msg, html=True, ) self.assertContains( response, '<a href="?surface__exact=y">Vertical</a>', msg_prefix=fail_msg, html=True, ) def test_change_list_null_boolean_display(self): Post.objects.create(public=None) response = self.client.get(reverse("admin:admin_views_post_changelist")) self.assertContains(response, "icon-unknown.svg") def test_display_decorator_with_boolean_and_empty_value(self): msg = ( "The boolean and empty_value arguments to the @display decorator " "are mutually exclusive." ) with self.assertRaisesMessage(ValueError, msg): class BookAdmin(admin.ModelAdmin): @admin.display(boolean=True, empty_value="(Missing)") def is_published(self, obj): return obj.publish_date is not None def test_i18n_language_non_english_default(self): """ Check if the JavaScript i18n view returns an empty language catalog if the default language is non-English but the selected language is English. See #13388 and #3594 for more details. """ with self.settings(LANGUAGE_CODE="fr"), translation.override("en-us"): response = self.client.get(reverse("admin:jsi18n")) self.assertNotContains(response, "Choisir une heure") def test_i18n_language_non_english_fallback(self): """ Makes sure that the fallback language is still working properly in cases where the selected language cannot be found. """ with self.settings(LANGUAGE_CODE="fr"), translation.override("none"): response = self.client.get(reverse("admin:jsi18n")) self.assertContains(response, "Choisir une heure") def test_jsi18n_with_context(self): response = self.client.get(reverse("admin-extra-context:jsi18n")) self.assertEqual(response.status_code, 200) def test_jsi18n_format_fallback(self): """ The JavaScript i18n view doesn't return localized date/time formats when the selected language cannot be found. """ with self.settings(LANGUAGE_CODE="ru"), translation.override("none"): response = self.client.get(reverse("admin:jsi18n")) self.assertNotContains(response, "%d.%m.%Y %H:%M:%S") self.assertContains(response, "%Y-%m-%d %H:%M:%S") def test_disallowed_filtering(self): with self.assertLogs("django.security.DisallowedModelAdminLookup", "ERROR"): response = self.client.get( "%s?owner__email__startswith=fuzzy" % reverse("admin:admin_views_album_changelist") ) self.assertEqual(response.status_code, 400) # Filters are allowed if explicitly included in list_filter response = self.client.get( "%s?color__value__startswith=red" % reverse("admin:admin_views_thing_changelist") ) self.assertEqual(response.status_code, 200) response = self.client.get( "%s?color__value=red" % reverse("admin:admin_views_thing_changelist") ) self.assertEqual(response.status_code, 200) # Filters should be allowed if they involve a local field without the # need to allow them in list_filter or date_hierarchy. response = self.client.get( "%s?age__gt=30" % reverse("admin:admin_views_person_changelist") ) self.assertEqual(response.status_code, 200) e1 = Employee.objects.create( name="Anonymous", gender=1, age=22, alive=True, code="123" ) e2 = Employee.objects.create( name="Visitor", gender=2, age=19, alive=True, code="124" ) WorkHour.objects.create(datum=datetime.datetime.now(), employee=e1) WorkHour.objects.create(datum=datetime.datetime.now(), employee=e2) response = self.client.get(reverse("admin:admin_views_workhour_changelist")) self.assertContains(response, "employee__person_ptr__exact") response = self.client.get( "%s?employee__person_ptr__exact=%d" % (reverse("admin:admin_views_workhour_changelist"), e1.pk) ) self.assertEqual(response.status_code, 200) def test_disallowed_to_field(self): url = reverse("admin:admin_views_section_changelist") with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.get(url, {TO_FIELD_VAR: "missing_field"}) self.assertEqual(response.status_code, 400) # Specifying a field that is not referred by any other model registered # to this admin site should raise an exception. with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.get( reverse("admin:admin_views_section_changelist"), {TO_FIELD_VAR: "name"} ) self.assertEqual(response.status_code, 400) # Primary key should always be allowed, even if the referenced model # isn't registered. response = self.client.get( reverse("admin:admin_views_notreferenced_changelist"), {TO_FIELD_VAR: "id"} ) self.assertEqual(response.status_code, 200) # Specifying a field referenced by another model though a m2m should be # allowed. response = self.client.get( reverse("admin:admin_views_recipe_changelist"), {TO_FIELD_VAR: "rname"} ) self.assertEqual(response.status_code, 200) # Specifying a field referenced through a reverse m2m relationship # should be allowed. response = self.client.get( reverse("admin:admin_views_ingredient_changelist"), {TO_FIELD_VAR: "iname"} ) self.assertEqual(response.status_code, 200) # Specifying a field that is not referred by any other model directly # registered to this admin site but registered through inheritance # should be allowed. response = self.client.get( reverse("admin:admin_views_referencedbyparent_changelist"), {TO_FIELD_VAR: "name"}, ) self.assertEqual(response.status_code, 200) # Specifying a field that is only referred to by a inline of a # registered model should be allowed. response = self.client.get( reverse("admin:admin_views_referencedbyinline_changelist"), {TO_FIELD_VAR: "name"}, ) self.assertEqual(response.status_code, 200) # #25622 - Specifying a field of a model only referred by a generic # relation should raise DisallowedModelAdminToField. url = reverse("admin:admin_views_referencedbygenrel_changelist") with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.get(url, {TO_FIELD_VAR: "object_id"}) self.assertEqual(response.status_code, 400) # We also want to prevent the add, change, and delete views from # leaking a disallowed field value. with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.post( reverse("admin:admin_views_section_add"), {TO_FIELD_VAR: "name"} ) self.assertEqual(response.status_code, 400) section = Section.objects.create() url = reverse("admin:admin_views_section_change", args=(section.pk,)) with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.post(url, {TO_FIELD_VAR: "name"}) self.assertEqual(response.status_code, 400) url = reverse("admin:admin_views_section_delete", args=(section.pk,)) with self.assertLogs("django.security.DisallowedModelAdminToField", "ERROR"): response = self.client.post(url, {TO_FIELD_VAR: "name"}) self.assertEqual(response.status_code, 400) def test_allowed_filtering_15103(self): """ Regressions test for ticket 15103 - filtering on fields defined in a ForeignKey 'limit_choices_to' should be allowed, otherwise raw_id_fields can break. """ # Filters should be allowed if they are defined on a ForeignKey # pointing to this model. url = "%s?leader__name=Palin&leader__age=27" % reverse( "admin:admin_views_inquisition_changelist" ) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_popup_dismiss_related(self): """ Regression test for ticket 20664 - ensure the pk is properly quoted. """ actor = Actor.objects.create(name="Palin", age=27) response = self.client.get( "%s?%s" % (reverse("admin:admin_views_actor_changelist"), IS_POPUP_VAR) ) self.assertContains(response, 'data-popup-opener="%s"' % actor.pk) def test_hide_change_password(self): """ Tests if the "change password" link in the admin is hidden if the User does not have a usable password set. (against 9bea85795705d015cdadc82c68b99196a8554f5c) """ user = User.objects.get(username="super") user.set_unusable_password() user.save() self.client.force_login(user) response = self.client.get(reverse("admin:index")) self.assertNotContains( response, reverse("admin:password_change"), msg_prefix=( 'The "change password" link should not be displayed if a user does not ' "have a usable password." ), ) def test_change_view_with_show_delete_extra_context(self): """ The 'show_delete' context variable in the admin's change view controls the display of the delete button. """ instance = UndeletableObject.objects.create(name="foo") response = self.client.get( reverse("admin:admin_views_undeletableobject_change", args=(instance.pk,)) ) self.assertNotContains(response, "deletelink") def test_change_view_logs_m2m_field_changes(self): """Changes to ManyToManyFields are included in the object's history.""" pizza = ReadablePizza.objects.create(name="Cheese") cheese = Topping.objects.create(name="cheese") post_data = {"name": pizza.name, "toppings": [cheese.pk]} response = self.client.post( reverse("admin:admin_views_readablepizza_change", args=(pizza.pk,)), post_data, ) self.assertRedirects( response, reverse("admin:admin_views_readablepizza_changelist") ) pizza_ctype = ContentType.objects.get_for_model( ReadablePizza, for_concrete_model=False ) log = LogEntry.objects.filter( content_type=pizza_ctype, object_id=pizza.pk ).first() self.assertEqual(log.get_change_message(), "Changed Toppings.") def test_allows_attributeerror_to_bubble_up(self): """ AttributeErrors are allowed to bubble when raised inside a change list view. Requires a model to be created so there's something to display. Refs: #16655, #18593, and #18747 """ Simple.objects.create() with self.assertRaises(AttributeError): self.client.get(reverse("admin:admin_views_simple_changelist")) def test_changelist_with_no_change_url(self): """ ModelAdmin.changelist_view shouldn't result in a NoReverseMatch if url for change_view is removed from get_urls (#20934). """ o = UnchangeableObject.objects.create() response = self.client.get( reverse("admin:admin_views_unchangeableobject_changelist") ) # Check the format of the shown object -- shouldn't contain a change link self.assertContains( response, '<th class="field-__str__">%s</th>' % o, html=True ) def test_invalid_appindex_url(self): """ #21056 -- URL reversing shouldn't work for nonexistent apps. """ good_url = "/test_admin/admin/admin_views/" confirm_good_url = reverse( "admin:app_list", kwargs={"app_label": "admin_views"} ) self.assertEqual(good_url, confirm_good_url) with self.assertRaises(NoReverseMatch): reverse("admin:app_list", kwargs={"app_label": "this_should_fail"}) with self.assertRaises(NoReverseMatch): reverse("admin:app_list", args=("admin_views2",)) def test_resolve_admin_views(self): index_match = resolve("/test_admin/admin4/") list_match = resolve("/test_admin/admin4/auth/user/") self.assertIs(index_match.func.admin_site, customadmin.simple_site) self.assertIsInstance( list_match.func.model_admin, customadmin.CustomPwdTemplateUserAdmin ) def test_adminsite_display_site_url(self): """ #13749 - Admin should display link to front-end site 'View site' """ url = reverse("admin:index") response = self.client.get(url) self.assertEqual(response.context["site_url"], "/my-site-url/") self.assertContains(response, '<a href="/my-site-url/">View site</a>') def test_date_hierarchy_empty_queryset(self): self.assertIs(Question.objects.exists(), False) response = self.client.get(reverse("admin:admin_views_answer2_changelist")) self.assertEqual(response.status_code, 200) @override_settings(TIME_ZONE="America/Sao_Paulo", USE_TZ=True) def test_date_hierarchy_timezone_dst(self): # This datetime doesn't exist in this timezone due to DST. for date in make_aware_datetimes( datetime.datetime(2016, 10, 16, 15), "America/Sao_Paulo" ): with self.subTest(repr(date.tzinfo)): q = Question.objects.create(question="Why?", expires=date) Answer2.objects.create(question=q, answer="Because.") response = self.client.get( reverse("admin:admin_views_answer2_changelist") ) self.assertContains(response, "question__expires__day=16") self.assertContains(response, "question__expires__month=10") self.assertContains(response, "question__expires__year=2016") @override_settings(TIME_ZONE="America/Los_Angeles", USE_TZ=True) def test_date_hierarchy_local_date_differ_from_utc(self): # This datetime is 2017-01-01 in UTC. for date in make_aware_datetimes( datetime.datetime(2016, 12, 31, 16), "America/Los_Angeles" ): with self.subTest(repr(date.tzinfo)): q = Question.objects.create(question="Why?", expires=date) Answer2.objects.create(question=q, answer="Because.") response = self.client.get( reverse("admin:admin_views_answer2_changelist") ) self.assertContains(response, "question__expires__day=31") self.assertContains(response, "question__expires__month=12") self.assertContains(response, "question__expires__year=2016") def test_sortable_by_columns_subset(self): expected_sortable_fields = ("date", "callable_year") expected_not_sortable_fields = ( "content", "model_year", "modeladmin_year", "model_year_reversed", "section", ) response = self.client.get(reverse("admin6:admin_views_article_changelist")) for field_name in expected_sortable_fields: self.assertContains( response, '<th scope="col" class="sortable column-%s">' % field_name ) for field_name in expected_not_sortable_fields: self.assertContains( response, '<th scope="col" class="column-%s">' % field_name ) def test_get_sortable_by_columns_subset(self): response = self.client.get(reverse("admin6:admin_views_actor_changelist")) self.assertContains(response, '<th scope="col" class="sortable column-age">') self.assertContains(response, '<th scope="col" class="column-name">') def test_sortable_by_no_column(self): expected_not_sortable_fields = ("title", "book") response = self.client.get(reverse("admin6:admin_views_chapter_changelist")) for field_name in expected_not_sortable_fields: self.assertContains( response, '<th scope="col" class="column-%s">' % field_name ) self.assertNotContains(response, '<th scope="col" class="sortable column') def test_get_sortable_by_no_column(self): response = self.client.get(reverse("admin6:admin_views_color_changelist")) self.assertContains(response, '<th scope="col" class="column-value">') self.assertNotContains(response, '<th scope="col" class="sortable column') def test_app_index_context(self): response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertContains( response, "<title>Admin_Views administration | Django site admin</title>", ) self.assertEqual(response.context["title"], "Admin_Views administration") self.assertEqual(response.context["app_label"], "admin_views") # Models are sorted alphabetically by default. models = [model["name"] for model in response.context["app_list"][0]["models"]] self.assertSequenceEqual(models, sorted(models)) def test_app_index_context_reordered(self): self.client.force_login(self.superuser) response = self.client.get(reverse("admin2:app_list", args=("admin_views",))) self.assertContains( response, "<title>Admin_Views administration | Django site admin</title>", ) # Models are in reverse order. models = [model["name"] for model in response.context["app_list"][0]["models"]] self.assertSequenceEqual(models, sorted(models, reverse=True)) def test_change_view_subtitle_per_object(self): response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a1.pk,)), ) self.assertContains( response, "<title>Article 1 | Change article | Django site admin</title>", ) self.assertContains(response, "<h1>Change article</h1>") self.assertContains(response, "<h2>Article 1</h2>") response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a2.pk,)), ) self.assertContains( response, "<title>Article 2 | Change article | Django site admin</title>", ) self.assertContains(response, "<h1>Change article</h1>") self.assertContains(response, "<h2>Article 2</h2>") def test_view_subtitle_per_object(self): viewuser = User.objects.create_user( username="viewuser", password="secret", is_staff=True, ) viewuser.user_permissions.add( get_perm(Article, get_permission_codename("view", Article._meta)), ) self.client.force_login(viewuser) response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a1.pk,)), ) self.assertContains( response, "<title>Article 1 | View article | Django site admin</title>", ) self.assertContains(response, "<h1>View article</h1>") self.assertContains(response, "<h2>Article 1</h2>") response = self.client.get( reverse("admin:admin_views_article_change", args=(self.a2.pk,)), ) self.assertContains( response, "<title>Article 2 | View article | Django site admin</title>", ) self.assertContains(response, "<h1>View article</h1>") self.assertContains(response, "<h2>Article 2</h2>") def test_formset_kwargs_can_be_overridden(self): response = self.client.get(reverse("admin:admin_views_city_add")) self.assertContains(response, "overridden_name") def test_render_views_no_subtitle(self): tests = [ reverse("admin:index"), reverse("admin:password_change"), reverse("admin:app_list", args=("admin_views",)), reverse("admin:admin_views_article_delete", args=(self.a1.pk,)), reverse("admin:admin_views_article_history", args=(self.a1.pk,)), ] for url in tests: with self.subTest(url=url): with self.assertNoLogs("django.template", "DEBUG"): self.client.get(url) # Login must be after logout. with self.assertNoLogs("django.template", "DEBUG"): self.client.post(reverse("admin:logout")) self.client.get(reverse("admin:login")) def test_render_delete_selected_confirmation_no_subtitle(self): post_data = { "action": "delete_selected", "selected_across": "0", "index": "0", "_selected_action": self.a1.pk, } with self.assertNoLogs("django.template", "DEBUG"): self.client.post(reverse("admin:admin_views_article_changelist"), post_data) @override_settings( AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, { "NAME": ( "django.contrib.auth.password_validation." "NumericPasswordValidator" ) }, ] ) def test_password_change_helptext(self): response = self.client.get(reverse("admin:password_change")) self.assertContains( response, '<div class="help" id="id_new_password1_helptext">' ) @override_settings( AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, { "NAME": ( "django.contrib.auth.password_validation." "NumericPasswordValidator" ) }, ], TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", # Put this app's and the shared tests templates dirs in DIRS to # take precedence over the admin's templates dir. "DIRS": [ os.path.join(os.path.dirname(__file__), "templates"), os.path.join(os.path.dirname(os.path.dirname(__file__)), "templates"), ], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ], ) class AdminCustomTemplateTests(AdminViewBasicTestCase): def test_custom_model_admin_templates(self): # Test custom change list template with custom extra context response = self.client.get( reverse("admin:admin_views_customarticle_changelist") ) self.assertContains(response, "var hello = 'Hello!';") self.assertTemplateUsed(response, "custom_admin/change_list.html") # Test custom add form template response = self.client.get(reverse("admin:admin_views_customarticle_add")) self.assertTemplateUsed(response, "custom_admin/add_form.html") # Add an article so we can test delete, change, and history views post = self.client.post( reverse("admin:admin_views_customarticle_add"), { "content": "<p>great article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", }, ) self.assertRedirects( post, reverse("admin:admin_views_customarticle_changelist") ) self.assertEqual(CustomArticle.objects.count(), 1) article_pk = CustomArticle.objects.all()[0].pk # Test custom delete, change, and object history templates # Test custom change form template response = self.client.get( reverse("admin:admin_views_customarticle_change", args=(article_pk,)) ) self.assertTemplateUsed(response, "custom_admin/change_form.html") response = self.client.get( reverse("admin:admin_views_customarticle_delete", args=(article_pk,)) ) self.assertTemplateUsed(response, "custom_admin/delete_confirmation.html") response = self.client.post( reverse("admin:admin_views_customarticle_changelist"), data={ "index": 0, "action": ["delete_selected"], "_selected_action": ["1"], }, ) self.assertTemplateUsed( response, "custom_admin/delete_selected_confirmation.html" ) response = self.client.get( reverse("admin:admin_views_customarticle_history", args=(article_pk,)) ) self.assertTemplateUsed(response, "custom_admin/object_history.html") # A custom popup response template may be specified by # ModelAdmin.popup_response_template. response = self.client.post( reverse("admin:admin_views_customarticle_add") + "?%s=1" % IS_POPUP_VAR, { "content": "<p>great article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", IS_POPUP_VAR: "1", }, ) self.assertEqual(response.template_name, "custom_admin/popup_response.html") def test_extended_bodyclass_template_change_form(self): """ The admin/change_form.html template uses block.super in the bodyclass block. """ response = self.client.get(reverse("admin:admin_views_section_add")) self.assertContains(response, "bodyclass_consistency_check ") def test_change_password_template(self): user = User.objects.get(username="super") response = self.client.get( reverse("admin:auth_user_password_change", args=(user.id,)) ) # The auth/user/change_password.html template uses super in the # bodyclass block. self.assertContains(response, "bodyclass_consistency_check ") # When a site has multiple passwords in the browser's password manager, # a browser pop up asks which user the new password is for. To prevent # this, the username is added to the change password form. self.assertContains( response, '<input type="text" name="username" value="super" class="hidden">' ) # help text for passwords has an id. self.assertContains( response, '<div class="help" id="id_password1_helptext"><ul><li>' "Your password can’t be too similar to your other personal information." "</li><li>Your password can’t be entirely numeric.</li></ul></div>", ) self.assertContains( response, '<div class="help" id="id_password2_helptext">' "Enter the same password as before, for verification.</div>", ) def test_extended_bodyclass_template_index(self): """ The admin/index.html template uses block.super in the bodyclass block. """ response = self.client.get(reverse("admin:index")) self.assertContains(response, "bodyclass_consistency_check ") def test_extended_bodyclass_change_list(self): """ The admin/change_list.html' template uses block.super in the bodyclass block. """ response = self.client.get(reverse("admin:admin_views_article_changelist")) self.assertContains(response, "bodyclass_consistency_check ") def test_extended_bodyclass_template_login(self): """ The admin/login.html template uses block.super in the bodyclass block. """ self.client.logout() response = self.client.get(reverse("admin:login")) self.assertContains(response, "bodyclass_consistency_check ") def test_extended_bodyclass_template_delete_confirmation(self): """ The admin/delete_confirmation.html template uses block.super in the bodyclass block. """ group = Group.objects.create(name="foogroup") response = self.client.get(reverse("admin:auth_group_delete", args=(group.id,))) self.assertContains(response, "bodyclass_consistency_check ") def test_extended_bodyclass_template_delete_selected_confirmation(self): """ The admin/delete_selected_confirmation.html template uses block.super in bodyclass block. """ group = Group.objects.create(name="foogroup") post_data = { "action": "delete_selected", "selected_across": "0", "index": "0", "_selected_action": group.id, } response = self.client.post(reverse("admin:auth_group_changelist"), post_data) self.assertEqual(response.context["site_header"], "Django administration") self.assertContains(response, "bodyclass_consistency_check ") def test_filter_with_custom_template(self): """ A custom template can be used to render an admin filter. """ response = self.client.get(reverse("admin:admin_views_color2_changelist")) self.assertTemplateUsed(response, "custom_filter_template.html") @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewFormUrlTest(TestCase): current_app = "admin3" @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) def setUp(self): self.client.force_login(self.superuser) def test_change_form_URL_has_correct_value(self): """ change_view has form_url in response.context """ response = self.client.get( reverse( "admin:admin_views_section_change", args=(self.s1.pk,), current_app=self.current_app, ) ) self.assertIn( "form_url", response.context, msg="form_url not present in response.context" ) self.assertEqual(response.context["form_url"], "pony") def test_initial_data_can_be_overridden(self): """ The behavior for setting initial form data can be overridden in the ModelAdmin class. Usually, the initial value is set via the GET params. """ response = self.client.get( reverse("admin:admin_views_restaurant_add", current_app=self.current_app), {"name": "test_value"}, ) # this would be the usual behaviour self.assertNotContains(response, 'value="test_value"') # this is the overridden behaviour self.assertContains(response, 'value="overridden_value"') @override_settings(ROOT_URLCONF="admin_views.urls") class AdminJavaScriptTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_js_minified_only_if_debug_is_false(self): """ The minified versions of the JS files are only used when DEBUG is False. """ with override_settings(DEBUG=False): response = self.client.get(reverse("admin:admin_views_section_add")) self.assertNotContains(response, "vendor/jquery/jquery.js") self.assertContains(response, "vendor/jquery/jquery.min.js") self.assertContains(response, "prepopulate.js") self.assertContains(response, "actions.js") self.assertContains(response, "collapse.js") self.assertContains(response, "inlines.js") with override_settings(DEBUG=True): response = self.client.get(reverse("admin:admin_views_section_add")) self.assertContains(response, "vendor/jquery/jquery.js") self.assertNotContains(response, "vendor/jquery/jquery.min.js") self.assertContains(response, "prepopulate.js") self.assertContains(response, "actions.js") self.assertContains(response, "collapse.js") self.assertContains(response, "inlines.js") @override_settings(ROOT_URLCONF="admin_views.urls") class SaveAsTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) def setUp(self): self.client.force_login(self.superuser) def test_save_as_duplication(self): """'save as' creates a new person""" post_data = {"_saveasnew": "", "name": "John M", "gender": 1, "age": 42} response = self.client.post( reverse("admin:admin_views_person_change", args=(self.per1.pk,)), post_data ) self.assertEqual(len(Person.objects.filter(name="John M")), 1) self.assertEqual(len(Person.objects.filter(id=self.per1.pk)), 1) new_person = Person.objects.latest("id") self.assertRedirects( response, reverse("admin:admin_views_person_change", args=(new_person.pk,)) ) def test_save_as_continue_false(self): """ Saving a new object using "Save as new" redirects to the changelist instead of the change view when ModelAdmin.save_as_continue=False. """ post_data = {"_saveasnew": "", "name": "John M", "gender": 1, "age": 42} url = reverse( "admin:admin_views_person_change", args=(self.per1.pk,), current_app=site2.name, ) response = self.client.post(url, post_data) self.assertEqual(len(Person.objects.filter(name="John M")), 1) self.assertEqual(len(Person.objects.filter(id=self.per1.pk)), 1) self.assertRedirects( response, reverse("admin:admin_views_person_changelist", current_app=site2.name), ) def test_save_as_new_with_validation_errors(self): """ When you click "Save as new" and have a validation error, you only see the "Save as new" button and not the other save buttons, and that only the "Save as" button is visible. """ response = self.client.post( reverse("admin:admin_views_person_change", args=(self.per1.pk,)), { "_saveasnew": "", "gender": "invalid", "_addanother": "fail", }, ) self.assertContains(response, "Please correct the errors below.") self.assertFalse(response.context["show_save_and_add_another"]) self.assertFalse(response.context["show_save_and_continue"]) self.assertTrue(response.context["show_save_as_new"]) def test_save_as_new_with_validation_errors_with_inlines(self): parent = Parent.objects.create(name="Father") child = Child.objects.create(parent=parent, name="Child") response = self.client.post( reverse("admin:admin_views_parent_change", args=(parent.pk,)), { "_saveasnew": "Save as new", "child_set-0-parent": parent.pk, "child_set-0-id": child.pk, "child_set-0-name": "Child", "child_set-INITIAL_FORMS": 1, "child_set-MAX_NUM_FORMS": 1000, "child_set-MIN_NUM_FORMS": 0, "child_set-TOTAL_FORMS": 4, "name": "_invalid", }, ) self.assertContains(response, "Please correct the error below.") self.assertFalse(response.context["show_save_and_add_another"]) self.assertFalse(response.context["show_save_and_continue"]) self.assertTrue(response.context["show_save_as_new"]) def test_save_as_new_with_inlines_with_validation_errors(self): parent = Parent.objects.create(name="Father") child = Child.objects.create(parent=parent, name="Child") response = self.client.post( reverse("admin:admin_views_parent_change", args=(parent.pk,)), { "_saveasnew": "Save as new", "child_set-0-parent": parent.pk, "child_set-0-id": child.pk, "child_set-0-name": "_invalid", "child_set-INITIAL_FORMS": 1, "child_set-MAX_NUM_FORMS": 1000, "child_set-MIN_NUM_FORMS": 0, "child_set-TOTAL_FORMS": 4, "name": "Father", }, ) self.assertContains(response, "Please correct the error below.") self.assertFalse(response.context["show_save_and_add_another"]) self.assertFalse(response.context["show_save_and_continue"]) self.assertTrue(response.context["show_save_as_new"]) @override_settings(ROOT_URLCONF="admin_views.urls") class CustomModelAdminTest(AdminViewBasicTestCase): def test_custom_admin_site_login_form(self): self.client.logout() response = self.client.get(reverse("admin2:index"), follow=True) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) login = self.client.post( reverse("admin2:login"), { REDIRECT_FIELD_NAME: reverse("admin2:index"), "username": "customform", "password": "secret", }, follow=True, ) self.assertIsInstance(login, TemplateResponse) self.assertContains(login, "custom form error") self.assertContains(login, "path/to/media.css") def test_custom_admin_site_login_template(self): self.client.logout() response = self.client.get(reverse("admin2:index"), follow=True) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/login.html") self.assertContains(response, "Hello from a custom login template") def test_custom_admin_site_logout_template(self): response = self.client.post(reverse("admin2:logout")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/logout.html") self.assertContains(response, "Hello from a custom logout template") def test_custom_admin_site_index_view_and_template(self): response = self.client.get(reverse("admin2:index")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/index.html") self.assertContains(response, "Hello from a custom index template *bar*") def test_custom_admin_site_app_index_view_and_template(self): response = self.client.get(reverse("admin2:app_list", args=("admin_views",))) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/app_index.html") self.assertContains(response, "Hello from a custom app_index template") def test_custom_admin_site_password_change_template(self): response = self.client.get(reverse("admin2:password_change")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/password_change_form.html") self.assertContains( response, "Hello from a custom password change form template" ) def test_custom_admin_site_password_change_with_extra_context(self): response = self.client.get(reverse("admin2:password_change")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/password_change_form.html") self.assertContains(response, "eggs") def test_custom_admin_site_password_change_done_template(self): response = self.client.get(reverse("admin2:password_change_done")) self.assertIsInstance(response, TemplateResponse) self.assertTemplateUsed(response, "custom_admin/password_change_done.html") self.assertContains( response, "Hello from a custom password change done template" ) def test_custom_admin_site_view(self): self.client.force_login(self.superuser) response = self.client.get(reverse("admin2:my_view")) self.assertEqual(response.content, b"Django is a magical pony!") def test_pwd_change_custom_template(self): self.client.force_login(self.superuser) su = User.objects.get(username="super") response = self.client.get( reverse("admin4:auth_user_password_change", args=(su.pk,)) ) self.assertEqual(response.status_code, 200) def get_perm(Model, codename): """Return the permission object, for the Model""" ct = ContentType.objects.get_for_model(Model, for_concrete_model=False) return Permission.objects.get(content_type=ct, codename=codename) @override_settings( ROOT_URLCONF="admin_views.urls", # Test with the admin's documented list of required context processors. TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ], ) class AdminViewPermissionsTest(TestCase): """Tests for Admin Views Permissions.""" @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.viewuser = User.objects.create_user( username="viewuser", password="secret", is_staff=True ) cls.adduser = User.objects.create_user( username="adduser", password="secret", is_staff=True ) cls.changeuser = User.objects.create_user( username="changeuser", password="secret", is_staff=True ) cls.deleteuser = User.objects.create_user( username="deleteuser", password="secret", is_staff=True ) cls.joepublicuser = User.objects.create_user( username="joepublic", password="secret" ) cls.nostaffuser = User.objects.create_user( username="nostaff", password="secret" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, another_section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) # Setup permissions, for our users who can add, change, and delete. opts = Article._meta # User who can view Articles cls.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("view", opts)) ) # User who can add Articles cls.adduser.user_permissions.add( get_perm(Article, get_permission_codename("add", opts)) ) # User who can change Articles cls.changeuser.user_permissions.add( get_perm(Article, get_permission_codename("change", opts)) ) cls.nostaffuser.user_permissions.add( get_perm(Article, get_permission_codename("change", opts)) ) # User who can delete Articles cls.deleteuser.user_permissions.add( get_perm(Article, get_permission_codename("delete", opts)) ) cls.deleteuser.user_permissions.add( get_perm(Section, get_permission_codename("delete", Section._meta)) ) # login POST dicts cls.index_url = reverse("admin:index") cls.super_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "super", "password": "secret", } cls.super_email_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "[email protected]", "password": "secret", } cls.super_email_bad_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "[email protected]", "password": "notsecret", } cls.adduser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "adduser", "password": "secret", } cls.changeuser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "changeuser", "password": "secret", } cls.deleteuser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "deleteuser", "password": "secret", } cls.nostaff_login = { REDIRECT_FIELD_NAME: reverse("has_permission_admin:index"), "username": "nostaff", "password": "secret", } cls.joepublic_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "joepublic", "password": "secret", } cls.viewuser_login = { REDIRECT_FIELD_NAME: cls.index_url, "username": "viewuser", "password": "secret", } cls.no_username_login = { REDIRECT_FIELD_NAME: cls.index_url, "password": "secret", } def test_login(self): """ Make sure only staff members can log in. Successful posts to the login page will redirect to the original url. Unsuccessful attempts will continue to render the login page with a 200 status code. """ login_url = "%s?next=%s" % (reverse("admin:login"), reverse("admin:index")) # Super User response = self.client.get(self.index_url) self.assertRedirects(response, login_url) login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Test if user enters email address response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.super_email_login) self.assertContains(login, ERROR_MESSAGE) # only correct passwords get a username hint login = self.client.post(login_url, self.super_email_bad_login) self.assertContains(login, ERROR_MESSAGE) new_user = User(username="jondoe", password="secret", email="[email protected]") new_user.save() # check to ensure if there are multiple email addresses a user doesn't get a 500 login = self.client.post(login_url, self.super_email_login) self.assertContains(login, ERROR_MESSAGE) # View User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.viewuser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Add User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.adduser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Change User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.changeuser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Delete User response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.deleteuser_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) # Regular User should not be able to login. response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.joepublic_login) self.assertContains(login, ERROR_MESSAGE) # Requests without username should not return 500 errors. response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) login = self.client.post(login_url, self.no_username_login) self.assertEqual(login.status_code, 200) self.assertFormError( login.context["form"], "username", ["This field is required."] ) def test_login_redirect_for_direct_get(self): """ Login redirect should be to the admin index page when going directly to /admin/login/. """ response = self.client.get(reverse("admin:login")) self.assertEqual(response.status_code, 200) self.assertEqual(response.context[REDIRECT_FIELD_NAME], reverse("admin:index")) def test_login_has_permission(self): # Regular User should not be able to login. response = self.client.get(reverse("has_permission_admin:index")) self.assertEqual(response.status_code, 302) login = self.client.post( reverse("has_permission_admin:login"), self.joepublic_login ) self.assertContains(login, "permission denied") # User with permissions should be able to login. response = self.client.get(reverse("has_permission_admin:index")) self.assertEqual(response.status_code, 302) login = self.client.post( reverse("has_permission_admin:login"), self.nostaff_login ) self.assertRedirects(login, reverse("has_permission_admin:index")) self.assertFalse(login.context) self.client.post(reverse("has_permission_admin:logout")) # Staff should be able to login. response = self.client.get(reverse("has_permission_admin:index")) self.assertEqual(response.status_code, 302) login = self.client.post( reverse("has_permission_admin:login"), { REDIRECT_FIELD_NAME: reverse("has_permission_admin:index"), "username": "deleteuser", "password": "secret", }, ) self.assertRedirects(login, reverse("has_permission_admin:index")) self.assertFalse(login.context) self.client.post(reverse("has_permission_admin:logout")) def test_login_successfully_redirects_to_original_URL(self): response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) query_string = "the-answer=42" redirect_url = "%s?%s" % (self.index_url, query_string) new_next = {REDIRECT_FIELD_NAME: redirect_url} post_data = self.super_login.copy() post_data.pop(REDIRECT_FIELD_NAME) login = self.client.post( "%s?%s" % (reverse("admin:login"), urlencode(new_next)), post_data ) self.assertRedirects(login, redirect_url) def test_double_login_is_not_allowed(self): """Regression test for #19327""" login_url = "%s?next=%s" % (reverse("admin:login"), reverse("admin:index")) response = self.client.get(self.index_url) self.assertEqual(response.status_code, 302) # Establish a valid admin session login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) # Logging in with non-admin user fails login = self.client.post(login_url, self.joepublic_login) self.assertContains(login, ERROR_MESSAGE) # Establish a valid admin session login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) # Logging in with admin user while already logged in login = self.client.post(login_url, self.super_login) self.assertRedirects(login, self.index_url) self.assertFalse(login.context) self.client.post(reverse("admin:logout")) def test_login_page_notice_for_non_staff_users(self): """ A logged-in non-staff user trying to access the admin index should be presented with the login page and a hint indicating that the current user doesn't have access to it. """ hint_template = "You are authenticated as {}" # Anonymous user should not be shown the hint response = self.client.get(self.index_url, follow=True) self.assertContains(response, "login-form") self.assertNotContains(response, hint_template.format(""), status_code=200) # Non-staff user should be shown the hint self.client.force_login(self.nostaffuser) response = self.client.get(self.index_url, follow=True) self.assertContains(response, "login-form") self.assertContains( response, hint_template.format(self.nostaffuser.username), status_code=200 ) def test_add_view(self): """Test add view restricts access and actually adds items.""" add_dict = { "title": "Døm ikke", "content": "<p>great article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", "section": self.s1.pk, } # Change User should not have access to add articles self.client.force_login(self.changeuser) # make sure the view removes test cookie self.assertIs(self.client.session.test_cookie_worked(), False) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.status_code, 403) # Try POST just to make sure post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) self.client.post(reverse("admin:logout")) # View User should not have access to add articles self.client.force_login(self.viewuser) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.status_code, 403) # Try POST just to make sure post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) # Now give the user permission to add but not change. self.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("add", Article._meta)) ) response = self.client.get(reverse("admin:admin_views_article_add")) self.assertEqual(response.context["title"], "Add article") self.assertContains(response, "<title>Add article | Django site admin</title>") self.assertContains( response, '<input type="submit" value="Save and view" name="_continue">' ) post = self.client.post( reverse("admin:admin_views_article_add"), add_dict, follow=False ) self.assertEqual(post.status_code, 302) self.assertEqual(Article.objects.count(), 4) article = Article.objects.latest("pk") response = self.client.get( reverse("admin:admin_views_article_change", args=(article.pk,)) ) self.assertContains( response, '<li class="success">The article “Døm ikke” was added successfully.</li>', ) article.delete() self.client.post(reverse("admin:logout")) # Add user may login and POST to add view, then redirect to admin root self.client.force_login(self.adduser) addpage = self.client.get(reverse("admin:admin_views_article_add")) change_list_link = '&rsaquo; <a href="%s">Articles</a>' % reverse( "admin:admin_views_article_changelist" ) self.assertNotContains( addpage, change_list_link, msg_prefix=( "User restricted to add permission is given link to change list view " "in breadcrumbs." ), ) post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertRedirects(post, self.index_url) self.assertEqual(Article.objects.count(), 4) self.assertEqual(len(mail.outbox), 2) self.assertEqual(mail.outbox[0].subject, "Greetings from a created object") self.client.post(reverse("admin:logout")) # The addition was logged correctly addition_log = LogEntry.objects.all()[0] new_article = Article.objects.last() article_ct = ContentType.objects.get_for_model(Article) self.assertEqual(addition_log.user_id, self.adduser.pk) self.assertEqual(addition_log.content_type_id, article_ct.pk) self.assertEqual(addition_log.object_id, str(new_article.pk)) self.assertEqual(addition_log.object_repr, "Døm ikke") self.assertEqual(addition_log.action_flag, ADDITION) self.assertEqual(addition_log.get_change_message(), "Added.") # Super can add too, but is redirected to the change list view self.client.force_login(self.superuser) addpage = self.client.get(reverse("admin:admin_views_article_add")) self.assertContains( addpage, change_list_link, msg_prefix=( "Unrestricted user is not given link to change list view in " "breadcrumbs." ), ) post = self.client.post(reverse("admin:admin_views_article_add"), add_dict) self.assertRedirects(post, reverse("admin:admin_views_article_changelist")) self.assertEqual(Article.objects.count(), 5) self.client.post(reverse("admin:logout")) # 8509 - if a normal user is already logged in, it is possible # to change user into the superuser without error self.client.force_login(self.joepublicuser) # Check and make sure that if user expires, data still persists self.client.force_login(self.superuser) # make sure the view removes test cookie self.assertIs(self.client.session.test_cookie_worked(), False) @mock.patch("django.contrib.admin.options.InlineModelAdmin.has_change_permission") def test_add_view_with_view_only_inlines(self, has_change_permission): """User with add permission to a section but view-only for inlines.""" self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("add", Section._meta)) ) self.client.force_login(self.viewuser) # Valid POST creates a new section. data = { "name": "New obj", "article_set-TOTAL_FORMS": 0, "article_set-INITIAL_FORMS": 0, } response = self.client.post(reverse("admin:admin_views_section_add"), data) self.assertRedirects(response, reverse("admin:index")) self.assertEqual(Section.objects.latest("id").name, data["name"]) # InlineModelAdmin.has_change_permission()'s obj argument is always # None during object add. self.assertEqual( [obj for (request, obj), _ in has_change_permission.call_args_list], [None, None], ) def test_change_view(self): """Change view should restrict access and allow users to edit items.""" change_dict = { "title": "Ikke fordømt", "content": "<p>edited article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", "section": self.s1.pk, } article_change_url = reverse( "admin:admin_views_article_change", args=(self.a1.pk,) ) article_changelist_url = reverse("admin:admin_views_article_changelist") # add user should not be able to view the list of article or change any of them self.client.force_login(self.adduser) response = self.client.get(article_changelist_url) self.assertEqual(response.status_code, 403) response = self.client.get(article_change_url) self.assertEqual(response.status_code, 403) post = self.client.post(article_change_url, change_dict) self.assertEqual(post.status_code, 403) self.client.post(reverse("admin:logout")) # view user can view articles but not make changes. self.client.force_login(self.viewuser) response = self.client.get(article_changelist_url) self.assertContains( response, "<title>Select article to view | Django site admin</title>", ) self.assertContains(response, "<h1>Select article to view</h1>") self.assertEqual(response.context["title"], "Select article to view") response = self.client.get(article_change_url) self.assertContains(response, "<title>View article | Django site admin</title>") self.assertContains(response, "<h1>View article</h1>") self.assertContains(response, "<label>Extra form field:</label>") self.assertContains( response, '<a href="/test_admin/admin/admin_views/article/" class="closelink">Close' "</a>", ) self.assertEqual(response.context["title"], "View article") post = self.client.post(article_change_url, change_dict) self.assertEqual(post.status_code, 403) self.assertEqual( Article.objects.get(pk=self.a1.pk).content, "<p>Middle content</p>" ) self.client.post(reverse("admin:logout")) # change user can view all items and edit them self.client.force_login(self.changeuser) response = self.client.get(article_changelist_url) self.assertEqual(response.context["title"], "Select article to change") self.assertContains( response, "<title>Select article to change | Django site admin</title>", ) self.assertContains(response, "<h1>Select article to change</h1>") response = self.client.get(article_change_url) self.assertEqual(response.context["title"], "Change article") self.assertContains( response, "<title>Change article | Django site admin</title>", ) self.assertContains(response, "<h1>Change article</h1>") post = self.client.post(article_change_url, change_dict) self.assertRedirects(post, article_changelist_url) self.assertEqual( Article.objects.get(pk=self.a1.pk).content, "<p>edited article</p>" ) # one error in form should produce singular error message, multiple # errors plural. change_dict["title"] = "" post = self.client.post(article_change_url, change_dict) self.assertContains( post, "Please correct the error below.", msg_prefix=( "Singular error message not found in response to post with one error" ), ) change_dict["content"] = "" post = self.client.post(article_change_url, change_dict) self.assertContains( post, "Please correct the errors below.", msg_prefix=( "Plural error message not found in response to post with multiple " "errors" ), ) self.client.post(reverse("admin:logout")) # Test redirection when using row-level change permissions. Refs #11513. r1 = RowLevelChangePermissionModel.objects.create(id=1, name="odd id") r2 = RowLevelChangePermissionModel.objects.create(id=2, name="even id") r3 = RowLevelChangePermissionModel.objects.create(id=3, name="odd id mult 3") r6 = RowLevelChangePermissionModel.objects.create(id=6, name="even id mult 3") change_url_1 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r1.pk,) ) change_url_2 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r2.pk,) ) change_url_3 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r3.pk,) ) change_url_6 = reverse( "admin:admin_views_rowlevelchangepermissionmodel_change", args=(r6.pk,) ) logins = [ self.superuser, self.viewuser, self.adduser, self.changeuser, self.deleteuser, ] for login_user in logins: with self.subTest(login_user.username): self.client.force_login(login_user) response = self.client.get(change_url_1) self.assertEqual(response.status_code, 403) response = self.client.post(change_url_1, {"name": "changed"}) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=1).name, "odd id" ) self.assertEqual(response.status_code, 403) response = self.client.get(change_url_2) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_2, {"name": "changed"}) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=2).name, "changed" ) self.assertRedirects(response, self.index_url) response = self.client.get(change_url_3) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_3, {"name": "changed"}) self.assertEqual(response.status_code, 403) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=3).name, "odd id mult 3", ) response = self.client.get(change_url_6) self.assertEqual(response.status_code, 200) response = self.client.post(change_url_6, {"name": "changed"}) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=6).name, "changed" ) self.assertRedirects(response, self.index_url) self.client.post(reverse("admin:logout")) for login_user in [self.joepublicuser, self.nostaffuser]: with self.subTest(login_user.username): self.client.force_login(login_user) response = self.client.get(change_url_1, follow=True) self.assertContains(response, "login-form") response = self.client.post( change_url_1, {"name": "changed"}, follow=True ) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=1).name, "odd id" ) self.assertContains(response, "login-form") response = self.client.get(change_url_2, follow=True) self.assertContains(response, "login-form") response = self.client.post( change_url_2, {"name": "changed again"}, follow=True ) self.assertEqual( RowLevelChangePermissionModel.objects.get(id=2).name, "changed" ) self.assertContains(response, "login-form") self.client.post(reverse("admin:logout")) def test_change_view_without_object_change_permission(self): """ The object should be read-only if the user has permission to view it and change objects of that type but not to change the current object. """ change_url = reverse("admin9:admin_views_article_change", args=(self.a1.pk,)) self.client.force_login(self.viewuser) response = self.client.get(change_url) self.assertEqual(response.context["title"], "View article") self.assertContains(response, "<title>View article | Django site admin</title>") self.assertContains(response, "<h1>View article</h1>") self.assertContains( response, '<a href="/test_admin/admin9/admin_views/article/" class="closelink">Close' "</a>", ) def test_change_view_save_as_new(self): """ 'Save as new' should raise PermissionDenied for users without the 'add' permission. """ change_dict_save_as_new = { "_saveasnew": "Save as new", "title": "Ikke fordømt", "content": "<p>edited article</p>", "date_0": "2008-03-18", "date_1": "10:54:39", "section": self.s1.pk, } article_change_url = reverse( "admin:admin_views_article_change", args=(self.a1.pk,) ) # Add user can perform "Save as new". article_count = Article.objects.count() self.client.force_login(self.adduser) post = self.client.post(article_change_url, change_dict_save_as_new) self.assertRedirects(post, self.index_url) self.assertEqual(Article.objects.count(), article_count + 1) self.client.logout() # Change user cannot perform "Save as new" (no 'add' permission). article_count = Article.objects.count() self.client.force_login(self.changeuser) post = self.client.post(article_change_url, change_dict_save_as_new) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), article_count) # User with both add and change permissions should be redirected to the # change page for the newly created object. article_count = Article.objects.count() self.client.force_login(self.superuser) post = self.client.post(article_change_url, change_dict_save_as_new) self.assertEqual(Article.objects.count(), article_count + 1) new_article = Article.objects.latest("id") self.assertRedirects( post, reverse("admin:admin_views_article_change", args=(new_article.pk,)) ) def test_change_view_with_view_only_inlines(self): """ User with change permission to a section but view-only for inlines. """ self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("change", Section._meta)) ) self.client.force_login(self.viewuser) # GET shows inlines. response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 3) # Valid POST changes the name. data = { "name": "Can edit name with view-only inlines", "article_set-TOTAL_FORMS": 3, "article_set-INITIAL_FORMS": 3, } response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Section.objects.get(pk=self.s1.pk).name, data["name"]) # Invalid POST reshows inlines. del data["name"] response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 3) def test_change_view_with_view_only_last_inline(self): self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("view", Section._meta)) ) self.client.force_login(self.viewuser) response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 3) # The last inline is not marked as empty. self.assertContains(response, 'id="article_set-2"') def test_change_view_with_view_and_add_inlines(self): """User has view and add permissions on the inline model.""" self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("change", Section._meta)) ) self.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("add", Article._meta)) ) self.client.force_login(self.viewuser) # GET shows inlines. response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 6) # Valid POST creates a new article. data = { "name": "Can edit name with view-only inlines", "article_set-TOTAL_FORMS": 6, "article_set-INITIAL_FORMS": 3, "article_set-3-id": [""], "article_set-3-title": ["A title"], "article_set-3-content": ["Added content"], "article_set-3-date_0": ["2008-3-18"], "article_set-3-date_1": ["11:54:58"], "article_set-3-section": [str(self.s1.pk)], } response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Section.objects.get(pk=self.s1.pk).name, data["name"]) self.assertEqual(Article.objects.count(), 4) # Invalid POST reshows inlines. del data["name"] response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.context["inline_admin_formsets"]), 1) formset = response.context["inline_admin_formsets"][0] self.assertEqual(len(formset.forms), 6) def test_change_view_with_view_and_delete_inlines(self): """User has view and delete permissions on the inline model.""" self.viewuser.user_permissions.add( get_perm(Section, get_permission_codename("change", Section._meta)) ) self.client.force_login(self.viewuser) data = { "name": "Name is required.", "article_set-TOTAL_FORMS": 6, "article_set-INITIAL_FORMS": 3, "article_set-0-id": [str(self.a1.pk)], "article_set-0-DELETE": ["on"], } # Inline POST details are ignored without delete permission. response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Article.objects.count(), 3) # Deletion successful when delete permission is added. self.viewuser.user_permissions.add( get_perm(Article, get_permission_codename("delete", Article._meta)) ) data = { "name": "Name is required.", "article_set-TOTAL_FORMS": 6, "article_set-INITIAL_FORMS": 3, "article_set-0-id": [str(self.a1.pk)], "article_set-0-DELETE": ["on"], } response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), data ) self.assertRedirects(response, reverse("admin:admin_views_section_changelist")) self.assertEqual(Article.objects.count(), 2) def test_delete_view(self): """Delete view should restrict access and actually delete items.""" delete_dict = {"post": "yes"} delete_url = reverse("admin:admin_views_article_delete", args=(self.a1.pk,)) # add user should not be able to delete articles self.client.force_login(self.adduser) response = self.client.get(delete_url) self.assertEqual(response.status_code, 403) post = self.client.post(delete_url, delete_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) self.client.logout() # view user should not be able to delete articles self.client.force_login(self.viewuser) response = self.client.get(delete_url) self.assertEqual(response.status_code, 403) post = self.client.post(delete_url, delete_dict) self.assertEqual(post.status_code, 403) self.assertEqual(Article.objects.count(), 3) self.client.logout() # Delete user can delete self.client.force_login(self.deleteuser) response = self.client.get( reverse("admin:admin_views_section_delete", args=(self.s1.pk,)) ) self.assertContains(response, "<h2>Summary</h2>") self.assertContains(response, "<li>Articles: 3</li>") # test response contains link to related Article self.assertContains(response, "admin_views/article/%s/" % self.a1.pk) response = self.client.get(delete_url) self.assertContains(response, "admin_views/article/%s/" % self.a1.pk) self.assertContains(response, "<h2>Summary</h2>") self.assertContains(response, "<li>Articles: 1</li>") post = self.client.post(delete_url, delete_dict) self.assertRedirects(post, self.index_url) self.assertEqual(Article.objects.count(), 2) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Greetings from a deleted object") article_ct = ContentType.objects.get_for_model(Article) logged = LogEntry.objects.get(content_type=article_ct, action_flag=DELETION) self.assertEqual(logged.object_id, str(self.a1.pk)) def test_delete_view_with_no_default_permissions(self): """ The delete view allows users to delete collected objects without a 'delete' permission (ReadOnlyPizza.Meta.default_permissions is empty). """ pizza = ReadOnlyPizza.objects.create(name="Double Cheese") delete_url = reverse("admin:admin_views_readonlypizza_delete", args=(pizza.pk,)) self.client.force_login(self.adduser) response = self.client.get(delete_url) self.assertContains(response, "admin_views/readonlypizza/%s/" % pizza.pk) self.assertContains(response, "<h2>Summary</h2>") self.assertContains(response, "<li>Read only pizzas: 1</li>") post = self.client.post(delete_url, {"post": "yes"}) self.assertRedirects( post, reverse("admin:admin_views_readonlypizza_changelist") ) self.assertEqual(ReadOnlyPizza.objects.count(), 0) def test_delete_view_nonexistent_obj(self): self.client.force_login(self.deleteuser) url = reverse("admin:admin_views_article_delete", args=("nonexistent",)) response = self.client.get(url, follow=True) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["article with ID “nonexistent” doesn’t exist. Perhaps it was deleted?"], ) def test_history_view(self): """History view should restrict access.""" # add user should not be able to view the list of article or change any of them self.client.force_login(self.adduser) response = self.client.get( reverse("admin:admin_views_article_history", args=(self.a1.pk,)) ) self.assertEqual(response.status_code, 403) self.client.post(reverse("admin:logout")) # view user can view all items self.client.force_login(self.viewuser) response = self.client.get( reverse("admin:admin_views_article_history", args=(self.a1.pk,)) ) self.assertEqual(response.status_code, 200) self.client.post(reverse("admin:logout")) # change user can view all items and edit them self.client.force_login(self.changeuser) response = self.client.get( reverse("admin:admin_views_article_history", args=(self.a1.pk,)) ) self.assertEqual(response.status_code, 200) # Test redirection when using row-level change permissions. Refs #11513. rl1 = RowLevelChangePermissionModel.objects.create(id=1, name="odd id") rl2 = RowLevelChangePermissionModel.objects.create(id=2, name="even id") logins = [ self.superuser, self.viewuser, self.adduser, self.changeuser, self.deleteuser, ] for login_user in logins: with self.subTest(login_user.username): self.client.force_login(login_user) url = reverse( "admin:admin_views_rowlevelchangepermissionmodel_history", args=(rl1.pk,), ) response = self.client.get(url) self.assertEqual(response.status_code, 403) url = reverse( "admin:admin_views_rowlevelchangepermissionmodel_history", args=(rl2.pk,), ) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.client.post(reverse("admin:logout")) for login_user in [self.joepublicuser, self.nostaffuser]: with self.subTest(login_user.username): self.client.force_login(login_user) url = reverse( "admin:admin_views_rowlevelchangepermissionmodel_history", args=(rl1.pk,), ) response = self.client.get(url, follow=True) self.assertContains(response, "login-form") url = reverse( "admin:admin_views_rowlevelchangepermissionmodel_history", args=(rl2.pk,), ) response = self.client.get(url, follow=True) self.assertContains(response, "login-form") self.client.post(reverse("admin:logout")) def test_history_view_bad_url(self): self.client.force_login(self.changeuser) response = self.client.get( reverse("admin:admin_views_article_history", args=("foo",)), follow=True ) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["article with ID “foo” doesn’t exist. Perhaps it was deleted?"], ) def test_conditionally_show_add_section_link(self): """ The foreign key widget should only show the "add related" button if the user has permission to add that related item. """ self.client.force_login(self.adduser) # The user can't add sections yet, so they shouldn't see the "add section" link. url = reverse("admin:admin_views_article_add") add_link_text = "add_id_section" response = self.client.get(url) self.assertNotContains(response, add_link_text) # Allow the user to add sections too. Now they can see the "add section" link. user = User.objects.get(username="adduser") perm = get_perm(Section, get_permission_codename("add", Section._meta)) user.user_permissions.add(perm) response = self.client.get(url) self.assertContains(response, add_link_text) def test_conditionally_show_change_section_link(self): """ The foreign key widget should only show the "change related" button if the user has permission to change that related item. """ def get_change_related(response): return ( response.context["adminform"] .form.fields["section"] .widget.can_change_related ) self.client.force_login(self.adduser) # The user can't change sections yet, so they shouldn't see the # "change section" link. url = reverse("admin:admin_views_article_add") change_link_text = "change_id_section" response = self.client.get(url) self.assertFalse(get_change_related(response)) self.assertNotContains(response, change_link_text) # Allow the user to change sections too. Now they can see the # "change section" link. user = User.objects.get(username="adduser") perm = get_perm(Section, get_permission_codename("change", Section._meta)) user.user_permissions.add(perm) response = self.client.get(url) self.assertTrue(get_change_related(response)) self.assertContains(response, change_link_text) def test_conditionally_show_delete_section_link(self): """ The foreign key widget should only show the "delete related" button if the user has permission to delete that related item. """ def get_delete_related(response): return ( response.context["adminform"] .form.fields["sub_section"] .widget.can_delete_related ) self.client.force_login(self.adduser) # The user can't delete sections yet, so they shouldn't see the # "delete section" link. url = reverse("admin:admin_views_article_add") delete_link_text = "delete_id_sub_section" response = self.client.get(url) self.assertFalse(get_delete_related(response)) self.assertNotContains(response, delete_link_text) # Allow the user to delete sections too. Now they can see the # "delete section" link. user = User.objects.get(username="adduser") perm = get_perm(Section, get_permission_codename("delete", Section._meta)) user.user_permissions.add(perm) response = self.client.get(url) self.assertTrue(get_delete_related(response)) self.assertContains(response, delete_link_text) def test_disabled_permissions_when_logged_in(self): self.client.force_login(self.superuser) superuser = User.objects.get(username="super") superuser.is_active = False superuser.save() response = self.client.get(self.index_url, follow=True) self.assertContains(response, 'id="login-form"') self.assertNotContains(response, "Log out") response = self.client.get(reverse("secure_view"), follow=True) self.assertContains(response, 'id="login-form"') def test_disabled_staff_permissions_when_logged_in(self): self.client.force_login(self.superuser) superuser = User.objects.get(username="super") superuser.is_staff = False superuser.save() response = self.client.get(self.index_url, follow=True) self.assertContains(response, 'id="login-form"') self.assertNotContains(response, "Log out") response = self.client.get(reverse("secure_view"), follow=True) self.assertContains(response, 'id="login-form"') def test_app_list_permissions(self): """ If a user has no module perms, the app list returns a 404. """ opts = Article._meta change_user = User.objects.get(username="changeuser") permission = get_perm(Article, get_permission_codename("change", opts)) self.client.force_login(self.changeuser) # the user has no module permissions change_user.user_permissions.remove(permission) response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertEqual(response.status_code, 404) # the user now has module permissions change_user.user_permissions.add(permission) response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertEqual(response.status_code, 200) def test_shortcut_view_only_available_to_staff(self): """ Only admin users should be able to use the admin shortcut view. """ model_ctype = ContentType.objects.get_for_model(ModelWithStringPrimaryKey) obj = ModelWithStringPrimaryKey.objects.create(string_pk="foo") shortcut_url = reverse("admin:view_on_site", args=(model_ctype.pk, obj.pk)) # Not logged in: we should see the login page. response = self.client.get(shortcut_url, follow=True) self.assertTemplateUsed(response, "admin/login.html") # Logged in? Redirect. self.client.force_login(self.superuser) response = self.client.get(shortcut_url, follow=False) # Can't use self.assertRedirects() because User.get_absolute_url() is silly. self.assertEqual(response.status_code, 302) # Domain may depend on contrib.sites tests also run self.assertRegex(response.url, "http://(testserver|example.com)/dummy/foo/") def test_has_module_permission(self): """ has_module_permission() returns True for all users who have any permission for that module (add, change, or delete), so that the module is displayed on the admin index page. """ self.client.force_login(self.superuser) response = self.client.get(self.index_url) self.assertContains(response, "admin_views") self.assertContains(response, "Articles") self.client.logout() self.client.force_login(self.viewuser) response = self.client.get(self.index_url) self.assertContains(response, "admin_views") self.assertContains(response, "Articles") self.client.logout() self.client.force_login(self.adduser) response = self.client.get(self.index_url) self.assertContains(response, "admin_views") self.assertContains(response, "Articles") self.client.logout() self.client.force_login(self.changeuser) response = self.client.get(self.index_url) self.assertContains(response, "admin_views") self.assertContains(response, "Articles") self.client.logout() self.client.force_login(self.deleteuser) response = self.client.get(self.index_url) self.assertContains(response, "admin_views") self.assertContains(response, "Articles") def test_overriding_has_module_permission(self): """ If has_module_permission() always returns False, the module shouldn't be displayed on the admin index page for any users. """ articles = Article._meta.verbose_name_plural.title() sections = Section._meta.verbose_name_plural.title() index_url = reverse("admin7:index") self.client.force_login(self.superuser) response = self.client.get(index_url) self.assertContains(response, sections) self.assertNotContains(response, articles) self.client.logout() self.client.force_login(self.viewuser) response = self.client.get(index_url) self.assertNotContains(response, "admin_views") self.assertNotContains(response, articles) self.client.logout() self.client.force_login(self.adduser) response = self.client.get(index_url) self.assertNotContains(response, "admin_views") self.assertNotContains(response, articles) self.client.logout() self.client.force_login(self.changeuser) response = self.client.get(index_url) self.assertNotContains(response, "admin_views") self.assertNotContains(response, articles) self.client.logout() self.client.force_login(self.deleteuser) response = self.client.get(index_url) self.assertNotContains(response, articles) # The app list displays Sections but not Articles as the latter has # ModelAdmin.has_module_permission() = False. self.client.force_login(self.superuser) response = self.client.get(reverse("admin7:app_list", args=("admin_views",))) self.assertContains(response, sections) self.assertNotContains(response, articles) def test_post_save_message_no_forbidden_links_visible(self): """ Post-save message shouldn't contain a link to the change form if the user doesn't have the change permission. """ self.client.force_login(self.adduser) # Emulate Article creation for user with add-only permission. post_data = { "title": "Fun & games", "content": "Some content", "date_0": "2015-10-31", "date_1": "16:35:00", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_article_add"), post_data, follow=True ) self.assertContains( response, '<li class="success">The article “Fun &amp; games” was added successfully.' "</li>", html=True, ) @override_settings( ROOT_URLCONF="admin_views.urls", TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ], ) class AdminViewProxyModelPermissionsTests(TestCase): """Tests for proxy models permissions in the admin.""" @classmethod def setUpTestData(cls): cls.viewuser = User.objects.create_user( username="viewuser", password="secret", is_staff=True ) cls.adduser = User.objects.create_user( username="adduser", password="secret", is_staff=True ) cls.changeuser = User.objects.create_user( username="changeuser", password="secret", is_staff=True ) cls.deleteuser = User.objects.create_user( username="deleteuser", password="secret", is_staff=True ) # Setup permissions. opts = UserProxy._meta cls.viewuser.user_permissions.add( get_perm(UserProxy, get_permission_codename("view", opts)) ) cls.adduser.user_permissions.add( get_perm(UserProxy, get_permission_codename("add", opts)) ) cls.changeuser.user_permissions.add( get_perm(UserProxy, get_permission_codename("change", opts)) ) cls.deleteuser.user_permissions.add( get_perm(UserProxy, get_permission_codename("delete", opts)) ) # UserProxy instances. cls.user_proxy = UserProxy.objects.create( username="user_proxy", password="secret" ) def test_add(self): self.client.force_login(self.adduser) url = reverse("admin:admin_views_userproxy_add") data = { "username": "can_add", "password": "secret", "date_joined_0": "2019-01-15", "date_joined_1": "16:59:10", } response = self.client.post(url, data, follow=True) self.assertEqual(response.status_code, 200) self.assertTrue(UserProxy.objects.filter(username="can_add").exists()) def test_view(self): self.client.force_login(self.viewuser) response = self.client.get(reverse("admin:admin_views_userproxy_changelist")) self.assertContains(response, "<h1>Select user proxy to view</h1>") response = self.client.get( reverse("admin:admin_views_userproxy_change", args=(self.user_proxy.pk,)) ) self.assertContains(response, "<h1>View user proxy</h1>") self.assertContains(response, '<div class="readonly">user_proxy</div>') def test_change(self): self.client.force_login(self.changeuser) data = { "password": self.user_proxy.password, "username": self.user_proxy.username, "date_joined_0": self.user_proxy.date_joined.strftime("%Y-%m-%d"), "date_joined_1": self.user_proxy.date_joined.strftime("%H:%M:%S"), "first_name": "first_name", } url = reverse("admin:admin_views_userproxy_change", args=(self.user_proxy.pk,)) response = self.client.post(url, data) self.assertRedirects( response, reverse("admin:admin_views_userproxy_changelist") ) self.assertEqual( UserProxy.objects.get(pk=self.user_proxy.pk).first_name, "first_name" ) def test_delete(self): self.client.force_login(self.deleteuser) url = reverse("admin:admin_views_userproxy_delete", args=(self.user_proxy.pk,)) response = self.client.post(url, {"post": "yes"}, follow=True) self.assertEqual(response.status_code, 200) self.assertFalse(UserProxy.objects.filter(pk=self.user_proxy.pk).exists()) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewsNoUrlTest(TestCase): """Regression test for #17333""" @classmethod def setUpTestData(cls): # User who can change Reports cls.changeuser = User.objects.create_user( username="changeuser", password="secret", is_staff=True ) cls.changeuser.user_permissions.add( get_perm(Report, get_permission_codename("change", Report._meta)) ) def test_no_standard_modeladmin_urls(self): """Admin index views don't break when user's ModelAdmin removes standard urls""" self.client.force_login(self.changeuser) r = self.client.get(reverse("admin:index")) # we shouldn't get a 500 error caused by a NoReverseMatch self.assertEqual(r.status_code, 200) self.client.post(reverse("admin:logout")) @skipUnlessDBFeature("can_defer_constraint_checks") @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewDeletedObjectsTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.deleteuser = User.objects.create_user( username="deleteuser", password="secret", is_staff=True ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.v1 = Villain.objects.create(name="Adam") cls.v2 = Villain.objects.create(name="Sue") cls.sv1 = SuperVillain.objects.create(name="Bob") cls.pl1 = Plot.objects.create( name="World Domination", team_leader=cls.v1, contact=cls.v2 ) cls.pl2 = Plot.objects.create( name="World Peace", team_leader=cls.v2, contact=cls.v2 ) cls.pl3 = Plot.objects.create( name="Corn Conspiracy", team_leader=cls.v1, contact=cls.v1 ) cls.pd1 = PlotDetails.objects.create(details="almost finished", plot=cls.pl1) cls.sh1 = SecretHideout.objects.create( location="underground bunker", villain=cls.v1 ) cls.sh2 = SecretHideout.objects.create( location="floating castle", villain=cls.sv1 ) cls.ssh1 = SuperSecretHideout.objects.create( location="super floating castle!", supervillain=cls.sv1 ) cls.cy1 = CyclicOne.objects.create(pk=1, name="I am recursive", two_id=1) cls.cy2 = CyclicTwo.objects.create(pk=1, name="I am recursive too", one_id=1) def setUp(self): self.client.force_login(self.superuser) def test_nesting(self): """ Objects should be nested to display the relationships that cause them to be scheduled for deletion. """ pattern = re.compile( r'<li>Plot: <a href="%s">World Domination</a>\s*<ul>\s*' r'<li>Plot details: <a href="%s">almost finished</a>' % ( reverse("admin:admin_views_plot_change", args=(self.pl1.pk,)), reverse("admin:admin_views_plotdetails_change", args=(self.pd1.pk,)), ) ) response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.v1.pk,)) ) self.assertRegex(response.content.decode(), pattern) def test_cyclic(self): """ Cyclic relationships should still cause each object to only be listed once. """ one = '<li>Cyclic one: <a href="%s">I am recursive</a>' % ( reverse("admin:admin_views_cyclicone_change", args=(self.cy1.pk,)), ) two = '<li>Cyclic two: <a href="%s">I am recursive too</a>' % ( reverse("admin:admin_views_cyclictwo_change", args=(self.cy2.pk,)), ) response = self.client.get( reverse("admin:admin_views_cyclicone_delete", args=(self.cy1.pk,)) ) self.assertContains(response, one, 1) self.assertContains(response, two, 1) def test_perms_needed(self): self.client.logout() delete_user = User.objects.get(username="deleteuser") delete_user.user_permissions.add( get_perm(Plot, get_permission_codename("delete", Plot._meta)) ) self.client.force_login(self.deleteuser) response = self.client.get( reverse("admin:admin_views_plot_delete", args=(self.pl1.pk,)) ) self.assertContains( response, "your account doesn't have permission to delete the following types of " "objects", ) self.assertContains(response, "<li>plot details</li>") def test_protected(self): q = Question.objects.create(question="Why?") a1 = Answer.objects.create(question=q, answer="Because.") a2 = Answer.objects.create(question=q, answer="Yes.") response = self.client.get( reverse("admin:admin_views_question_delete", args=(q.pk,)) ) self.assertContains( response, "would require deleting the following protected related objects" ) self.assertContains( response, '<li>Answer: <a href="%s">Because.</a></li>' % reverse("admin:admin_views_answer_change", args=(a1.pk,)), ) self.assertContains( response, '<li>Answer: <a href="%s">Yes.</a></li>' % reverse("admin:admin_views_answer_change", args=(a2.pk,)), ) def test_post_delete_protected(self): """ A POST request to delete protected objects should display the page which says the deletion is prohibited. """ q = Question.objects.create(question="Why?") Answer.objects.create(question=q, answer="Because.") response = self.client.post( reverse("admin:admin_views_question_delete", args=(q.pk,)), {"post": "yes"} ) self.assertEqual(Question.objects.count(), 1) self.assertContains( response, "would require deleting the following protected related objects" ) def test_restricted(self): album = Album.objects.create(title="Amaryllis") song = Song.objects.create(album=album, name="Unity") response = self.client.get( reverse("admin:admin_views_album_delete", args=(album.pk,)) ) self.assertContains( response, "would require deleting the following protected related objects", ) self.assertContains( response, '<li>Song: <a href="%s">Unity</a></li>' % reverse("admin:admin_views_song_change", args=(song.pk,)), ) def test_post_delete_restricted(self): album = Album.objects.create(title="Amaryllis") Song.objects.create(album=album, name="Unity") response = self.client.post( reverse("admin:admin_views_album_delete", args=(album.pk,)), {"post": "yes"}, ) self.assertEqual(Album.objects.count(), 1) self.assertContains( response, "would require deleting the following protected related objects", ) def test_not_registered(self): should_contain = """<li>Secret hideout: underground bunker""" response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.v1.pk,)) ) self.assertContains(response, should_contain, 1) def test_multiple_fkeys_to_same_model(self): """ If a deleted object has two relationships from another model, both of those should be followed in looking for related objects to delete. """ should_contain = '<li>Plot: <a href="%s">World Domination</a>' % reverse( "admin:admin_views_plot_change", args=(self.pl1.pk,) ) response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.v1.pk,)) ) self.assertContains(response, should_contain) response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.v2.pk,)) ) self.assertContains(response, should_contain) def test_multiple_fkeys_to_same_instance(self): """ If a deleted object has two relationships pointing to it from another object, the other object should still only be listed once. """ should_contain = '<li>Plot: <a href="%s">World Peace</a></li>' % reverse( "admin:admin_views_plot_change", args=(self.pl2.pk,) ) response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.v2.pk,)) ) self.assertContains(response, should_contain, 1) def test_inheritance(self): """ In the case of an inherited model, if either the child or parent-model instance is deleted, both instances are listed for deletion, as well as any relationships they have. """ should_contain = [ '<li>Villain: <a href="%s">Bob</a>' % reverse("admin:admin_views_villain_change", args=(self.sv1.pk,)), '<li>Super villain: <a href="%s">Bob</a>' % reverse("admin:admin_views_supervillain_change", args=(self.sv1.pk,)), "<li>Secret hideout: floating castle", "<li>Super secret hideout: super floating castle!", ] response = self.client.get( reverse("admin:admin_views_villain_delete", args=(self.sv1.pk,)) ) for should in should_contain: self.assertContains(response, should, 1) response = self.client.get( reverse("admin:admin_views_supervillain_delete", args=(self.sv1.pk,)) ) for should in should_contain: self.assertContains(response, should, 1) def test_generic_relations(self): """ If a deleted object has GenericForeignKeys pointing to it, those objects should be listed for deletion. """ plot = self.pl3 tag = FunkyTag.objects.create(content_object=plot, name="hott") should_contain = '<li>Funky tag: <a href="%s">hott' % reverse( "admin:admin_views_funkytag_change", args=(tag.id,) ) response = self.client.get( reverse("admin:admin_views_plot_delete", args=(plot.pk,)) ) self.assertContains(response, should_contain) def test_generic_relations_with_related_query_name(self): """ If a deleted object has GenericForeignKey with GenericRelation(related_query_name='...') pointing to it, those objects should be listed for deletion. """ bookmark = Bookmark.objects.create(name="djangoproject") tag = FunkyTag.objects.create(content_object=bookmark, name="django") tag_url = reverse("admin:admin_views_funkytag_change", args=(tag.id,)) should_contain = '<li>Funky tag: <a href="%s">django' % tag_url response = self.client.get( reverse("admin:admin_views_bookmark_delete", args=(bookmark.pk,)) ) self.assertContains(response, should_contain) def test_delete_view_uses_get_deleted_objects(self): """The delete view uses ModelAdmin.get_deleted_objects().""" book = Book.objects.create(name="Test Book") response = self.client.get( reverse("admin2:admin_views_book_delete", args=(book.pk,)) ) # BookAdmin.get_deleted_objects() returns custom text. self.assertContains(response, "a deletable object") @override_settings(ROOT_URLCONF="admin_views.urls") class TestGenericRelations(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.v1 = Villain.objects.create(name="Adam") cls.pl3 = Plot.objects.create( name="Corn Conspiracy", team_leader=cls.v1, contact=cls.v1 ) def setUp(self): self.client.force_login(self.superuser) def test_generic_content_object_in_list_display(self): FunkyTag.objects.create(content_object=self.pl3, name="hott") response = self.client.get(reverse("admin:admin_views_funkytag_changelist")) self.assertContains(response, "%s</td>" % self.pl3) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewStringPrimaryKeyTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.pk = ( "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 " r"""-_.!~*'() ;/?:@&=+$, <>#%" {}|\^[]`""" ) cls.m1 = ModelWithStringPrimaryKey.objects.create(string_pk=cls.pk) content_type_pk = ContentType.objects.get_for_model( ModelWithStringPrimaryKey ).pk user_pk = cls.superuser.pk LogEntry.objects.log_action( user_pk, content_type_pk, cls.pk, cls.pk, 2, change_message="Changed something", ) def setUp(self): self.client.force_login(self.superuser) def test_get_history_view(self): """ Retrieving the history for an object using urlencoded form of primary key should work. Refs #12349, #18550. """ response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_history", args=(self.pk,) ) ) self.assertContains(response, escape(self.pk)) self.assertContains(response, "Changed something") def test_get_change_view(self): "Retrieving the object using urlencoded form of primary key should work" response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(self.pk,) ) ) self.assertContains(response, escape(self.pk)) def test_changelist_to_changeform_link(self): """ Link to the changeform of the object in changelist should use reverse() and be quoted. """ response = self.client.get( reverse("admin:admin_views_modelwithstringprimarykey_changelist") ) # this URL now comes through reverse(), thus url quoting and iri_to_uri encoding pk_final_url = escape(iri_to_uri(quote(self.pk))) change_url = reverse( "admin:admin_views_modelwithstringprimarykey_change", args=("__fk__",) ).replace("__fk__", pk_final_url) should_contain = '<th class="field-__str__"><a href="%s">%s</a></th>' % ( change_url, escape(self.pk), ) self.assertContains(response, should_contain) def test_recentactions_link(self): """ The link from the recent actions list referring to the changeform of the object should be quoted. """ response = self.client.get(reverse("admin:index")) link = reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(self.pk),) ) should_contain = """<a href="%s">%s</a>""" % (escape(link), escape(self.pk)) self.assertContains(response, should_contain) def test_deleteconfirmation_link(self): """ " The link from the delete confirmation page referring back to the changeform of the object should be quoted. """ url = reverse( "admin:admin_views_modelwithstringprimarykey_delete", args=(quote(self.pk),) ) response = self.client.get(url) # this URL now comes through reverse(), thus url quoting and iri_to_uri encoding change_url = reverse( "admin:admin_views_modelwithstringprimarykey_change", args=("__fk__",) ).replace("__fk__", escape(iri_to_uri(quote(self.pk)))) should_contain = '<a href="%s">%s</a>' % (change_url, escape(self.pk)) self.assertContains(response, should_contain) def test_url_conflicts_with_add(self): "A model with a primary key that ends with add or is `add` should be visible" add_model = ModelWithStringPrimaryKey.objects.create( pk="i have something to add" ) add_model.save() response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(add_model.pk),), ) ) should_contain = """<h1>Change model with string primary key</h1>""" self.assertContains(response, should_contain) add_model2 = ModelWithStringPrimaryKey.objects.create(pk="add") add_url = reverse("admin:admin_views_modelwithstringprimarykey_add") change_url = reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(add_model2.pk),), ) self.assertNotEqual(add_url, change_url) def test_url_conflicts_with_delete(self): "A model with a primary key that ends with delete should be visible" delete_model = ModelWithStringPrimaryKey(pk="delete") delete_model.save() response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(delete_model.pk),), ) ) should_contain = """<h1>Change model with string primary key</h1>""" self.assertContains(response, should_contain) def test_url_conflicts_with_history(self): "A model with a primary key that ends with history should be visible" history_model = ModelWithStringPrimaryKey(pk="history") history_model.save() response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(history_model.pk),), ) ) should_contain = """<h1>Change model with string primary key</h1>""" self.assertContains(response, should_contain) def test_shortcut_view_with_escaping(self): "'View on site should' work properly with char fields" model = ModelWithStringPrimaryKey(pk="abc_123") model.save() response = self.client.get( reverse( "admin:admin_views_modelwithstringprimarykey_change", args=(quote(model.pk),), ) ) should_contain = '/%s/" class="viewsitelink">' % model.pk self.assertContains(response, should_contain) def test_change_view_history_link(self): """Object history button link should work and contain the pk value quoted.""" url = reverse( "admin:%s_modelwithstringprimarykey_change" % ModelWithStringPrimaryKey._meta.app_label, args=(quote(self.pk),), ) response = self.client.get(url) self.assertEqual(response.status_code, 200) expected_link = reverse( "admin:%s_modelwithstringprimarykey_history" % ModelWithStringPrimaryKey._meta.app_label, args=(quote(self.pk),), ) self.assertContains( response, '<a href="%s" class="historylink"' % escape(expected_link) ) def test_redirect_on_add_view_continue_button(self): """As soon as an object is added using "Save and continue editing" button, the user should be redirected to the object's change_view. In case primary key is a string containing some special characters like slash or underscore, these characters must be escaped (see #22266) """ response = self.client.post( reverse("admin:admin_views_modelwithstringprimarykey_add"), { "string_pk": "123/history", "_continue": "1", # Save and continue editing }, ) self.assertEqual(response.status_code, 302) # temporary redirect self.assertIn("/123_2Fhistory/", response.headers["location"]) # PK is quoted @override_settings(ROOT_URLCONF="admin_views.urls") class SecureViewTests(TestCase): """ Test behavior of a view protected by the staff_member_required decorator. """ def test_secure_view_shows_login_if_not_logged_in(self): secure_url = reverse("secure_view") response = self.client.get(secure_url) self.assertRedirects( response, "%s?next=%s" % (reverse("admin:login"), secure_url) ) response = self.client.get(secure_url, follow=True) self.assertTemplateUsed(response, "admin/login.html") self.assertEqual(response.context[REDIRECT_FIELD_NAME], secure_url) def test_staff_member_required_decorator_works_with_argument(self): """ Staff_member_required decorator works with an argument (redirect_field_name). """ secure_url = "/test_admin/admin/secure-view2/" response = self.client.get(secure_url) self.assertRedirects( response, "%s?myfield=%s" % (reverse("admin:login"), secure_url) ) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewUnicodeTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.b1 = Book.objects.create(name="Lærdommer") cls.p1 = Promo.objects.create(name="<Promo for Lærdommer>", book=cls.b1) cls.chap1 = Chapter.objects.create( title="Norske bostaver æøå skaper problemer", content="<p>Svært frustrerende med UnicodeDecodeErro</p>", book=cls.b1, ) cls.chap2 = Chapter.objects.create( title="Kjærlighet", content="<p>La kjærligheten til de lidende seire.</p>", book=cls.b1, ) cls.chap3 = Chapter.objects.create( title="Kjærlighet", content="<p>Noe innhold</p>", book=cls.b1 ) cls.chap4 = ChapterXtra1.objects.create( chap=cls.chap1, xtra="<Xtra(1) Norske bostaver æøå skaper problemer>" ) cls.chap5 = ChapterXtra1.objects.create( chap=cls.chap2, xtra="<Xtra(1) Kjærlighet>" ) cls.chap6 = ChapterXtra1.objects.create( chap=cls.chap3, xtra="<Xtra(1) Kjærlighet>" ) cls.chap7 = ChapterXtra2.objects.create( chap=cls.chap1, xtra="<Xtra(2) Norske bostaver æøå skaper problemer>" ) cls.chap8 = ChapterXtra2.objects.create( chap=cls.chap2, xtra="<Xtra(2) Kjærlighet>" ) cls.chap9 = ChapterXtra2.objects.create( chap=cls.chap3, xtra="<Xtra(2) Kjærlighet>" ) def setUp(self): self.client.force_login(self.superuser) def test_unicode_edit(self): """ A test to ensure that POST on edit_view handles non-ASCII characters. """ post_data = { "name": "Test lærdommer", # inline data "chapter_set-TOTAL_FORMS": "6", "chapter_set-INITIAL_FORMS": "3", "chapter_set-MAX_NUM_FORMS": "0", "chapter_set-0-id": self.chap1.pk, "chapter_set-0-title": "Norske bostaver æøå skaper problemer", "chapter_set-0-content": ( "&lt;p&gt;Svært frustrerende med UnicodeDecodeError&lt;/p&gt;" ), "chapter_set-1-id": self.chap2.id, "chapter_set-1-title": "Kjærlighet.", "chapter_set-1-content": ( "&lt;p&gt;La kjærligheten til de lidende seire.&lt;/p&gt;" ), "chapter_set-2-id": self.chap3.id, "chapter_set-2-title": "Need a title.", "chapter_set-2-content": "&lt;p&gt;Newest content&lt;/p&gt;", "chapter_set-3-id": "", "chapter_set-3-title": "", "chapter_set-3-content": "", "chapter_set-4-id": "", "chapter_set-4-title": "", "chapter_set-4-content": "", "chapter_set-5-id": "", "chapter_set-5-title": "", "chapter_set-5-content": "", } response = self.client.post( reverse("admin:admin_views_book_change", args=(self.b1.pk,)), post_data ) self.assertEqual(response.status_code, 302) # redirect somewhere def test_unicode_delete(self): """ The delete_view handles non-ASCII characters """ delete_dict = {"post": "yes"} delete_url = reverse("admin:admin_views_book_delete", args=(self.b1.pk,)) response = self.client.get(delete_url) self.assertEqual(response.status_code, 200) response = self.client.post(delete_url, delete_dict) self.assertRedirects(response, reverse("admin:admin_views_book_changelist")) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewListEditable(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) cls.per2 = Person.objects.create(name="Grace Hopper", gender=1, alive=False) cls.per3 = Person.objects.create(name="Guido van Rossum", gender=1, alive=True) def setUp(self): self.client.force_login(self.superuser) def test_inheritance(self): Podcast.objects.create( name="This Week in Django", release_date=datetime.date.today() ) response = self.client.get(reverse("admin:admin_views_podcast_changelist")) self.assertEqual(response.status_code, 200) def test_inheritance_2(self): Vodcast.objects.create(name="This Week in Django", released=True) response = self.client.get(reverse("admin:admin_views_vodcast_changelist")) self.assertEqual(response.status_code, 200) def test_custom_pk(self): Language.objects.create(iso="en", name="English", english_name="English") response = self.client.get(reverse("admin:admin_views_language_changelist")) self.assertEqual(response.status_code, 200) def test_changelist_input_html(self): response = self.client.get(reverse("admin:admin_views_person_changelist")) # 2 inputs per object(the field and the hidden id field) = 6 # 4 management hidden fields = 4 # 4 action inputs (3 regular checkboxes, 1 checkbox to select all) # main form submit button = 1 # search field and search submit button = 2 # CSRF field = 2 # field to track 'select all' across paginated views = 1 # 6 + 4 + 4 + 1 + 2 + 2 + 1 = 20 inputs self.assertContains(response, "<input", count=21) # 1 select per object = 3 selects self.assertContains(response, "<select", count=4) def test_post_messages(self): # Ticket 12707: Saving inline editable should not show admin # action warnings data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-gender": "1", "form-0-id": str(self.per1.pk), "form-1-gender": "2", "form-1-id": str(self.per2.pk), "form-2-alive": "checked", "form-2-gender": "1", "form-2-id": str(self.per3.pk), "_save": "Save", } response = self.client.post( reverse("admin:admin_views_person_changelist"), data, follow=True ) self.assertEqual(len(response.context["messages"]), 1) def test_post_submission(self): data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-gender": "1", "form-0-id": str(self.per1.pk), "form-1-gender": "2", "form-1-id": str(self.per2.pk), "form-2-alive": "checked", "form-2-gender": "1", "form-2-id": str(self.per3.pk), "_save": "Save", } self.client.post(reverse("admin:admin_views_person_changelist"), data) self.assertIs(Person.objects.get(name="John Mauchly").alive, False) self.assertEqual(Person.objects.get(name="Grace Hopper").gender, 2) # test a filtered page data = { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "2", "form-MAX_NUM_FORMS": "0", "form-0-id": str(self.per1.pk), "form-0-gender": "1", "form-0-alive": "checked", "form-1-id": str(self.per3.pk), "form-1-gender": "1", "form-1-alive": "checked", "_save": "Save", } self.client.post( reverse("admin:admin_views_person_changelist") + "?gender__exact=1", data ) self.assertIs(Person.objects.get(name="John Mauchly").alive, True) # test a searched page data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "1", "form-MAX_NUM_FORMS": "0", "form-0-id": str(self.per1.pk), "form-0-gender": "1", "_save": "Save", } self.client.post( reverse("admin:admin_views_person_changelist") + "?q=john", data ) self.assertIs(Person.objects.get(name="John Mauchly").alive, False) def test_non_field_errors(self): """ Non-field errors are displayed for each of the forms in the changelist's formset. """ fd1 = FoodDelivery.objects.create( reference="123", driver="bill", restaurant="thai" ) fd2 = FoodDelivery.objects.create( reference="456", driver="bill", restaurant="india" ) fd3 = FoodDelivery.objects.create( reference="789", driver="bill", restaurant="pizza" ) data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-id": str(fd1.id), "form-0-reference": "123", "form-0-driver": "bill", "form-0-restaurant": "thai", # Same data as above: Forbidden because of unique_together! "form-1-id": str(fd2.id), "form-1-reference": "456", "form-1-driver": "bill", "form-1-restaurant": "thai", "form-2-id": str(fd3.id), "form-2-reference": "789", "form-2-driver": "bill", "form-2-restaurant": "pizza", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_fooddelivery_changelist"), data ) self.assertContains( response, '<tr><td colspan="4"><ul class="errorlist nonfield"><li>Food delivery ' "with this Driver and Restaurant already exists.</li></ul></td></tr>", 1, html=True, ) data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-id": str(fd1.id), "form-0-reference": "123", "form-0-driver": "bill", "form-0-restaurant": "thai", # Same data as above: Forbidden because of unique_together! "form-1-id": str(fd2.id), "form-1-reference": "456", "form-1-driver": "bill", "form-1-restaurant": "thai", # Same data also. "form-2-id": str(fd3.id), "form-2-reference": "789", "form-2-driver": "bill", "form-2-restaurant": "thai", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_fooddelivery_changelist"), data ) self.assertContains( response, '<tr><td colspan="4"><ul class="errorlist nonfield"><li>Food delivery ' "with this Driver and Restaurant already exists.</li></ul></td></tr>", 2, html=True, ) def test_non_form_errors(self): # test if non-form errors are handled; ticket #12716 data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "1", "form-MAX_NUM_FORMS": "0", "form-0-id": str(self.per2.pk), "form-0-alive": "1", "form-0-gender": "2", # The form processing understands this as a list_editable "Save" # and not an action "Go". "_save": "Save", } response = self.client.post( reverse("admin:admin_views_person_changelist"), data ) self.assertContains(response, "Grace is not a Zombie") def test_non_form_errors_is_errorlist(self): # test if non-form errors are correctly handled; ticket #12878 data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "1", "form-MAX_NUM_FORMS": "0", "form-0-id": str(self.per2.pk), "form-0-alive": "1", "form-0-gender": "2", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_person_changelist"), data ) non_form_errors = response.context["cl"].formset.non_form_errors() self.assertIsInstance(non_form_errors, ErrorList) self.assertEqual( str(non_form_errors), str(ErrorList(["Grace is not a Zombie"], error_class="nonform")), ) def test_list_editable_ordering(self): collector = Collector.objects.create(id=1, name="Frederick Clegg") Category.objects.create(id=1, order=1, collector=collector) Category.objects.create(id=2, order=2, collector=collector) Category.objects.create(id=3, order=0, collector=collector) Category.objects.create(id=4, order=0, collector=collector) # NB: The order values must be changed so that the items are reordered. data = { "form-TOTAL_FORMS": "4", "form-INITIAL_FORMS": "4", "form-MAX_NUM_FORMS": "0", "form-0-order": "14", "form-0-id": "1", "form-0-collector": "1", "form-1-order": "13", "form-1-id": "2", "form-1-collector": "1", "form-2-order": "1", "form-2-id": "3", "form-2-collector": "1", "form-3-order": "0", "form-3-id": "4", "form-3-collector": "1", # The form processing understands this as a list_editable "Save" # and not an action "Go". "_save": "Save", } response = self.client.post( reverse("admin:admin_views_category_changelist"), data ) # Successful post will redirect self.assertEqual(response.status_code, 302) # The order values have been applied to the right objects self.assertEqual(Category.objects.get(id=1).order, 14) self.assertEqual(Category.objects.get(id=2).order, 13) self.assertEqual(Category.objects.get(id=3).order, 1) self.assertEqual(Category.objects.get(id=4).order, 0) def test_list_editable_pagination(self): """ Pagination works for list_editable items. """ UnorderedObject.objects.create(id=1, name="Unordered object #1") UnorderedObject.objects.create(id=2, name="Unordered object #2") UnorderedObject.objects.create(id=3, name="Unordered object #3") response = self.client.get( reverse("admin:admin_views_unorderedobject_changelist") ) self.assertContains(response, "Unordered object #3") self.assertContains(response, "Unordered object #2") self.assertNotContains(response, "Unordered object #1") response = self.client.get( reverse("admin:admin_views_unorderedobject_changelist") + "?p=2" ) self.assertNotContains(response, "Unordered object #3") self.assertNotContains(response, "Unordered object #2") self.assertContains(response, "Unordered object #1") def test_list_editable_action_submit(self): # List editable changes should not be executed if the action "Go" button is # used to submit the form. data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-gender": "1", "form-0-id": "1", "form-1-gender": "2", "form-1-id": "2", "form-2-alive": "checked", "form-2-gender": "1", "form-2-id": "3", "index": "0", "_selected_action": ["3"], "action": ["", "delete_selected"], } self.client.post(reverse("admin:admin_views_person_changelist"), data) self.assertIs(Person.objects.get(name="John Mauchly").alive, True) self.assertEqual(Person.objects.get(name="Grace Hopper").gender, 1) def test_list_editable_action_choices(self): # List editable changes should be executed if the "Save" button is # used to submit the form - any action choices should be ignored. data = { "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "3", "form-MAX_NUM_FORMS": "0", "form-0-gender": "1", "form-0-id": str(self.per1.pk), "form-1-gender": "2", "form-1-id": str(self.per2.pk), "form-2-alive": "checked", "form-2-gender": "1", "form-2-id": str(self.per3.pk), "_save": "Save", "_selected_action": ["1"], "action": ["", "delete_selected"], } self.client.post(reverse("admin:admin_views_person_changelist"), data) self.assertIs(Person.objects.get(name="John Mauchly").alive, False) self.assertEqual(Person.objects.get(name="Grace Hopper").gender, 2) def test_list_editable_popup(self): """ Fields should not be list-editable in popups. """ response = self.client.get(reverse("admin:admin_views_person_changelist")) self.assertNotEqual(response.context["cl"].list_editable, ()) response = self.client.get( reverse("admin:admin_views_person_changelist") + "?%s" % IS_POPUP_VAR ) self.assertEqual(response.context["cl"].list_editable, ()) def test_pk_hidden_fields(self): """ hidden pk fields aren't displayed in the table body and their corresponding human-readable value is displayed instead. The hidden pk fields are displayed but separately (not in the table) and only once. """ story1 = Story.objects.create( title="The adventures of Guido", content="Once upon a time in Djangoland..." ) story2 = Story.objects.create( title="Crouching Tiger, Hidden Python", content="The Python was sneaking into...", ) response = self.client.get(reverse("admin:admin_views_story_changelist")) # Only one hidden field, in a separate place than the table. self.assertContains(response, 'id="id_form-0-id"', 1) self.assertContains(response, 'id="id_form-1-id"', 1) self.assertContains( response, '<div class="hiddenfields">\n' '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id">' '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id">\n' "</div>" % (story2.id, story1.id), html=True, ) self.assertContains(response, '<td class="field-id">%d</td>' % story1.id, 1) self.assertContains(response, '<td class="field-id">%d</td>' % story2.id, 1) def test_pk_hidden_fields_with_list_display_links(self): """Similarly as test_pk_hidden_fields, but when the hidden pk fields are referenced in list_display_links. Refs #12475. """ story1 = OtherStory.objects.create( title="The adventures of Guido", content="Once upon a time in Djangoland...", ) story2 = OtherStory.objects.create( title="Crouching Tiger, Hidden Python", content="The Python was sneaking into...", ) link1 = reverse("admin:admin_views_otherstory_change", args=(story1.pk,)) link2 = reverse("admin:admin_views_otherstory_change", args=(story2.pk,)) response = self.client.get(reverse("admin:admin_views_otherstory_changelist")) # Only one hidden field, in a separate place than the table. self.assertContains(response, 'id="id_form-0-id"', 1) self.assertContains(response, 'id="id_form-1-id"', 1) self.assertContains( response, '<div class="hiddenfields">\n' '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id">' '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id">\n' "</div>" % (story2.id, story1.id), html=True, ) self.assertContains( response, '<th class="field-id"><a href="%s">%d</a></th>' % (link1, story1.id), 1, ) self.assertContains( response, '<th class="field-id"><a href="%s">%d</a></th>' % (link2, story2.id), 1, ) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminSearchTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.joepublicuser = User.objects.create_user( username="joepublic", password="secret" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) cls.per2 = Person.objects.create(name="Grace Hopper", gender=1, alive=False) cls.per3 = Person.objects.create(name="Guido van Rossum", gender=1, alive=True) Person.objects.create(name="John Doe", gender=1) Person.objects.create(name='John O"Hara', gender=1) Person.objects.create(name="John O'Hara", gender=1) cls.t1 = Recommender.objects.create() cls.t2 = Recommendation.objects.create(the_recommender=cls.t1) cls.t3 = Recommender.objects.create() cls.t4 = Recommendation.objects.create(the_recommender=cls.t3) cls.tt1 = TitleTranslation.objects.create(title=cls.t1, text="Bar") cls.tt2 = TitleTranslation.objects.create(title=cls.t2, text="Foo") cls.tt3 = TitleTranslation.objects.create(title=cls.t3, text="Few") cls.tt4 = TitleTranslation.objects.create(title=cls.t4, text="Bas") def setUp(self): self.client.force_login(self.superuser) def test_search_on_sibling_models(self): "A search that mentions sibling models" response = self.client.get( reverse("admin:admin_views_recommendation_changelist") + "?q=bar" ) # confirm the search returned 1 object self.assertContains(response, "\n1 recommendation\n") def test_with_fk_to_field(self): """ The to_field GET parameter is preserved when a search is performed. Refs #10918. """ response = self.client.get( reverse("admin:auth_user_changelist") + "?q=joe&%s=id" % TO_FIELD_VAR ) self.assertContains(response, "\n1 user\n") self.assertContains( response, '<input type="hidden" name="%s" value="id">' % TO_FIELD_VAR, html=True, ) def test_exact_matches(self): response = self.client.get( reverse("admin:admin_views_recommendation_changelist") + "?q=bar" ) # confirm the search returned one object self.assertContains(response, "\n1 recommendation\n") response = self.client.get( reverse("admin:admin_views_recommendation_changelist") + "?q=ba" ) # confirm the search returned zero objects self.assertContains(response, "\n0 recommendations\n") def test_beginning_matches(self): response = self.client.get( reverse("admin:admin_views_person_changelist") + "?q=Gui" ) # confirm the search returned one object self.assertContains(response, "\n1 person\n") self.assertContains(response, "Guido") response = self.client.get( reverse("admin:admin_views_person_changelist") + "?q=uido" ) # confirm the search returned zero objects self.assertContains(response, "\n0 persons\n") self.assertNotContains(response, "Guido") def test_pluggable_search(self): PluggableSearchPerson.objects.create(name="Bob", age=10) PluggableSearchPerson.objects.create(name="Amy", age=20) response = self.client.get( reverse("admin:admin_views_pluggablesearchperson_changelist") + "?q=Bob" ) # confirm the search returned one object self.assertContains(response, "\n1 pluggable search person\n") self.assertContains(response, "Bob") response = self.client.get( reverse("admin:admin_views_pluggablesearchperson_changelist") + "?q=20" ) # confirm the search returned one object self.assertContains(response, "\n1 pluggable search person\n") self.assertContains(response, "Amy") def test_reset_link(self): """ Test presence of reset link in search bar ("1 result (_x total_)"). """ # 1 query for session + 1 for fetching user # + 1 for filtered result + 1 for filtered count # + 1 for total count with self.assertNumQueries(5): response = self.client.get( reverse("admin:admin_views_person_changelist") + "?q=Gui" ) self.assertContains( response, """<span class="small quiet">1 result (<a href="?">6 total</a>)</span>""", html=True, ) def test_no_total_count(self): """ #8408 -- "Show all" should be displayed instead of the total count if ModelAdmin.show_full_result_count is False. """ # 1 query for session + 1 for fetching user # + 1 for filtered result + 1 for filtered count with self.assertNumQueries(4): response = self.client.get( reverse("admin:admin_views_recommendation_changelist") + "?q=bar" ) self.assertContains( response, """<span class="small quiet">1 result (<a href="?">Show all</a>)</span>""", html=True, ) self.assertTrue(response.context["cl"].show_admin_actions) def test_search_with_spaces(self): url = reverse("admin:admin_views_person_changelist") + "?q=%s" tests = [ ('"John Doe"', 1), ("'John Doe'", 1), ("John Doe", 0), ('"John Doe" John', 1), ("'John Doe' John", 1), ("John Doe John", 0), ('"John Do"', 1), ("'John Do'", 1), ("'John O'Hara'", 0), ("'John O\\'Hara'", 1), ('"John O"Hara"', 0), ('"John O\\"Hara"', 1), ] for search, hits in tests: with self.subTest(search=search): response = self.client.get(url % search) self.assertContains(response, "\n%s person" % hits) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminInheritedInlinesTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_inline(self): """ Inline models which inherit from a common parent are correctly handled. """ foo_user = "foo username" bar_user = "bar username" name_re = re.compile(b'name="(.*?)"') # test the add case response = self.client.get(reverse("admin:admin_views_persona_add")) names = name_re.findall(response.content) names.remove(b"csrfmiddlewaretoken") # make sure we have no duplicate HTML names self.assertEqual(len(names), len(set(names))) # test the add case post_data = { "name": "Test Name", # inline data "accounts-TOTAL_FORMS": "1", "accounts-INITIAL_FORMS": "0", "accounts-MAX_NUM_FORMS": "0", "accounts-0-username": foo_user, "accounts-2-TOTAL_FORMS": "1", "accounts-2-INITIAL_FORMS": "0", "accounts-2-MAX_NUM_FORMS": "0", "accounts-2-0-username": bar_user, } response = self.client.post(reverse("admin:admin_views_persona_add"), post_data) self.assertEqual(response.status_code, 302) # redirect somewhere self.assertEqual(Persona.objects.count(), 1) self.assertEqual(FooAccount.objects.count(), 1) self.assertEqual(BarAccount.objects.count(), 1) self.assertEqual(FooAccount.objects.all()[0].username, foo_user) self.assertEqual(BarAccount.objects.all()[0].username, bar_user) self.assertEqual(Persona.objects.all()[0].accounts.count(), 2) persona_id = Persona.objects.all()[0].id foo_id = FooAccount.objects.all()[0].id bar_id = BarAccount.objects.all()[0].id # test the edit case response = self.client.get( reverse("admin:admin_views_persona_change", args=(persona_id,)) ) names = name_re.findall(response.content) names.remove(b"csrfmiddlewaretoken") # make sure we have no duplicate HTML names self.assertEqual(len(names), len(set(names))) post_data = { "name": "Test Name", "accounts-TOTAL_FORMS": "2", "accounts-INITIAL_FORMS": "1", "accounts-MAX_NUM_FORMS": "0", "accounts-0-username": "%s-1" % foo_user, "accounts-0-account_ptr": str(foo_id), "accounts-0-persona": str(persona_id), "accounts-2-TOTAL_FORMS": "2", "accounts-2-INITIAL_FORMS": "1", "accounts-2-MAX_NUM_FORMS": "0", "accounts-2-0-username": "%s-1" % bar_user, "accounts-2-0-account_ptr": str(bar_id), "accounts-2-0-persona": str(persona_id), } response = self.client.post( reverse("admin:admin_views_persona_change", args=(persona_id,)), post_data ) self.assertEqual(response.status_code, 302) self.assertEqual(Persona.objects.count(), 1) self.assertEqual(FooAccount.objects.count(), 1) self.assertEqual(BarAccount.objects.count(), 1) self.assertEqual(FooAccount.objects.all()[0].username, "%s-1" % foo_user) self.assertEqual(BarAccount.objects.all()[0].username, "%s-1" % bar_user) self.assertEqual(Persona.objects.all()[0].accounts.count(), 2) @override_settings(ROOT_URLCONF="admin_views.urls") class TestCustomChangeList(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_custom_changelist(self): """ Validate that a custom ChangeList class can be used (#9749) """ # Insert some data post_data = {"name": "First Gadget"} response = self.client.post(reverse("admin:admin_views_gadget_add"), post_data) self.assertEqual(response.status_code, 302) # redirect somewhere # Hit the page once to get messages out of the queue message list response = self.client.get(reverse("admin:admin_views_gadget_changelist")) # Data is still not visible on the page response = self.client.get(reverse("admin:admin_views_gadget_changelist")) self.assertNotContains(response, "First Gadget") @override_settings(ROOT_URLCONF="admin_views.urls") class TestInlineNotEditable(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_GET_parent_add(self): """ InlineModelAdmin broken? """ response = self.client.get(reverse("admin:admin_views_parent_add")) self.assertEqual(response.status_code, 200) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminCustomQuerysetTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.pks = [EmptyModel.objects.create().id for i in range(3)] def setUp(self): self.client.force_login(self.superuser) self.super_login = { REDIRECT_FIELD_NAME: reverse("admin:index"), "username": "super", "password": "secret", } def test_changelist_view(self): response = self.client.get(reverse("admin:admin_views_emptymodel_changelist")) for i in self.pks: if i > 1: self.assertContains(response, "Primary key = %s" % i) else: self.assertNotContains(response, "Primary key = %s" % i) def test_changelist_view_count_queries(self): # create 2 Person objects Person.objects.create(name="person1", gender=1) Person.objects.create(name="person2", gender=2) changelist_url = reverse("admin:admin_views_person_changelist") # 5 queries are expected: 1 for the session, 1 for the user, # 2 for the counts and 1 for the objects on the page with self.assertNumQueries(5): resp = self.client.get(changelist_url) self.assertEqual(resp.context["selection_note"], "0 of 2 selected") self.assertEqual(resp.context["selection_note_all"], "All 2 selected") with self.assertNumQueries(5): extra = {"q": "not_in_name"} resp = self.client.get(changelist_url, extra) self.assertEqual(resp.context["selection_note"], "0 of 0 selected") self.assertEqual(resp.context["selection_note_all"], "All 0 selected") with self.assertNumQueries(5): extra = {"q": "person"} resp = self.client.get(changelist_url, extra) self.assertEqual(resp.context["selection_note"], "0 of 2 selected") self.assertEqual(resp.context["selection_note_all"], "All 2 selected") with self.assertNumQueries(5): extra = {"gender__exact": "1"} resp = self.client.get(changelist_url, extra) self.assertEqual(resp.context["selection_note"], "0 of 1 selected") self.assertEqual(resp.context["selection_note_all"], "1 selected") def test_change_view(self): for i in self.pks: url = reverse("admin:admin_views_emptymodel_change", args=(i,)) response = self.client.get(url, follow=True) if i > 1: self.assertEqual(response.status_code, 200) else: self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["empty model with ID “1” doesn’t exist. Perhaps it was deleted?"], ) def test_add_model_modeladmin_defer_qs(self): # Test for #14529. defer() is used in ModelAdmin.get_queryset() # model has __str__ method self.assertEqual(CoverLetter.objects.count(), 0) # Emulate model instance creation via the admin post_data = { "author": "Candidate, Best", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_coverletter_add"), post_data, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(CoverLetter.objects.count(), 1) # Message should contain non-ugly model verbose name pk = CoverLetter.objects.all()[0].pk self.assertContains( response, '<li class="success">The cover letter “<a href="%s">' "Candidate, Best</a>” was added successfully.</li>" % reverse("admin:admin_views_coverletter_change", args=(pk,)), html=True, ) # model has no __str__ method self.assertEqual(ShortMessage.objects.count(), 0) # Emulate model instance creation via the admin post_data = { "content": "What's this SMS thing?", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_shortmessage_add"), post_data, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(ShortMessage.objects.count(), 1) # Message should contain non-ugly model verbose name sm = ShortMessage.objects.all()[0] self.assertContains( response, '<li class="success">The short message “<a href="%s">' "%s</a>” was added successfully.</li>" % (reverse("admin:admin_views_shortmessage_change", args=(sm.pk,)), sm), html=True, ) def test_add_model_modeladmin_only_qs(self): # Test for #14529. only() is used in ModelAdmin.get_queryset() # model has __str__ method self.assertEqual(Telegram.objects.count(), 0) # Emulate model instance creation via the admin post_data = { "title": "Urgent telegram", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_telegram_add"), post_data, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(Telegram.objects.count(), 1) # Message should contain non-ugly model verbose name pk = Telegram.objects.all()[0].pk self.assertContains( response, '<li class="success">The telegram “<a href="%s">' "Urgent telegram</a>” was added successfully.</li>" % reverse("admin:admin_views_telegram_change", args=(pk,)), html=True, ) # model has no __str__ method self.assertEqual(Paper.objects.count(), 0) # Emulate model instance creation via the admin post_data = { "title": "My Modified Paper Title", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_paper_add"), post_data, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(Paper.objects.count(), 1) # Message should contain non-ugly model verbose name p = Paper.objects.all()[0] self.assertContains( response, '<li class="success">The paper “<a href="%s">' "%s</a>” was added successfully.</li>" % (reverse("admin:admin_views_paper_change", args=(p.pk,)), p), html=True, ) def test_edit_model_modeladmin_defer_qs(self): # Test for #14529. defer() is used in ModelAdmin.get_queryset() # model has __str__ method cl = CoverLetter.objects.create(author="John Doe") self.assertEqual(CoverLetter.objects.count(), 1) response = self.client.get( reverse("admin:admin_views_coverletter_change", args=(cl.pk,)) ) self.assertEqual(response.status_code, 200) # Emulate model instance edit via the admin post_data = { "author": "John Doe II", "_save": "Save", } url = reverse("admin:admin_views_coverletter_change", args=(cl.pk,)) response = self.client.post(url, post_data, follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(CoverLetter.objects.count(), 1) # Message should contain non-ugly model verbose name. Instance # representation is set by model's __str__() self.assertContains( response, '<li class="success">The cover letter “<a href="%s">' "John Doe II</a>” was changed successfully.</li>" % reverse("admin:admin_views_coverletter_change", args=(cl.pk,)), html=True, ) # model has no __str__ method sm = ShortMessage.objects.create(content="This is expensive") self.assertEqual(ShortMessage.objects.count(), 1) response = self.client.get( reverse("admin:admin_views_shortmessage_change", args=(sm.pk,)) ) self.assertEqual(response.status_code, 200) # Emulate model instance edit via the admin post_data = { "content": "Too expensive", "_save": "Save", } url = reverse("admin:admin_views_shortmessage_change", args=(sm.pk,)) response = self.client.post(url, post_data, follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(ShortMessage.objects.count(), 1) # Message should contain non-ugly model verbose name. The ugly(!) # instance representation is set by __str__(). self.assertContains( response, '<li class="success">The short message “<a href="%s">' "%s</a>” was changed successfully.</li>" % (reverse("admin:admin_views_shortmessage_change", args=(sm.pk,)), sm), html=True, ) def test_edit_model_modeladmin_only_qs(self): # Test for #14529. only() is used in ModelAdmin.get_queryset() # model has __str__ method t = Telegram.objects.create(title="First Telegram") self.assertEqual(Telegram.objects.count(), 1) response = self.client.get( reverse("admin:admin_views_telegram_change", args=(t.pk,)) ) self.assertEqual(response.status_code, 200) # Emulate model instance edit via the admin post_data = { "title": "Telegram without typo", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_telegram_change", args=(t.pk,)), post_data, follow=True, ) self.assertEqual(response.status_code, 200) self.assertEqual(Telegram.objects.count(), 1) # Message should contain non-ugly model verbose name. The instance # representation is set by model's __str__() self.assertContains( response, '<li class="success">The telegram “<a href="%s">' "Telegram without typo</a>” was changed successfully.</li>" % reverse("admin:admin_views_telegram_change", args=(t.pk,)), html=True, ) # model has no __str__ method p = Paper.objects.create(title="My Paper Title") self.assertEqual(Paper.objects.count(), 1) response = self.client.get( reverse("admin:admin_views_paper_change", args=(p.pk,)) ) self.assertEqual(response.status_code, 200) # Emulate model instance edit via the admin post_data = { "title": "My Modified Paper Title", "_save": "Save", } response = self.client.post( reverse("admin:admin_views_paper_change", args=(p.pk,)), post_data, follow=True, ) self.assertEqual(response.status_code, 200) self.assertEqual(Paper.objects.count(), 1) # Message should contain non-ugly model verbose name. The ugly(!) # instance representation is set by __str__(). self.assertContains( response, '<li class="success">The paper “<a href="%s">' "%s</a>” was changed successfully.</li>" % (reverse("admin:admin_views_paper_change", args=(p.pk,)), p), html=True, ) def test_history_view_custom_qs(self): """ Custom querysets are considered for the admin history view. """ self.client.post(reverse("admin:login"), self.super_login) FilteredManager.objects.create(pk=1) FilteredManager.objects.create(pk=2) response = self.client.get( reverse("admin:admin_views_filteredmanager_changelist") ) self.assertContains(response, "PK=1") self.assertContains(response, "PK=2") self.assertEqual( self.client.get( reverse("admin:admin_views_filteredmanager_history", args=(1,)) ).status_code, 200, ) self.assertEqual( self.client.get( reverse("admin:admin_views_filteredmanager_history", args=(2,)) ).status_code, 200, ) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminInlineFileUploadTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) file1 = tempfile.NamedTemporaryFile(suffix=".file1") file1.write(b"a" * (2**21)) filename = file1.name file1.close() cls.gallery = Gallery.objects.create(name="Test Gallery") cls.picture = Picture.objects.create( name="Test Picture", image=filename, gallery=cls.gallery, ) def setUp(self): self.client.force_login(self.superuser) def test_form_has_multipart_enctype(self): response = self.client.get( reverse("admin:admin_views_gallery_change", args=(self.gallery.id,)) ) self.assertIs(response.context["has_file_field"], True) self.assertContains(response, MULTIPART_ENCTYPE) def test_inline_file_upload_edit_validation_error_post(self): """ Inline file uploads correctly display prior data (#10002). """ post_data = { "name": "Test Gallery", "pictures-TOTAL_FORMS": "2", "pictures-INITIAL_FORMS": "1", "pictures-MAX_NUM_FORMS": "0", "pictures-0-id": str(self.picture.id), "pictures-0-gallery": str(self.gallery.id), "pictures-0-name": "Test Picture", "pictures-0-image": "", "pictures-1-id": "", "pictures-1-gallery": str(self.gallery.id), "pictures-1-name": "Test Picture 2", "pictures-1-image": "", } response = self.client.post( reverse("admin:admin_views_gallery_change", args=(self.gallery.id,)), post_data, ) self.assertContains(response, b"Currently") @override_settings(ROOT_URLCONF="admin_views.urls") class AdminInlineTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.collector = Collector.objects.create(pk=1, name="John Fowles") def setUp(self): self.post_data = { "name": "Test Name", "widget_set-TOTAL_FORMS": "3", "widget_set-INITIAL_FORMS": "0", "widget_set-MAX_NUM_FORMS": "0", "widget_set-0-id": "", "widget_set-0-owner": "1", "widget_set-0-name": "", "widget_set-1-id": "", "widget_set-1-owner": "1", "widget_set-1-name": "", "widget_set-2-id": "", "widget_set-2-owner": "1", "widget_set-2-name": "", "doohickey_set-TOTAL_FORMS": "3", "doohickey_set-INITIAL_FORMS": "0", "doohickey_set-MAX_NUM_FORMS": "0", "doohickey_set-0-owner": "1", "doohickey_set-0-code": "", "doohickey_set-0-name": "", "doohickey_set-1-owner": "1", "doohickey_set-1-code": "", "doohickey_set-1-name": "", "doohickey_set-2-owner": "1", "doohickey_set-2-code": "", "doohickey_set-2-name": "", "grommet_set-TOTAL_FORMS": "3", "grommet_set-INITIAL_FORMS": "0", "grommet_set-MAX_NUM_FORMS": "0", "grommet_set-0-code": "", "grommet_set-0-owner": "1", "grommet_set-0-name": "", "grommet_set-1-code": "", "grommet_set-1-owner": "1", "grommet_set-1-name": "", "grommet_set-2-code": "", "grommet_set-2-owner": "1", "grommet_set-2-name": "", "whatsit_set-TOTAL_FORMS": "3", "whatsit_set-INITIAL_FORMS": "0", "whatsit_set-MAX_NUM_FORMS": "0", "whatsit_set-0-owner": "1", "whatsit_set-0-index": "", "whatsit_set-0-name": "", "whatsit_set-1-owner": "1", "whatsit_set-1-index": "", "whatsit_set-1-name": "", "whatsit_set-2-owner": "1", "whatsit_set-2-index": "", "whatsit_set-2-name": "", "fancydoodad_set-TOTAL_FORMS": "3", "fancydoodad_set-INITIAL_FORMS": "0", "fancydoodad_set-MAX_NUM_FORMS": "0", "fancydoodad_set-0-doodad_ptr": "", "fancydoodad_set-0-owner": "1", "fancydoodad_set-0-name": "", "fancydoodad_set-0-expensive": "on", "fancydoodad_set-1-doodad_ptr": "", "fancydoodad_set-1-owner": "1", "fancydoodad_set-1-name": "", "fancydoodad_set-1-expensive": "on", "fancydoodad_set-2-doodad_ptr": "", "fancydoodad_set-2-owner": "1", "fancydoodad_set-2-name": "", "fancydoodad_set-2-expensive": "on", "category_set-TOTAL_FORMS": "3", "category_set-INITIAL_FORMS": "0", "category_set-MAX_NUM_FORMS": "0", "category_set-0-order": "", "category_set-0-id": "", "category_set-0-collector": "1", "category_set-1-order": "", "category_set-1-id": "", "category_set-1-collector": "1", "category_set-2-order": "", "category_set-2-id": "", "category_set-2-collector": "1", } self.client.force_login(self.superuser) def test_simple_inline(self): "A simple model can be saved as inlines" # First add a new inline self.post_data["widget_set-0-name"] = "Widget 1" collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Widget.objects.count(), 1) self.assertEqual(Widget.objects.all()[0].name, "Widget 1") widget_id = Widget.objects.all()[0].id # The PK link exists on the rendered form response = self.client.get(collector_url) self.assertContains(response, 'name="widget_set-0-id"') # No file or image fields, no enctype on the forms self.assertIs(response.context["has_file_field"], False) self.assertNotContains(response, MULTIPART_ENCTYPE) # Now resave that inline self.post_data["widget_set-INITIAL_FORMS"] = "1" self.post_data["widget_set-0-id"] = str(widget_id) self.post_data["widget_set-0-name"] = "Widget 1" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Widget.objects.count(), 1) self.assertEqual(Widget.objects.all()[0].name, "Widget 1") # Now modify that inline self.post_data["widget_set-INITIAL_FORMS"] = "1" self.post_data["widget_set-0-id"] = str(widget_id) self.post_data["widget_set-0-name"] = "Widget 1 Updated" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Widget.objects.count(), 1) self.assertEqual(Widget.objects.all()[0].name, "Widget 1 Updated") def test_explicit_autofield_inline(self): """ A model with an explicit autofield primary key can be saved as inlines. """ # First add a new inline self.post_data["grommet_set-0-name"] = "Grommet 1" collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Grommet.objects.count(), 1) self.assertEqual(Grommet.objects.all()[0].name, "Grommet 1") # The PK link exists on the rendered form response = self.client.get(collector_url) self.assertContains(response, 'name="grommet_set-0-code"') # Now resave that inline self.post_data["grommet_set-INITIAL_FORMS"] = "1" self.post_data["grommet_set-0-code"] = str(Grommet.objects.all()[0].code) self.post_data["grommet_set-0-name"] = "Grommet 1" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Grommet.objects.count(), 1) self.assertEqual(Grommet.objects.all()[0].name, "Grommet 1") # Now modify that inline self.post_data["grommet_set-INITIAL_FORMS"] = "1" self.post_data["grommet_set-0-code"] = str(Grommet.objects.all()[0].code) self.post_data["grommet_set-0-name"] = "Grommet 1 Updated" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Grommet.objects.count(), 1) self.assertEqual(Grommet.objects.all()[0].name, "Grommet 1 Updated") def test_char_pk_inline(self): "A model with a character PK can be saved as inlines. Regression for #10992" # First add a new inline self.post_data["doohickey_set-0-code"] = "DH1" self.post_data["doohickey_set-0-name"] = "Doohickey 1" collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(DooHickey.objects.count(), 1) self.assertEqual(DooHickey.objects.all()[0].name, "Doohickey 1") # The PK link exists on the rendered form response = self.client.get(collector_url) self.assertContains(response, 'name="doohickey_set-0-code"') # Now resave that inline self.post_data["doohickey_set-INITIAL_FORMS"] = "1" self.post_data["doohickey_set-0-code"] = "DH1" self.post_data["doohickey_set-0-name"] = "Doohickey 1" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(DooHickey.objects.count(), 1) self.assertEqual(DooHickey.objects.all()[0].name, "Doohickey 1") # Now modify that inline self.post_data["doohickey_set-INITIAL_FORMS"] = "1" self.post_data["doohickey_set-0-code"] = "DH1" self.post_data["doohickey_set-0-name"] = "Doohickey 1 Updated" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(DooHickey.objects.count(), 1) self.assertEqual(DooHickey.objects.all()[0].name, "Doohickey 1 Updated") def test_integer_pk_inline(self): "A model with an integer PK can be saved as inlines. Regression for #10992" # First add a new inline self.post_data["whatsit_set-0-index"] = "42" self.post_data["whatsit_set-0-name"] = "Whatsit 1" collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Whatsit.objects.count(), 1) self.assertEqual(Whatsit.objects.all()[0].name, "Whatsit 1") # The PK link exists on the rendered form response = self.client.get(collector_url) self.assertContains(response, 'name="whatsit_set-0-index"') # Now resave that inline self.post_data["whatsit_set-INITIAL_FORMS"] = "1" self.post_data["whatsit_set-0-index"] = "42" self.post_data["whatsit_set-0-name"] = "Whatsit 1" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Whatsit.objects.count(), 1) self.assertEqual(Whatsit.objects.all()[0].name, "Whatsit 1") # Now modify that inline self.post_data["whatsit_set-INITIAL_FORMS"] = "1" self.post_data["whatsit_set-0-index"] = "42" self.post_data["whatsit_set-0-name"] = "Whatsit 1 Updated" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(Whatsit.objects.count(), 1) self.assertEqual(Whatsit.objects.all()[0].name, "Whatsit 1 Updated") def test_inherited_inline(self): "An inherited model can be saved as inlines. Regression for #11042" # First add a new inline self.post_data["fancydoodad_set-0-name"] = "Fancy Doodad 1" collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(FancyDoodad.objects.count(), 1) self.assertEqual(FancyDoodad.objects.all()[0].name, "Fancy Doodad 1") doodad_pk = FancyDoodad.objects.all()[0].pk # The PK link exists on the rendered form response = self.client.get(collector_url) self.assertContains(response, 'name="fancydoodad_set-0-doodad_ptr"') # Now resave that inline self.post_data["fancydoodad_set-INITIAL_FORMS"] = "1" self.post_data["fancydoodad_set-0-doodad_ptr"] = str(doodad_pk) self.post_data["fancydoodad_set-0-name"] = "Fancy Doodad 1" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(FancyDoodad.objects.count(), 1) self.assertEqual(FancyDoodad.objects.all()[0].name, "Fancy Doodad 1") # Now modify that inline self.post_data["fancydoodad_set-INITIAL_FORMS"] = "1" self.post_data["fancydoodad_set-0-doodad_ptr"] = str(doodad_pk) self.post_data["fancydoodad_set-0-name"] = "Fancy Doodad 1 Updated" response = self.client.post(collector_url, self.post_data) self.assertEqual(response.status_code, 302) self.assertEqual(FancyDoodad.objects.count(), 1) self.assertEqual(FancyDoodad.objects.all()[0].name, "Fancy Doodad 1 Updated") def test_ordered_inline(self): """ An inline with an editable ordering fields is updated correctly. """ # Create some objects with an initial ordering Category.objects.create(id=1, order=1, collector=self.collector) Category.objects.create(id=2, order=2, collector=self.collector) Category.objects.create(id=3, order=0, collector=self.collector) Category.objects.create(id=4, order=0, collector=self.collector) # NB: The order values must be changed so that the items are reordered. self.post_data.update( { "name": "Frederick Clegg", "category_set-TOTAL_FORMS": "7", "category_set-INITIAL_FORMS": "4", "category_set-MAX_NUM_FORMS": "0", "category_set-0-order": "14", "category_set-0-id": "1", "category_set-0-collector": "1", "category_set-1-order": "13", "category_set-1-id": "2", "category_set-1-collector": "1", "category_set-2-order": "1", "category_set-2-id": "3", "category_set-2-collector": "1", "category_set-3-order": "0", "category_set-3-id": "4", "category_set-3-collector": "1", "category_set-4-order": "", "category_set-4-id": "", "category_set-4-collector": "1", "category_set-5-order": "", "category_set-5-id": "", "category_set-5-collector": "1", "category_set-6-order": "", "category_set-6-id": "", "category_set-6-collector": "1", } ) collector_url = reverse( "admin:admin_views_collector_change", args=(self.collector.pk,) ) response = self.client.post(collector_url, self.post_data) # Successful post will redirect self.assertEqual(response.status_code, 302) # The order values have been applied to the right objects self.assertEqual(self.collector.category_set.count(), 4) self.assertEqual(Category.objects.get(id=1).order, 14) self.assertEqual(Category.objects.get(id=2).order, 13) self.assertEqual(Category.objects.get(id=3).order, 1) self.assertEqual(Category.objects.get(id=4).order, 0) @override_settings(ROOT_URLCONF="admin_views.urls") class NeverCacheTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") def setUp(self): self.client.force_login(self.superuser) def test_admin_index(self): "Check the never-cache status of the main index" response = self.client.get(reverse("admin:index")) self.assertEqual(get_max_age(response), 0) def test_app_index(self): "Check the never-cache status of an application index" response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertEqual(get_max_age(response), 0) def test_model_index(self): "Check the never-cache status of a model index" response = self.client.get(reverse("admin:admin_views_fabric_changelist")) self.assertEqual(get_max_age(response), 0) def test_model_add(self): "Check the never-cache status of a model add page" response = self.client.get(reverse("admin:admin_views_fabric_add")) self.assertEqual(get_max_age(response), 0) def test_model_view(self): "Check the never-cache status of a model edit page" response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertEqual(get_max_age(response), 0) def test_model_history(self): "Check the never-cache status of a model history page" response = self.client.get( reverse("admin:admin_views_section_history", args=(self.s1.pk,)) ) self.assertEqual(get_max_age(response), 0) def test_model_delete(self): "Check the never-cache status of a model delete page" response = self.client.get( reverse("admin:admin_views_section_delete", args=(self.s1.pk,)) ) self.assertEqual(get_max_age(response), 0) def test_login(self): "Check the never-cache status of login views" self.client.logout() response = self.client.get(reverse("admin:index")) self.assertEqual(get_max_age(response), 0) def test_logout(self): "Check the never-cache status of logout view" response = self.client.post(reverse("admin:logout")) self.assertEqual(get_max_age(response), 0) def test_password_change(self): "Check the never-cache status of the password change view" self.client.logout() response = self.client.get(reverse("admin:password_change")) self.assertIsNone(get_max_age(response)) def test_password_change_done(self): "Check the never-cache status of the password change done view" response = self.client.get(reverse("admin:password_change_done")) self.assertIsNone(get_max_age(response)) def test_JS_i18n(self): "Check the never-cache status of the JavaScript i18n view" response = self.client.get(reverse("admin:jsi18n")) self.assertIsNone(get_max_age(response)) @override_settings(ROOT_URLCONF="admin_views.urls") class PrePopulatedTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) def setUp(self): self.client.force_login(self.superuser) def test_prepopulated_on(self): response = self.client.get(reverse("admin:admin_views_prepopulatedpost_add")) self.assertContains(response, "&quot;id&quot;: &quot;#id_slug&quot;") self.assertContains( response, "&quot;dependency_ids&quot;: [&quot;#id_title&quot;]" ) self.assertContains( response, "&quot;id&quot;: &quot;#id_prepopulatedsubpost_set-0-subslug&quot;", ) def test_prepopulated_off(self): response = self.client.get( reverse("admin:admin_views_prepopulatedpost_change", args=(self.p1.pk,)) ) self.assertContains(response, "A Long Title") self.assertNotContains(response, "&quot;id&quot;: &quot;#id_slug&quot;") self.assertNotContains( response, "&quot;dependency_ids&quot;: [&quot;#id_title&quot;]" ) self.assertNotContains( response, "&quot;id&quot;: &quot;#id_prepopulatedsubpost_set-0-subslug&quot;", ) @override_settings(USE_THOUSAND_SEPARATOR=True) def test_prepopulated_maxlength_localized(self): """ Regression test for #15938: if USE_THOUSAND_SEPARATOR is set, make sure that maxLength (in the JavaScript) is rendered without separators. """ response = self.client.get( reverse("admin:admin_views_prepopulatedpostlargeslug_add") ) self.assertContains(response, "&quot;maxLength&quot;: 1000") # instead of 1,000 def test_view_only_add_form(self): """ PrePopulatedPostReadOnlyAdmin.prepopulated_fields includes 'slug' which is present in the add view, even if the ModelAdmin.has_change_permission() returns False. """ response = self.client.get(reverse("admin7:admin_views_prepopulatedpost_add")) self.assertContains(response, "data-prepopulated-fields=") self.assertContains(response, "&quot;id&quot;: &quot;#id_slug&quot;") def test_view_only_change_form(self): """ PrePopulatedPostReadOnlyAdmin.prepopulated_fields includes 'slug'. That doesn't break a view-only change view. """ response = self.client.get( reverse("admin7:admin_views_prepopulatedpost_change", args=(self.p1.pk,)) ) self.assertContains(response, 'data-prepopulated-fields="[]"') self.assertContains(response, '<div class="readonly">%s</div>' % self.p1.slug) @override_settings(ROOT_URLCONF="admin_views.urls") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) self.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) def test_login_button_centered(self): from selenium.webdriver.common.by import By self.selenium.get(self.live_server_url + reverse("admin:login")) button = self.selenium.find_element(By.CSS_SELECTOR, ".submit-row input") offset_left = button.get_property("offsetLeft") offset_right = button.get_property("offsetParent").get_property( "offsetWidth" ) - (offset_left + button.get_property("offsetWidth")) # Use assertAlmostEqual to avoid pixel rounding errors. self.assertAlmostEqual(offset_left, offset_right, delta=3) def test_prepopulated_fields(self): """ The JavaScript-automated prepopulated fields work with the main form and with stacked and tabular inlines. Refs #13068, #9264, #9983, #9784. """ from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_mainprepopulated_add") ) self.wait_for(".select2") # Main form ---------------------------------------------------------- self.selenium.find_element(By.ID, "id_pubdate").send_keys("2012-02-18") self.select_option("#id_status", "option two") self.selenium.find_element(By.ID, "id_name").send_keys( " the mAin nÀMë and it's awεšomeıııİ" ) slug1 = self.selenium.find_element(By.ID, "id_slug1").get_attribute("value") slug2 = self.selenium.find_element(By.ID, "id_slug2").get_attribute("value") slug3 = self.selenium.find_element(By.ID, "id_slug3").get_attribute("value") self.assertEqual(slug1, "the-main-name-and-its-awesomeiiii-2012-02-18") self.assertEqual(slug2, "option-two-the-main-name-and-its-awesomeiiii") self.assertEqual( slug3, "the-main-n\xe0m\xeb-and-its-aw\u03b5\u0161ome\u0131\u0131\u0131i" ) # Stacked inlines with fieldsets ------------------------------------- # Initial inline self.selenium.find_element( By.ID, "id_relatedprepopulated_set-0-pubdate" ).send_keys("2011-12-17") self.select_option("#id_relatedprepopulated_set-0-status", "option one") self.selenium.find_element( By.ID, "id_relatedprepopulated_set-0-name" ).send_keys(" here is a sŤāÇkeð inline ! ") slug1 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-0-slug1" ).get_attribute("value") slug2 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-0-slug2" ).get_attribute("value") self.assertEqual(slug1, "here-is-a-stacked-inline-2011-12-17") self.assertEqual(slug2, "option-one-here-is-a-stacked-inline") initial_select2_inputs = self.selenium.find_elements( By.CLASS_NAME, "select2-selection" ) # Inline formsets have empty/invisible forms. # Only the 4 visible select2 inputs are initialized. num_initial_select2_inputs = len(initial_select2_inputs) self.assertEqual(num_initial_select2_inputs, 4) # Add an inline self.selenium.find_elements(By.LINK_TEXT, "Add another Related prepopulated")[ 0 ].click() self.assertEqual( len(self.selenium.find_elements(By.CLASS_NAME, "select2-selection")), num_initial_select2_inputs + 2, ) self.selenium.find_element( By.ID, "id_relatedprepopulated_set-1-pubdate" ).send_keys("1999-01-25") self.select_option("#id_relatedprepopulated_set-1-status", "option two") self.selenium.find_element( By.ID, "id_relatedprepopulated_set-1-name" ).send_keys( " now you haVe anöther sŤāÇkeð inline with a very ... " "loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooog " "text... " ) slug1 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-1-slug1" ).get_attribute("value") slug2 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-1-slug2" ).get_attribute("value") # 50 characters maximum for slug1 field self.assertEqual(slug1, "now-you-have-another-stacked-inline-with-a-very-lo") # 60 characters maximum for slug2 field self.assertEqual( slug2, "option-two-now-you-have-another-stacked-inline-with-a-very-l" ) # Tabular inlines ---------------------------------------------------- # Initial inline element = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-0-status" ) self.selenium.execute_script("window.scrollTo(0, %s);" % element.location["y"]) self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-0-pubdate" ).send_keys("1234-12-07") self.select_option("#id_relatedprepopulated_set-2-0-status", "option two") self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-0-name" ).send_keys("And now, with a tÃbűlaŘ inline !!!") slug1 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-0-slug1" ).get_attribute("value") slug2 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-0-slug2" ).get_attribute("value") self.assertEqual(slug1, "and-now-with-a-tabular-inline-1234-12-07") self.assertEqual(slug2, "option-two-and-now-with-a-tabular-inline") # Add an inline # Button may be outside the browser frame. element = self.selenium.find_elements( By.LINK_TEXT, "Add another Related prepopulated" )[1] self.selenium.execute_script("window.scrollTo(0, %s);" % element.location["y"]) element.click() self.assertEqual( len(self.selenium.find_elements(By.CLASS_NAME, "select2-selection")), num_initial_select2_inputs + 4, ) self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-1-pubdate" ).send_keys("1981-08-22") self.select_option("#id_relatedprepopulated_set-2-1-status", "option one") self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-1-name" ).send_keys(r'tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters') slug1 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-1-slug1" ).get_attribute("value") slug2 = self.selenium.find_element( By.ID, "id_relatedprepopulated_set-2-1-slug2" ).get_attribute("value") self.assertEqual(slug1, "tabular-inline-with-ignored-characters-1981-08-22") self.assertEqual(slug2, "option-one-tabular-inline-with-ignored-characters") # Add an inline without an initial inline. # The button is outside of the browser frame. self.selenium.execute_script("window.scrollTo(0, document.body.scrollHeight);") self.selenium.find_elements(By.LINK_TEXT, "Add another Related prepopulated")[ 2 ].click() self.assertEqual( len(self.selenium.find_elements(By.CLASS_NAME, "select2-selection")), num_initial_select2_inputs + 6, ) # Stacked Inlines without fieldsets ---------------------------------- # Initial inline. row_id = "id_relatedprepopulated_set-4-0-" self.selenium.find_element(By.ID, f"{row_id}pubdate").send_keys("2011-12-12") self.select_option(f"#{row_id}status", "option one") self.selenium.find_element(By.ID, f"{row_id}name").send_keys( " sŤāÇkeð inline ! " ) slug1 = self.selenium.find_element(By.ID, f"{row_id}slug1").get_attribute( "value" ) slug2 = self.selenium.find_element(By.ID, f"{row_id}slug2").get_attribute( "value" ) self.assertEqual(slug1, "stacked-inline-2011-12-12") self.assertEqual(slug2, "option-one") # Add inline. self.selenium.find_elements( By.LINK_TEXT, "Add another Related prepopulated", )[3].click() row_id = "id_relatedprepopulated_set-4-1-" self.selenium.find_element(By.ID, f"{row_id}pubdate").send_keys("1999-01-20") self.select_option(f"#{row_id}status", "option two") self.selenium.find_element(By.ID, f"{row_id}name").send_keys( " now you haVe anöther sŤāÇkeð inline with a very loooong " ) slug1 = self.selenium.find_element(By.ID, f"{row_id}slug1").get_attribute( "value" ) slug2 = self.selenium.find_element(By.ID, f"{row_id}slug2").get_attribute( "value" ) self.assertEqual(slug1, "now-you-have-another-stacked-inline-with-a-very-lo") self.assertEqual(slug2, "option-two") # Save and check that everything is properly stored in the database with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.assertEqual(MainPrepopulated.objects.count(), 1) MainPrepopulated.objects.get( name=" the mAin nÀMë and it's awεšomeıııİ", pubdate="2012-02-18", status="option two", slug1="the-main-name-and-its-awesomeiiii-2012-02-18", slug2="option-two-the-main-name-and-its-awesomeiiii", slug3="the-main-nàmë-and-its-awεšomeıııi", ) self.assertEqual(RelatedPrepopulated.objects.count(), 6) RelatedPrepopulated.objects.get( name=" here is a sŤāÇkeð inline ! ", pubdate="2011-12-17", status="option one", slug1="here-is-a-stacked-inline-2011-12-17", slug2="option-one-here-is-a-stacked-inline", ) RelatedPrepopulated.objects.get( # 75 characters in name field name=( " now you haVe anöther sŤāÇkeð inline with a very ... " "loooooooooooooooooo" ), pubdate="1999-01-25", status="option two", slug1="now-you-have-another-stacked-inline-with-a-very-lo", slug2="option-two-now-you-have-another-stacked-inline-with-a-very-l", ) RelatedPrepopulated.objects.get( name="And now, with a tÃbűlaŘ inline !!!", pubdate="1234-12-07", status="option two", slug1="and-now-with-a-tabular-inline-1234-12-07", slug2="option-two-and-now-with-a-tabular-inline", ) RelatedPrepopulated.objects.get( name=r'tÃbűlaŘ inline with ignored ;"&*^\%$#@-/`~ characters', pubdate="1981-08-22", status="option one", slug1="tabular-inline-with-ignored-characters-1981-08-22", slug2="option-one-tabular-inline-with-ignored-characters", ) def test_populate_existing_object(self): """ The prepopulation works for existing objects too, as long as the original field is empty (#19082). """ from selenium.webdriver.common.by import By # Slugs are empty to start with. item = MainPrepopulated.objects.create( name=" this is the mAin nÀMë", pubdate="2012-02-18", status="option two", slug1="", slug2="", ) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) object_url = self.live_server_url + reverse( "admin:admin_views_mainprepopulated_change", args=(item.id,) ) self.selenium.get(object_url) self.selenium.find_element(By.ID, "id_name").send_keys(" the best") # The slugs got prepopulated since they were originally empty slug1 = self.selenium.find_element(By.ID, "id_slug1").get_attribute("value") slug2 = self.selenium.find_element(By.ID, "id_slug2").get_attribute("value") self.assertEqual(slug1, "this-is-the-main-name-the-best-2012-02-18") self.assertEqual(slug2, "option-two-this-is-the-main-name-the-best") # Save the object with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.get(object_url) self.selenium.find_element(By.ID, "id_name").send_keys(" hello") # The slugs got prepopulated didn't change since they were originally not empty slug1 = self.selenium.find_element(By.ID, "id_slug1").get_attribute("value") slug2 = self.selenium.find_element(By.ID, "id_slug2").get_attribute("value") self.assertEqual(slug1, "this-is-the-main-name-the-best-2012-02-18") self.assertEqual(slug2, "option-two-this-is-the-main-name-the-best") def test_collapsible_fieldset(self): """ The 'collapse' class in fieldsets definition allows to show/hide the appropriate field section. """ from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_article_add") ) self.assertFalse(self.selenium.find_element(By.ID, "id_title").is_displayed()) self.selenium.find_elements(By.LINK_TEXT, "Show")[0].click() self.assertTrue(self.selenium.find_element(By.ID, "id_title").is_displayed()) self.assertEqual( self.selenium.find_element(By.ID, "fieldsetcollapser0").text, "Hide" ) def test_selectbox_height_collapsible_fieldset(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin7:index"), ) url = self.live_server_url + reverse("admin7:admin_views_pizza_add") self.selenium.get(url) self.selenium.find_elements(By.LINK_TEXT, "Show")[0].click() from_filter_box = self.selenium.find_element(By.ID, "id_toppings_filter") from_box = self.selenium.find_element(By.ID, "id_toppings_from") to_filter_box = self.selenium.find_element(By.ID, "id_toppings_filter_selected") to_box = self.selenium.find_element(By.ID, "id_toppings_to") self.assertEqual( ( to_filter_box.get_property("offsetHeight") + to_box.get_property("offsetHeight") ), ( from_filter_box.get_property("offsetHeight") + from_box.get_property("offsetHeight") ), ) def test_selectbox_height_not_collapsible_fieldset(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin7:index"), ) url = self.live_server_url + reverse("admin7:admin_views_question_add") self.selenium.get(url) from_filter_box = self.selenium.find_element( By.ID, "id_related_questions_filter" ) from_box = self.selenium.find_element(By.ID, "id_related_questions_from") to_filter_box = self.selenium.find_element( By.ID, "id_related_questions_filter_selected" ) to_box = self.selenium.find_element(By.ID, "id_related_questions_to") self.assertEqual( ( to_filter_box.get_property("offsetHeight") + to_box.get_property("offsetHeight") ), ( from_filter_box.get_property("offsetHeight") + from_box.get_property("offsetHeight") ), ) def test_first_field_focus(self): """JavaScript-assisted auto-focus on first usable form field.""" from selenium.webdriver.common.by import By # First form field has a single widget self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) with self.wait_page_loaded(): self.selenium.get( self.live_server_url + reverse("admin:admin_views_picture_add") ) self.assertEqual( self.selenium.switch_to.active_element, self.selenium.find_element(By.ID, "id_name"), ) # First form field has a MultiWidget with self.wait_page_loaded(): self.selenium.get( self.live_server_url + reverse("admin:admin_views_reservation_add") ) self.assertEqual( self.selenium.switch_to.active_element, self.selenium.find_element(By.ID, "id_start_date_0"), ) def test_cancel_delete_confirmation(self): "Cancelling the deletion of an object takes the user back one page." from selenium.webdriver.common.by import By pizza = Pizza.objects.create(name="Double Cheese") url = reverse("admin:admin_views_pizza_change", args=(pizza.id,)) full_url = self.live_server_url + url self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get(full_url) self.selenium.find_element(By.CLASS_NAME, "deletelink").click() # Click 'cancel' on the delete page. self.selenium.find_element(By.CLASS_NAME, "cancel-link").click() # Wait until we're back on the change page. self.wait_for_text("#content h1", "Change pizza") self.assertEqual(self.selenium.current_url, full_url) self.assertEqual(Pizza.objects.count(), 1) def test_cancel_delete_related_confirmation(self): """ Cancelling the deletion of an object with relations takes the user back one page. """ from selenium.webdriver.common.by import By pizza = Pizza.objects.create(name="Double Cheese") topping1 = Topping.objects.create(name="Cheddar") topping2 = Topping.objects.create(name="Mozzarella") pizza.toppings.add(topping1, topping2) url = reverse("admin:admin_views_pizza_change", args=(pizza.id,)) full_url = self.live_server_url + url self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get(full_url) self.selenium.find_element(By.CLASS_NAME, "deletelink").click() # Click 'cancel' on the delete page. self.selenium.find_element(By.CLASS_NAME, "cancel-link").click() # Wait until we're back on the change page. self.wait_for_text("#content h1", "Change pizza") self.assertEqual(self.selenium.current_url, full_url) self.assertEqual(Pizza.objects.count(), 1) self.assertEqual(Topping.objects.count(), 2) def test_list_editable_popups(self): """ list_editable foreign keys have add/change popups. """ from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select s1 = Section.objects.create(name="Test section") Article.objects.create( title="foo", content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=s1, ) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_article_changelist") ) # Change popup self.selenium.find_element(By.ID, "change_id_form-0-section").click() self.wait_for_and_switch_to_popup() self.wait_for_text("#content h1", "Change section") name_input = self.selenium.find_element(By.ID, "id_name") name_input.clear() name_input.send_keys("<i>edited section</i>") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) # Hide sidebar. toggle_button = self.selenium.find_element( By.CSS_SELECTOR, "#toggle-nav-sidebar" ) toggle_button.click() select = Select(self.selenium.find_element(By.ID, "id_form-0-section")) self.assertEqual(select.first_selected_option.text, "<i>edited section</i>") # Rendered select2 input. select2_display = self.selenium.find_element( By.CLASS_NAME, "select2-selection__rendered" ) # Clear button (×\n) is included in text. self.assertEqual(select2_display.text, "×\n<i>edited section</i>") # Add popup self.selenium.find_element(By.ID, "add_id_form-0-section").click() self.wait_for_and_switch_to_popup() self.wait_for_text("#content h1", "Add section") self.selenium.find_element(By.ID, "id_name").send_keys("new section") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_form-0-section")) self.assertEqual(select.first_selected_option.text, "new section") select2_display = self.selenium.find_element( By.CLASS_NAME, "select2-selection__rendered" ) # Clear button (×\n) is included in text. self.assertEqual(select2_display.text, "×\nnew section") def test_inline_uuid_pk_edit_with_popup(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select parent = ParentWithUUIDPK.objects.create(title="test") related_with_parent = RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_change", args=(related_with_parent.id,), ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "change_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_parent")) self.assertEqual(select.first_selected_option.text, str(parent.id)) self.assertEqual( select.first_selected_option.get_attribute("value"), str(parent.id) ) def test_inline_uuid_pk_add_with_popup(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_relatedwithuuidpkmodel_add") ) self.selenium.find_element(By.ID, "add_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.ID, "id_title").send_keys("test") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_parent")) uuid_id = str(ParentWithUUIDPK.objects.first().id) self.assertEqual(select.first_selected_option.text, uuid_id) self.assertEqual(select.first_selected_option.get_attribute("value"), uuid_id) def test_inline_uuid_pk_delete_with_popup(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select parent = ParentWithUUIDPK.objects.create(title="test") related_with_parent = RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_change", args=(related_with_parent.id,), ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "delete_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.XPATH, '//input[@value="Yes, I’m sure"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) select = Select(self.selenium.find_element(By.ID, "id_parent")) self.assertEqual(ParentWithUUIDPK.objects.count(), 0) self.assertEqual(select.first_selected_option.text, "---------") self.assertEqual(select.first_selected_option.get_attribute("value"), "") def test_inline_with_popup_cancel_delete(self): """Clicking ""No, take me back" on a delete popup closes the window.""" from selenium.webdriver.common.by import By parent = ParentWithUUIDPK.objects.create(title="test") related_with_parent = RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_change", args=(related_with_parent.id,), ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "delete_id_parent").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.XPATH, '//a[text()="No, take me back"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertEqual(len(self.selenium.window_handles), 1) def test_list_editable_raw_id_fields(self): from selenium.webdriver.common.by import By parent = ParentWithUUIDPK.objects.create(title="test") parent2 = ParentWithUUIDPK.objects.create(title="test2") RelatedWithUUIDPKModel.objects.create(parent=parent) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) change_url = reverse( "admin:admin_views_relatedwithuuidpkmodel_changelist", current_app=site2.name, ) self.selenium.get(self.live_server_url + change_url) self.selenium.find_element(By.ID, "lookup_id_form-0-parent").click() self.wait_for_and_switch_to_popup() # Select "parent2" in the popup. self.selenium.find_element(By.LINK_TEXT, str(parent2.pk)).click() self.selenium.switch_to.window(self.selenium.window_handles[0]) # The newly selected pk should appear in the raw id input. value = self.selenium.find_element(By.ID, "id_form-0-parent").get_attribute( "value" ) self.assertEqual(value, str(parent2.pk)) def test_input_element_font(self): """ Browsers' default stylesheets override the font of inputs. The admin adds additional CSS to handle this. """ from selenium.webdriver.common.by import By self.selenium.get(self.live_server_url + reverse("admin:login")) element = self.selenium.find_element(By.ID, "id_username") # Some browsers quotes the fonts, some don't. fonts = [ font.strip().strip('"') for font in element.value_of_css_property("font-family").split(",") ] self.assertEqual( fonts, [ "-apple-system", "BlinkMacSystemFont", "Segoe UI", "system-ui", "Roboto", "Helvetica Neue", "Arial", "sans-serif", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", ], ) def test_search_input_filtered_page(self): from selenium.webdriver.common.by import By Person.objects.create(name="Guido van Rossum", gender=1, alive=True) Person.objects.create(name="Grace Hopper", gender=1, alive=False) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) person_url = reverse("admin:admin_views_person_changelist") + "?q=Gui" self.selenium.get(self.live_server_url + person_url) self.assertGreater( self.selenium.find_element(By.ID, "searchbar").rect["width"], 50, ) def test_related_popup_index(self): """ Create a chain of 'self' related objects via popups. """ from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin:admin_views_box_add", current_app=site.name) self.selenium.get(self.live_server_url + add_url) base_window = self.selenium.current_window_handle self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup() popup_window_test = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=3) popup_window_test2 = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test2") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=4) self.selenium.find_element(By.ID, "id_title").send_keys("test3") self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(popup_window_test2) select = Select(self.selenium.find_element(By.ID, "id_next_box")) next_box_id = str(Box.objects.get(title="test3").id) self.assertEqual( select.first_selected_option.get_attribute("value"), next_box_id ) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(popup_window_test) select = Select(self.selenium.find_element(By.ID, "id_next_box")) next_box_id = str(Box.objects.get(title="test2").id) self.assertEqual( select.first_selected_option.get_attribute("value"), next_box_id ) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.selenium.switch_to.window(base_window) select = Select(self.selenium.find_element(By.ID, "id_next_box")) next_box_id = str(Box.objects.get(title="test").id) self.assertEqual( select.first_selected_option.get_attribute("value"), next_box_id ) def test_related_popup_incorrect_close(self): """ Cleanup child popups when closing a parent popup. """ from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin:admin_views_box_add", current_app=site.name) self.selenium.get(self.live_server_url + add_url) self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup() test_window = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=3) test2_window = self.selenium.current_window_handle self.selenium.find_element(By.ID, "id_title").send_keys("test2") self.selenium.find_element(By.ID, "add_id_next_box").click() self.wait_for_and_switch_to_popup(num_windows=4) self.assertEqual(len(self.selenium.window_handles), 4) self.selenium.switch_to.window(test2_window) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.wait_until(lambda d: len(d.window_handles) == 2, 1) self.assertEqual(len(self.selenium.window_handles), 2) # Close final popup to clean up test. self.selenium.switch_to.window(test_window) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.wait_until(lambda d: len(d.window_handles) == 1, 1) self.selenium.switch_to.window(self.selenium.window_handles[-1]) def test_hidden_fields_small_window(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index"), ) self.selenium.get(self.live_server_url + reverse("admin:admin_views_story_add")) field_title = self.selenium.find_element(By.CLASS_NAME, "field-title") current_size = self.selenium.get_window_size() try: self.selenium.set_window_size(1024, 768) self.assertIs(field_title.is_displayed(), False) self.selenium.set_window_size(767, 575) self.assertIs(field_title.is_displayed(), False) finally: self.selenium.set_window_size(current_size["width"], current_size["height"]) def test_updating_related_objects_updates_fk_selects_except_autocompletes(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select born_country_select_id = "id_born_country" living_country_select_id = "id_living_country" living_country_select2_textbox_id = "select2-id_living_country-container" favorite_country_to_vacation_select_id = "id_favorite_country_to_vacation" continent_select_id = "id_continent" def _get_HTML_inside_element_by_id(id_): return self.selenium.find_element(By.ID, id_).get_attribute("innerHTML") def _get_text_inside_element_by_selector(selector): return self.selenium.find_element(By.CSS_SELECTOR, selector).get_attribute( "innerText" ) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin:admin_views_traveler_add") self.selenium.get(self.live_server_url + add_url) # Add new Country from the born_country select. self.selenium.find_element(By.ID, f"add_{born_country_select_id}").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.ID, "id_name").send_keys("Argentina") continent_select = Select( self.selenium.find_element(By.ID, continent_select_id) ) continent_select.select_by_visible_text("South America") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertHTMLEqual( _get_HTML_inside_element_by_id(born_country_select_id), """ <option value="" selected="">---------</option> <option value="1" selected="">Argentina</option> """, ) # Argentina isn't added to the living_country select nor selected by # the select2 widget. self.assertEqual( _get_text_inside_element_by_selector(f"#{living_country_select_id}"), "" ) self.assertEqual( _get_text_inside_element_by_selector( f"#{living_country_select2_textbox_id}" ), "", ) # Argentina won't appear because favorite_country_to_vacation field has # limit_choices_to. self.assertHTMLEqual( _get_HTML_inside_element_by_id(favorite_country_to_vacation_select_id), '<option value="" selected="">---------</option>', ) # Add new Country from the living_country select. self.selenium.find_element(By.ID, f"add_{living_country_select_id}").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.ID, "id_name").send_keys("Spain") continent_select = Select( self.selenium.find_element(By.ID, continent_select_id) ) continent_select.select_by_visible_text("Europe") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertHTMLEqual( _get_HTML_inside_element_by_id(born_country_select_id), """ <option value="" selected="">---------</option> <option value="1" selected="">Argentina</option> <option value="2">Spain</option> """, ) # Spain is added to the living_country select and it's also selected by # the select2 widget. self.assertEqual( _get_text_inside_element_by_selector(f"#{living_country_select_id} option"), "Spain", ) self.assertEqual( _get_text_inside_element_by_selector( f"#{living_country_select2_textbox_id}" ), "Spain", ) # Spain won't appear because favorite_country_to_vacation field has # limit_choices_to. self.assertHTMLEqual( _get_HTML_inside_element_by_id(favorite_country_to_vacation_select_id), '<option value="" selected="">---------</option>', ) # Edit second Country created from living_country select. favorite_select = Select( self.selenium.find_element(By.ID, living_country_select_id) ) favorite_select.select_by_visible_text("Spain") self.selenium.find_element(By.ID, f"change_{living_country_select_id}").click() self.wait_for_and_switch_to_popup() favorite_name_input = self.selenium.find_element(By.ID, "id_name") favorite_name_input.clear() favorite_name_input.send_keys("Italy") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) self.assertHTMLEqual( _get_HTML_inside_element_by_id(born_country_select_id), """ <option value="" selected="">---------</option> <option value="1" selected="">Argentina</option> <option value="2">Italy</option> """, ) # Italy is added to the living_country select and it's also selected by # the select2 widget. self.assertEqual( _get_text_inside_element_by_selector(f"#{living_country_select_id} option"), "Italy", ) self.assertEqual( _get_text_inside_element_by_selector( f"#{living_country_select2_textbox_id}" ), "Italy", ) # favorite_country_to_vacation field has no options. self.assertHTMLEqual( _get_HTML_inside_element_by_id(favorite_country_to_vacation_select_id), '<option value="" selected="">---------</option>', ) # Add a new Asian country. self.selenium.find_element( By.ID, f"add_{favorite_country_to_vacation_select_id}" ).click() self.wait_for_and_switch_to_popup() favorite_name_input = self.selenium.find_element(By.ID, "id_name") favorite_name_input.send_keys("Qatar") continent_select = Select( self.selenium.find_element(By.ID, continent_select_id) ) continent_select.select_by_visible_text("Asia") self.selenium.find_element(By.CSS_SELECTOR, '[type="submit"]').click() self.selenium.switch_to.window(self.selenium.window_handles[0]) # Submit the new Traveler. self.selenium.find_element(By.CSS_SELECTOR, '[name="_save"]').click() traveler = Traveler.objects.get() self.assertEqual(traveler.born_country.name, "Argentina") self.assertEqual(traveler.living_country.name, "Italy") self.assertEqual(traveler.favorite_country_to_vacation.name, "Qatar") def test_redirect_on_add_view_add_another_button(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin7:admin_views_section_add") self.selenium.get(self.live_server_url + add_url) name_input = self.selenium.find_element(By.ID, "id_name") name_input.send_keys("Test section 1") self.selenium.find_element( By.XPATH, '//input[@value="Save and add another"]' ).click() self.assertEqual(Section.objects.count(), 1) name_input = self.selenium.find_element(By.ID, "id_name") name_input.send_keys("Test section 2") self.selenium.find_element( By.XPATH, '//input[@value="Save and add another"]' ).click() self.assertEqual(Section.objects.count(), 2) def test_redirect_on_add_view_continue_button(self): from selenium.webdriver.common.by import By self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) add_url = reverse("admin7:admin_views_section_add") self.selenium.get(self.live_server_url + add_url) name_input = self.selenium.find_element(By.ID, "id_name") name_input.send_keys("Test section 1") self.selenium.find_element( By.XPATH, '//input[@value="Save and continue editing"]' ).click() self.assertEqual(Section.objects.count(), 1) name_input = self.selenium.find_element(By.ID, "id_name") name_input_value = name_input.get_attribute("value") self.assertEqual(name_input_value, "Test section 1") @override_settings(ROOT_URLCONF="admin_views.urls") class ReadonlyTest(AdminFieldExtractionMixin, TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_readonly_get(self): response = self.client.get(reverse("admin:admin_views_post_add")) self.assertNotContains(response, 'name="posted"') # 3 fields + 2 submit buttons + 5 inline management form fields, + 2 # hidden fields for inlines + 1 field for the inline + 2 empty form # + 1 logout form. self.assertContains(response, "<input", count=17) self.assertContains(response, formats.localize(datetime.date.today())) self.assertContains(response, "<label>Awesomeness level:</label>") self.assertContains(response, "Very awesome.") self.assertContains(response, "Unknown coolness.") self.assertContains(response, "foo") # Multiline text in a readonly field gets <br> tags self.assertContains(response, "Multiline<br>test<br>string") self.assertContains( response, '<div class="readonly">Multiline<br>html<br>content</div>', html=True, ) self.assertContains(response, "InlineMultiline<br>test<br>string") self.assertContains( response, formats.localize(datetime.date.today() - datetime.timedelta(days=7)), ) self.assertContains(response, '<div class="form-row field-coolness">') self.assertContains(response, '<div class="form-row field-awesomeness_level">') self.assertContains(response, '<div class="form-row field-posted">') self.assertContains(response, '<div class="form-row field-value">') self.assertContains(response, '<div class="form-row">') self.assertContains(response, '<div class="help"', 3) self.assertContains( response, '<div class="help" id="id_title_helptext"><div>Some help text for the ' "title (with Unicode ŠĐĆŽćžšđ)</div></div>", html=True, ) self.assertContains( response, '<div class="help" id="id_content_helptext"><div>Some help text for the ' "content (with Unicode ŠĐĆŽćžšđ)</div></div>", html=True, ) self.assertContains( response, '<div class="help"><div>Some help text for the date (with Unicode ŠĐĆŽćžšđ)' "</div></div>", html=True, ) p = Post.objects.create( title="I worked on readonly_fields", content="Its good stuff" ) response = self.client.get( reverse("admin:admin_views_post_change", args=(p.pk,)) ) self.assertContains(response, "%d amount of cool" % p.pk) def test_readonly_text_field(self): p = Post.objects.create( title="Readonly test", content="test", readonly_content="test\r\n\r\ntest\r\n\r\ntest\r\n\r\ntest", ) Link.objects.create( url="http://www.djangoproject.com", post=p, readonly_link_content="test\r\nlink", ) response = self.client.get( reverse("admin:admin_views_post_change", args=(p.pk,)) ) # Checking readonly field. self.assertContains(response, "test<br><br>test<br><br>test<br><br>test") # Checking readonly field in inline. self.assertContains(response, "test<br>link") def test_readonly_post(self): data = { "title": "Django Got Readonly Fields", "content": "This is an incredible development.", "link_set-TOTAL_FORMS": "1", "link_set-INITIAL_FORMS": "0", "link_set-MAX_NUM_FORMS": "0", } response = self.client.post(reverse("admin:admin_views_post_add"), data) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 1) p = Post.objects.get() self.assertEqual(p.posted, datetime.date.today()) data["posted"] = "10-8-1990" # some date that's not today response = self.client.post(reverse("admin:admin_views_post_add"), data) self.assertEqual(response.status_code, 302) self.assertEqual(Post.objects.count(), 2) p = Post.objects.order_by("-id")[0] self.assertEqual(p.posted, datetime.date.today()) def test_readonly_manytomany(self): "Regression test for #13004" response = self.client.get(reverse("admin:admin_views_pizza_add")) self.assertEqual(response.status_code, 200) def test_user_password_change_limited_queryset(self): su = User.objects.filter(is_superuser=True)[0] response = self.client.get( reverse("admin2:auth_user_password_change", args=(su.pk,)) ) self.assertEqual(response.status_code, 404) def test_change_form_renders_correct_null_choice_value(self): """ Regression test for #17911. """ choice = Choice.objects.create(choice=None) response = self.client.get( reverse("admin:admin_views_choice_change", args=(choice.pk,)) ) self.assertContains( response, '<div class="readonly">No opinion</div>', html=True ) def _test_readonly_foreignkey_links(self, admin_site): """ ForeignKey readonly fields render as links if the target model is registered in admin. """ chapter = Chapter.objects.create( title="Chapter 1", content="content", book=Book.objects.create(name="Book 1"), ) language = Language.objects.create(iso="_40", name="Test") obj = ReadOnlyRelatedField.objects.create( chapter=chapter, language=language, user=self.superuser, ) response = self.client.get( reverse( f"{admin_site}:admin_views_readonlyrelatedfield_change", args=(obj.pk,) ), ) # Related ForeignKey object registered in admin. user_url = reverse(f"{admin_site}:auth_user_change", args=(self.superuser.pk,)) self.assertContains( response, '<div class="readonly"><a href="%s">super</a></div>' % user_url, html=True, ) # Related ForeignKey with the string primary key registered in admin. language_url = reverse( f"{admin_site}:admin_views_language_change", args=(quote(language.pk),), ) self.assertContains( response, '<div class="readonly"><a href="%s">_40</a></div>' % language_url, html=True, ) # Related ForeignKey object not registered in admin. self.assertContains( response, '<div class="readonly">Chapter 1</div>', html=True ) def test_readonly_foreignkey_links_default_admin_site(self): self._test_readonly_foreignkey_links("admin") def test_readonly_foreignkey_links_custom_admin_site(self): self._test_readonly_foreignkey_links("namespaced_admin") def test_readonly_manytomany_backwards_ref(self): """ Regression test for #16433 - backwards references for related objects broke if the related field is read-only due to the help_text attribute """ topping = Topping.objects.create(name="Salami") pizza = Pizza.objects.create(name="Americano") pizza.toppings.add(topping) response = self.client.get(reverse("admin:admin_views_topping_add")) self.assertEqual(response.status_code, 200) def test_readonly_manytomany_forwards_ref(self): topping = Topping.objects.create(name="Salami") pizza = Pizza.objects.create(name="Americano") pizza.toppings.add(topping) response = self.client.get( reverse("admin:admin_views_pizza_change", args=(pizza.pk,)) ) self.assertContains(response, "<label>Toppings:</label>", html=True) self.assertContains(response, '<div class="readonly">Salami</div>', html=True) def test_readonly_onetoone_backwards_ref(self): """ Can reference a reverse OneToOneField in ModelAdmin.readonly_fields. """ v1 = Villain.objects.create(name="Adam") pl = Plot.objects.create(name="Test Plot", team_leader=v1, contact=v1) pd = PlotDetails.objects.create(details="Brand New Plot", plot=pl) response = self.client.get( reverse("admin:admin_views_plotproxy_change", args=(pl.pk,)) ) field = self.get_admin_readonly_field(response, "plotdetails") pd_url = reverse("admin:admin_views_plotdetails_change", args=(pd.pk,)) self.assertEqual(field.contents(), '<a href="%s">Brand New Plot</a>' % pd_url) # The reverse relation also works if the OneToOneField is null. pd.plot = None pd.save() response = self.client.get( reverse("admin:admin_views_plotproxy_change", args=(pl.pk,)) ) field = self.get_admin_readonly_field(response, "plotdetails") self.assertEqual(field.contents(), "-") # default empty value def test_readonly_field_overrides(self): """ Regression test for #22087 - ModelForm Meta overrides are ignored by AdminReadonlyField """ p = FieldOverridePost.objects.create(title="Test Post", content="Test Content") response = self.client.get( reverse("admin:admin_views_fieldoverridepost_change", args=(p.pk,)) ) self.assertContains( response, '<div class="help"><div>Overridden help text for the date</div></div>', html=True, ) self.assertContains( response, '<label for="id_public">Overridden public label:</label>', html=True, ) self.assertNotContains( response, "Some help text for the date (with Unicode ŠĐĆŽćžšđ)" ) def test_correct_autoescaping(self): """ Make sure that non-field readonly elements are properly autoescaped (#24461) """ section = Section.objects.create(name="<a>evil</a>") response = self.client.get( reverse("admin:admin_views_section_change", args=(section.pk,)) ) self.assertNotContains(response, "<a>evil</a>", status_code=200) self.assertContains(response, "&lt;a&gt;evil&lt;/a&gt;", status_code=200) def test_label_suffix_translated(self): pizza = Pizza.objects.create(name="Americano") url = reverse("admin:admin_views_pizza_change", args=(pizza.pk,)) with self.settings(LANGUAGE_CODE="fr"): response = self.client.get(url) self.assertContains(response, "<label>Toppings\u00A0:</label>", html=True) @override_settings(ROOT_URLCONF="admin_views.urls") class LimitChoicesToInAdminTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_limit_choices_to_as_callable(self): """Test for ticket 2445 changes to admin.""" threepwood = Character.objects.create( username="threepwood", last_action=datetime.datetime.today() + datetime.timedelta(days=1), ) marley = Character.objects.create( username="marley", last_action=datetime.datetime.today() - datetime.timedelta(days=1), ) response = self.client.get(reverse("admin:admin_views_stumpjoke_add")) # The allowed option should appear twice; the limited option should not appear. self.assertContains(response, threepwood.username, count=2) self.assertNotContains(response, marley.username) @override_settings(ROOT_URLCONF="admin_views.urls") class RawIdFieldsTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_limit_choices_to(self): """Regression test for 14880""" actor = Actor.objects.create(name="Palin", age=27) Inquisition.objects.create(expected=True, leader=actor, country="England") Inquisition.objects.create(expected=False, leader=actor, country="Spain") response = self.client.get(reverse("admin:admin_views_sketch_add")) # Find the link m = re.search( rb'<a href="([^"]*)"[^>]* id="lookup_id_inquisition"', response.content ) self.assertTrue(m) # Got a match popup_url = m[1].decode().replace("&amp;", "&") # Handle relative links popup_url = urljoin(response.request["PATH_INFO"], popup_url) # Get the popup and verify the correct objects show up in the resulting # page. This step also tests integers, strings and booleans in the # lookup query string; in model we define inquisition field to have a # limit_choices_to option that includes a filter on a string field # (inquisition__actor__name), a filter on an integer field # (inquisition__actor__age), and a filter on a boolean field # (inquisition__expected). response2 = self.client.get(popup_url) self.assertContains(response2, "Spain") self.assertNotContains(response2, "England") def test_limit_choices_to_isnull_false(self): """Regression test for 20182""" Actor.objects.create(name="Palin", age=27) Actor.objects.create(name="Kilbraken", age=50, title="Judge") response = self.client.get(reverse("admin:admin_views_sketch_add")) # Find the link m = re.search( rb'<a href="([^"]*)"[^>]* id="lookup_id_defendant0"', response.content ) self.assertTrue(m) # Got a match popup_url = m[1].decode().replace("&amp;", "&") # Handle relative links popup_url = urljoin(response.request["PATH_INFO"], popup_url) # Get the popup and verify the correct objects show up in the resulting # page. This step tests field__isnull=0 gets parsed correctly from the # lookup query string; in model we define defendant0 field to have a # limit_choices_to option that includes "actor__title__isnull=False". response2 = self.client.get(popup_url) self.assertContains(response2, "Kilbraken") self.assertNotContains(response2, "Palin") def test_limit_choices_to_isnull_true(self): """Regression test for 20182""" Actor.objects.create(name="Palin", age=27) Actor.objects.create(name="Kilbraken", age=50, title="Judge") response = self.client.get(reverse("admin:admin_views_sketch_add")) # Find the link m = re.search( rb'<a href="([^"]*)"[^>]* id="lookup_id_defendant1"', response.content ) self.assertTrue(m) # Got a match popup_url = m[1].decode().replace("&amp;", "&") # Handle relative links popup_url = urljoin(response.request["PATH_INFO"], popup_url) # Get the popup and verify the correct objects show up in the resulting # page. This step tests field__isnull=1 gets parsed correctly from the # lookup query string; in model we define defendant1 field to have a # limit_choices_to option that includes "actor__title__isnull=True". response2 = self.client.get(popup_url) self.assertNotContains(response2, "Kilbraken") self.assertContains(response2, "Palin") def test_list_display_method_same_name_as_reverse_accessor(self): """ Should be able to use a ModelAdmin method in list_display that has the same name as a reverse model field ("sketch" in this case). """ actor = Actor.objects.create(name="Palin", age=27) Inquisition.objects.create(expected=True, leader=actor, country="England") response = self.client.get(reverse("admin:admin_views_inquisition_changelist")) self.assertContains(response, "list-display-sketch") @override_settings(ROOT_URLCONF="admin_views.urls") class UserAdminTest(TestCase): """ Tests user CRUD functionality. """ @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.adduser = User.objects.create_user( username="adduser", password="secret", is_staff=True ) cls.changeuser = User.objects.create_user( username="changeuser", password="secret", is_staff=True ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.per1 = Person.objects.create(name="John Mauchly", gender=1, alive=True) cls.per2 = Person.objects.create(name="Grace Hopper", gender=1, alive=False) cls.per3 = Person.objects.create(name="Guido van Rossum", gender=1, alive=True) def setUp(self): self.client.force_login(self.superuser) def test_save_button(self): user_count = User.objects.count() response = self.client.post( reverse("admin:auth_user_add"), { "username": "newuser", "password1": "newpassword", "password2": "newpassword", }, ) new_user = User.objects.get(username="newuser") self.assertRedirects( response, reverse("admin:auth_user_change", args=(new_user.pk,)) ) self.assertEqual(User.objects.count(), user_count + 1) self.assertTrue(new_user.has_usable_password()) def test_save_continue_editing_button(self): user_count = User.objects.count() response = self.client.post( reverse("admin:auth_user_add"), { "username": "newuser", "password1": "newpassword", "password2": "newpassword", "_continue": "1", }, ) new_user = User.objects.get(username="newuser") new_user_url = reverse("admin:auth_user_change", args=(new_user.pk,)) self.assertRedirects(response, new_user_url, fetch_redirect_response=False) self.assertEqual(User.objects.count(), user_count + 1) self.assertTrue(new_user.has_usable_password()) response = self.client.get(new_user_url) self.assertContains( response, '<li class="success">The user “<a href="%s">' "%s</a>” was added successfully. You may edit it again below.</li>" % (new_user_url, new_user), html=True, ) def test_password_mismatch(self): response = self.client.post( reverse("admin:auth_user_add"), { "username": "newuser", "password1": "newpassword", "password2": "mismatch", }, ) self.assertEqual(response.status_code, 200) self.assertFormError(response.context["adminform"], "password1", []) self.assertFormError( response.context["adminform"], "password2", ["The two password fields didn’t match."], ) def test_user_fk_add_popup(self): """ User addition through a FK popup should return the appropriate JavaScript response. """ response = self.client.get(reverse("admin:admin_views_album_add")) self.assertContains(response, reverse("admin:auth_user_add")) self.assertContains( response, 'class="related-widget-wrapper-link add-related" id="add_id_owner"', ) response = self.client.get( reverse("admin:auth_user_add") + "?%s=1" % IS_POPUP_VAR ) self.assertNotContains(response, 'name="_continue"') self.assertNotContains(response, 'name="_addanother"') data = { "username": "newuser", "password1": "newpassword", "password2": "newpassword", IS_POPUP_VAR: "1", "_save": "1", } response = self.client.post( reverse("admin:auth_user_add") + "?%s=1" % IS_POPUP_VAR, data, follow=True ) self.assertContains(response, "&quot;obj&quot;: &quot;newuser&quot;") def test_user_fk_change_popup(self): """ User change through a FK popup should return the appropriate JavaScript response. """ response = self.client.get(reverse("admin:admin_views_album_add")) self.assertContains( response, reverse("admin:auth_user_change", args=("__fk__",)) ) self.assertContains( response, 'class="related-widget-wrapper-link change-related" id="change_id_owner"', ) user = User.objects.get(username="changeuser") url = ( reverse("admin:auth_user_change", args=(user.pk,)) + "?%s=1" % IS_POPUP_VAR ) response = self.client.get(url) self.assertNotContains(response, 'name="_continue"') self.assertNotContains(response, 'name="_addanother"') data = { "username": "newuser", "password1": "newpassword", "password2": "newpassword", "last_login_0": "2007-05-30", "last_login_1": "13:20:10", "date_joined_0": "2007-05-30", "date_joined_1": "13:20:10", IS_POPUP_VAR: "1", "_save": "1", } response = self.client.post(url, data, follow=True) self.assertContains(response, "&quot;obj&quot;: &quot;newuser&quot;") self.assertContains(response, "&quot;action&quot;: &quot;change&quot;") def test_user_fk_delete_popup(self): """ User deletion through a FK popup should return the appropriate JavaScript response. """ response = self.client.get(reverse("admin:admin_views_album_add")) self.assertContains( response, reverse("admin:auth_user_delete", args=("__fk__",)) ) self.assertContains( response, 'class="related-widget-wrapper-link change-related" id="change_id_owner"', ) user = User.objects.get(username="changeuser") url = ( reverse("admin:auth_user_delete", args=(user.pk,)) + "?%s=1" % IS_POPUP_VAR ) response = self.client.get(url) self.assertEqual(response.status_code, 200) data = { "post": "yes", IS_POPUP_VAR: "1", } response = self.client.post(url, data, follow=True) self.assertContains(response, "&quot;action&quot;: &quot;delete&quot;") def test_save_add_another_button(self): user_count = User.objects.count() response = self.client.post( reverse("admin:auth_user_add"), { "username": "newuser", "password1": "newpassword", "password2": "newpassword", "_addanother": "1", }, ) new_user = User.objects.order_by("-id")[0] self.assertRedirects(response, reverse("admin:auth_user_add")) self.assertEqual(User.objects.count(), user_count + 1) self.assertTrue(new_user.has_usable_password()) def test_user_permission_performance(self): u = User.objects.all()[0] # Don't depend on a warm cache, see #17377. ContentType.objects.clear_cache() expected_num_queries = 10 if connection.features.uses_savepoints else 8 with self.assertNumQueries(expected_num_queries): response = self.client.get(reverse("admin:auth_user_change", args=(u.pk,))) self.assertEqual(response.status_code, 200) def test_form_url_present_in_context(self): u = User.objects.all()[0] response = self.client.get( reverse("admin3:auth_user_password_change", args=(u.pk,)) ) self.assertEqual(response.status_code, 200) self.assertEqual(response.context["form_url"], "pony") @override_settings(ROOT_URLCONF="admin_views.urls") class GroupAdminTest(TestCase): """ Tests group CRUD functionality. """ @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_save_button(self): group_count = Group.objects.count() response = self.client.post( reverse("admin:auth_group_add"), { "name": "newgroup", }, ) Group.objects.order_by("-id")[0] self.assertRedirects(response, reverse("admin:auth_group_changelist")) self.assertEqual(Group.objects.count(), group_count + 1) def test_group_permission_performance(self): g = Group.objects.create(name="test_group") # Ensure no queries are skipped due to cached content type for Group. ContentType.objects.clear_cache() expected_num_queries = 8 if connection.features.uses_savepoints else 6 with self.assertNumQueries(expected_num_queries): response = self.client.get(reverse("admin:auth_group_change", args=(g.pk,))) self.assertEqual(response.status_code, 200) @override_settings(ROOT_URLCONF="admin_views.urls") class CSSTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) def setUp(self): self.client.force_login(self.superuser) def test_field_prefix_css_classes(self): """ Fields have a CSS class name with a 'field-' prefix. """ response = self.client.get(reverse("admin:admin_views_post_add")) # The main form self.assertContains(response, 'class="form-row field-title"') self.assertContains(response, 'class="form-row field-content"') self.assertContains(response, 'class="form-row field-public"') self.assertContains(response, 'class="form-row field-awesomeness_level"') self.assertContains(response, 'class="form-row field-coolness"') self.assertContains(response, 'class="form-row field-value"') self.assertContains(response, 'class="form-row"') # The lambda function # The tabular inline self.assertContains(response, '<td class="field-url">') self.assertContains(response, '<td class="field-posted">') def test_index_css_classes(self): """ CSS class names are used for each app and model on the admin index pages (#17050). """ # General index page response = self.client.get(reverse("admin:index")) self.assertContains(response, '<div class="app-admin_views module') self.assertContains(response, '<tr class="model-actor">') self.assertContains(response, '<tr class="model-album">') # App index page response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertContains(response, '<div class="app-admin_views module') self.assertContains(response, '<tr class="model-actor">') self.assertContains(response, '<tr class="model-album">') def test_app_model_in_form_body_class(self): """ Ensure app and model tag are correctly read by change_form template """ response = self.client.get(reverse("admin:admin_views_section_add")) self.assertContains(response, '<body class=" app-admin_views model-section ') def test_app_model_in_list_body_class(self): """ Ensure app and model tag are correctly read by change_list template """ response = self.client.get(reverse("admin:admin_views_section_changelist")) self.assertContains(response, '<body class=" app-admin_views model-section ') def test_app_model_in_delete_confirmation_body_class(self): """ Ensure app and model tag are correctly read by delete_confirmation template """ response = self.client.get( reverse("admin:admin_views_section_delete", args=(self.s1.pk,)) ) self.assertContains(response, '<body class=" app-admin_views model-section ') def test_app_model_in_app_index_body_class(self): """ Ensure app and model tag are correctly read by app_index template """ response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertContains(response, '<body class=" dashboard app-admin_views') def test_app_model_in_delete_selected_confirmation_body_class(self): """ Ensure app and model tag are correctly read by delete_selected_confirmation template """ action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], "action": "delete_selected", "index": 0, } response = self.client.post( reverse("admin:admin_views_section_changelist"), action_data ) self.assertContains(response, '<body class=" app-admin_views model-section ') def test_changelist_field_classes(self): """ Cells of the change list table should contain the field name in their class attribute. """ Podcast.objects.create(name="Django Dose", release_date=datetime.date.today()) response = self.client.get(reverse("admin:admin_views_podcast_changelist")) self.assertContains(response, '<th class="field-name">') self.assertContains(response, '<td class="field-release_date nowrap">') self.assertContains(response, '<td class="action-checkbox">') try: import docutils except ImportError: docutils = None @unittest.skipUnless(docutils, "no docutils installed.") @override_settings(ROOT_URLCONF="admin_views.urls") @modify_settings( INSTALLED_APPS={"append": ["django.contrib.admindocs", "django.contrib.flatpages"]} ) class AdminDocsTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_tags(self): response = self.client.get(reverse("django-admindocs-tags")) # The builtin tag group exists self.assertContains(response, "<h2>Built-in tags</h2>", count=2, html=True) # A builtin tag exists in both the index and detail self.assertContains( response, '<h3 id="built_in-autoescape">autoescape</h3>', html=True ) self.assertContains( response, '<li><a href="#built_in-autoescape">autoescape</a></li>', html=True, ) # An app tag exists in both the index and detail self.assertContains( response, '<h3 id="flatpages-get_flatpages">get_flatpages</h3>', html=True ) self.assertContains( response, '<li><a href="#flatpages-get_flatpages">get_flatpages</a></li>', html=True, ) # The admin list tag group exists self.assertContains(response, "<h2>admin_list</h2>", count=2, html=True) # An admin list tag exists in both the index and detail self.assertContains( response, '<h3 id="admin_list-admin_actions">admin_actions</h3>', html=True ) self.assertContains( response, '<li><a href="#admin_list-admin_actions">admin_actions</a></li>', html=True, ) def test_filters(self): response = self.client.get(reverse("django-admindocs-filters")) # The builtin filter group exists self.assertContains(response, "<h2>Built-in filters</h2>", count=2, html=True) # A builtin filter exists in both the index and detail self.assertContains(response, '<h3 id="built_in-add">add</h3>', html=True) self.assertContains( response, '<li><a href="#built_in-add">add</a></li>', html=True ) @override_settings( ROOT_URLCONF="admin_views.urls", TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ], ) class ValidXHTMLTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_lang_name_present(self): with translation.override(None): response = self.client.get(reverse("admin:app_list", args=("admin_views",))) self.assertNotContains(response, ' lang=""') self.assertNotContains(response, ' xml:lang=""') @override_settings(ROOT_URLCONF="admin_views.urls", USE_THOUSAND_SEPARATOR=True) class DateHierarchyTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def assert_non_localized_year(self, response, year): """ The year is not localized with USE_THOUSAND_SEPARATOR (#15234). """ self.assertNotContains(response, formats.number_format(year)) def assert_contains_year_link(self, response, date): self.assertContains(response, '?release_date__year=%d"' % date.year) def assert_contains_month_link(self, response, date): self.assertContains( response, '?release_date__month=%d&amp;release_date__year=%d"' % (date.month, date.year), ) def assert_contains_day_link(self, response, date): self.assertContains( response, "?release_date__day=%d&amp;" 'release_date__month=%d&amp;release_date__year=%d"' % (date.day, date.month, date.year), ) def test_empty(self): """ No date hierarchy links display with empty changelist. """ response = self.client.get(reverse("admin:admin_views_podcast_changelist")) self.assertNotContains(response, "release_date__year=") self.assertNotContains(response, "release_date__month=") self.assertNotContains(response, "release_date__day=") def test_single(self): """ Single day-level date hierarchy appears for single object. """ DATE = datetime.date(2000, 6, 30) Podcast.objects.create(release_date=DATE) url = reverse("admin:admin_views_podcast_changelist") response = self.client.get(url) self.assert_contains_day_link(response, DATE) self.assert_non_localized_year(response, 2000) def test_within_month(self): """ day-level links appear for changelist within single month. """ DATES = ( datetime.date(2000, 6, 30), datetime.date(2000, 6, 15), datetime.date(2000, 6, 3), ) for date in DATES: Podcast.objects.create(release_date=date) url = reverse("admin:admin_views_podcast_changelist") response = self.client.get(url) for date in DATES: self.assert_contains_day_link(response, date) self.assert_non_localized_year(response, 2000) def test_within_year(self): """ month-level links appear for changelist within single year. """ DATES = ( datetime.date(2000, 1, 30), datetime.date(2000, 3, 15), datetime.date(2000, 5, 3), ) for date in DATES: Podcast.objects.create(release_date=date) url = reverse("admin:admin_views_podcast_changelist") response = self.client.get(url) # no day-level links self.assertNotContains(response, "release_date__day=") for date in DATES: self.assert_contains_month_link(response, date) self.assert_non_localized_year(response, 2000) def test_multiple_years(self): """ year-level links appear for year-spanning changelist. """ DATES = ( datetime.date(2001, 1, 30), datetime.date(2003, 3, 15), datetime.date(2005, 5, 3), ) for date in DATES: Podcast.objects.create(release_date=date) response = self.client.get(reverse("admin:admin_views_podcast_changelist")) # no day/month-level links self.assertNotContains(response, "release_date__day=") self.assertNotContains(response, "release_date__month=") for date in DATES: self.assert_contains_year_link(response, date) # and make sure GET parameters still behave correctly for date in DATES: url = "%s?release_date__year=%d" % ( reverse("admin:admin_views_podcast_changelist"), date.year, ) response = self.client.get(url) self.assert_contains_month_link(response, date) self.assert_non_localized_year(response, 2000) self.assert_non_localized_year(response, 2003) self.assert_non_localized_year(response, 2005) url = "%s?release_date__year=%d&release_date__month=%d" % ( reverse("admin:admin_views_podcast_changelist"), date.year, date.month, ) response = self.client.get(url) self.assert_contains_day_link(response, date) self.assert_non_localized_year(response, 2000) self.assert_non_localized_year(response, 2003) self.assert_non_localized_year(response, 2005) def test_related_field(self): questions_data = ( # (posted data, number of answers), (datetime.date(2001, 1, 30), 0), (datetime.date(2003, 3, 15), 1), (datetime.date(2005, 5, 3), 2), ) for date, answer_count in questions_data: question = Question.objects.create(posted=date) for i in range(answer_count): question.answer_set.create() response = self.client.get(reverse("admin:admin_views_answer_changelist")) for date, answer_count in questions_data: link = '?question__posted__year=%d"' % date.year if answer_count > 0: self.assertContains(response, link) else: self.assertNotContains(response, link) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminCustomSaveRelatedTests(TestCase): """ One can easily customize the way related objects are saved. Refs #16115. """ @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_should_be_able_to_edit_related_objects_on_add_view(self): post = { "child_set-TOTAL_FORMS": "3", "child_set-INITIAL_FORMS": "0", "name": "Josh Stone", "child_set-0-name": "Paul", "child_set-1-name": "Catherine", } self.client.post(reverse("admin:admin_views_parent_add"), post) self.assertEqual(1, Parent.objects.count()) self.assertEqual(2, Child.objects.count()) children_names = list( Child.objects.order_by("name").values_list("name", flat=True) ) self.assertEqual("Josh Stone", Parent.objects.latest("id").name) self.assertEqual(["Catherine Stone", "Paul Stone"], children_names) def test_should_be_able_to_edit_related_objects_on_change_view(self): parent = Parent.objects.create(name="Josh Stone") paul = Child.objects.create(parent=parent, name="Paul") catherine = Child.objects.create(parent=parent, name="Catherine") post = { "child_set-TOTAL_FORMS": "5", "child_set-INITIAL_FORMS": "2", "name": "Josh Stone", "child_set-0-name": "Paul", "child_set-0-id": paul.id, "child_set-1-name": "Catherine", "child_set-1-id": catherine.id, } self.client.post( reverse("admin:admin_views_parent_change", args=(parent.id,)), post ) children_names = list( Child.objects.order_by("name").values_list("name", flat=True) ) self.assertEqual("Josh Stone", Parent.objects.latest("id").name) self.assertEqual(["Catherine Stone", "Paul Stone"], children_names) def test_should_be_able_to_edit_related_objects_on_changelist_view(self): parent = Parent.objects.create(name="Josh Rock") Child.objects.create(parent=parent, name="Paul") Child.objects.create(parent=parent, name="Catherine") post = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "1", "form-MAX_NUM_FORMS": "0", "form-0-id": parent.id, "form-0-name": "Josh Stone", "_save": "Save", } self.client.post(reverse("admin:admin_views_parent_changelist"), post) children_names = list( Child.objects.order_by("name").values_list("name", flat=True) ) self.assertEqual("Josh Stone", Parent.objects.latest("id").name) self.assertEqual(["Catherine Stone", "Paul Stone"], children_names) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewLogoutTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def test_logout(self): self.client.force_login(self.superuser) response = self.client.post(reverse("admin:logout")) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "registration/logged_out.html") self.assertEqual(response.request["PATH_INFO"], reverse("admin:logout")) self.assertFalse(response.context["has_permission"]) self.assertNotContains( response, "user-tools" ) # user-tools div shouldn't visible. def test_client_logout_url_can_be_used_to_login(self): response = self.client.post(reverse("admin:logout")) self.assertEqual( response.status_code, 302 ) # we should be redirected to the login page. # follow the redirect and test results. response = self.client.post(reverse("admin:logout"), follow=True) self.assertContains( response, '<input type="hidden" name="next" value="%s">' % reverse("admin:index"), ) self.assertTemplateUsed(response, "admin/login.html") self.assertEqual(response.request["PATH_INFO"], reverse("admin:login")) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminUserMessageTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def send_message(self, level): """ Helper that sends a post to the dummy test methods and asserts that a message with the level has appeared in the response. """ action_data = { ACTION_CHECKBOX_NAME: [1], "action": "message_%s" % level, "index": 0, } response = self.client.post( reverse("admin:admin_views_usermessenger_changelist"), action_data, follow=True, ) self.assertContains( response, '<li class="%s">Test %s</li>' % (level, level), html=True ) @override_settings(MESSAGE_LEVEL=10) # Set to DEBUG for this request def test_message_debug(self): self.send_message("debug") def test_message_info(self): self.send_message("info") def test_message_success(self): self.send_message("success") def test_message_warning(self): self.send_message("warning") def test_message_error(self): self.send_message("error") def test_message_extra_tags(self): action_data = { ACTION_CHECKBOX_NAME: [1], "action": "message_extra_tags", "index": 0, } response = self.client.post( reverse("admin:admin_views_usermessenger_changelist"), action_data, follow=True, ) self.assertContains( response, '<li class="extra_tag info">Test tags</li>', html=True ) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminKeepChangeListFiltersTests(TestCase): admin_site = site @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.joepublicuser = User.objects.create_user( username="joepublic", password="secret" ) def setUp(self): self.client.force_login(self.superuser) def assertURLEqual(self, url1, url2, msg_prefix=""): """ Assert that two URLs are equal despite the ordering of their querystring. Refs #22360. """ parsed_url1 = urlparse(url1) path1 = parsed_url1.path parsed_qs1 = dict(parse_qsl(parsed_url1.query)) parsed_url2 = urlparse(url2) path2 = parsed_url2.path parsed_qs2 = dict(parse_qsl(parsed_url2.query)) for parsed_qs in [parsed_qs1, parsed_qs2]: if "_changelist_filters" in parsed_qs: changelist_filters = parsed_qs["_changelist_filters"] parsed_filters = dict(parse_qsl(changelist_filters)) parsed_qs["_changelist_filters"] = parsed_filters self.assertEqual(path1, path2) self.assertEqual(parsed_qs1, parsed_qs2) def test_assert_url_equal(self): # Test equality. change_user_url = reverse( "admin:auth_user_change", args=(self.joepublicuser.pk,) ) self.assertURLEqual( "http://testserver{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), "http://testserver{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), ) # Test inequality. with self.assertRaises(AssertionError): self.assertURLEqual( "http://testserver{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), "http://testserver{}?_changelist_filters=" "is_staff__exact%3D1%26is_superuser__exact%3D1".format(change_user_url), ) # Ignore scheme and host. self.assertURLEqual( "http://testserver{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), "{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), ) # Ignore ordering of querystring. self.assertURLEqual( "{}?is_staff__exact=0&is_superuser__exact=0".format( reverse("admin:auth_user_changelist") ), "{}?is_superuser__exact=0&is_staff__exact=0".format( reverse("admin:auth_user_changelist") ), ) # Ignore ordering of _changelist_filters. self.assertURLEqual( "{}?_changelist_filters=" "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url), "{}?_changelist_filters=" "is_superuser__exact%3D0%26is_staff__exact%3D0".format(change_user_url), ) def get_changelist_filters(self): return { "is_superuser__exact": 0, "is_staff__exact": 0, } def get_changelist_filters_querystring(self): return urlencode(self.get_changelist_filters()) def get_preserved_filters_querystring(self): return urlencode( {"_changelist_filters": self.get_changelist_filters_querystring()} ) def get_sample_user_id(self): return self.joepublicuser.pk def get_changelist_url(self): return "%s?%s" % ( reverse("admin:auth_user_changelist", current_app=self.admin_site.name), self.get_changelist_filters_querystring(), ) def get_add_url(self, add_preserved_filters=True): url = reverse("admin:auth_user_add", current_app=self.admin_site.name) if add_preserved_filters: url = "%s?%s" % (url, self.get_preserved_filters_querystring()) return url def get_change_url(self, user_id=None, add_preserved_filters=True): if user_id is None: user_id = self.get_sample_user_id() url = reverse( "admin:auth_user_change", args=(user_id,), current_app=self.admin_site.name ) if add_preserved_filters: url = "%s?%s" % (url, self.get_preserved_filters_querystring()) return url def get_history_url(self, user_id=None): if user_id is None: user_id = self.get_sample_user_id() return "%s?%s" % ( reverse( "admin:auth_user_history", args=(user_id,), current_app=self.admin_site.name, ), self.get_preserved_filters_querystring(), ) def get_delete_url(self, user_id=None): if user_id is None: user_id = self.get_sample_user_id() return "%s?%s" % ( reverse( "admin:auth_user_delete", args=(user_id,), current_app=self.admin_site.name, ), self.get_preserved_filters_querystring(), ) def test_changelist_view(self): response = self.client.get(self.get_changelist_url()) self.assertEqual(response.status_code, 200) # Check the `change_view` link has the correct querystring. detail_link = re.search( '<a href="(.*?)">{}</a>'.format(self.joepublicuser.username), response.content.decode(), ) self.assertURLEqual(detail_link[1], self.get_change_url()) def test_change_view(self): # Get the `change_view`. response = self.client.get(self.get_change_url()) self.assertEqual(response.status_code, 200) # Check the form action. form_action = re.search( '<form action="(.*?)" method="post" id="user_form" novalidate>', response.content.decode(), ) self.assertURLEqual( form_action[1], "?%s" % self.get_preserved_filters_querystring() ) # Check the history link. history_link = re.search( '<a href="(.*?)" class="historylink">History</a>', response.content.decode() ) self.assertURLEqual(history_link[1], self.get_history_url()) # Check the delete link. delete_link = re.search( '<a href="(.*?)" class="deletelink">Delete</a>', response.content.decode() ) self.assertURLEqual(delete_link[1], self.get_delete_url()) # Test redirect on "Save". post_data = { "username": "joepublic", "last_login_0": "2007-05-30", "last_login_1": "13:20:10", "date_joined_0": "2007-05-30", "date_joined_1": "13:20:10", } post_data["_save"] = 1 response = self.client.post(self.get_change_url(), data=post_data) self.assertRedirects(response, self.get_changelist_url()) post_data.pop("_save") # Test redirect on "Save and continue". post_data["_continue"] = 1 response = self.client.post(self.get_change_url(), data=post_data) self.assertRedirects(response, self.get_change_url()) post_data.pop("_continue") # Test redirect on "Save and add new". post_data["_addanother"] = 1 response = self.client.post(self.get_change_url(), data=post_data) self.assertRedirects(response, self.get_add_url()) post_data.pop("_addanother") def test_change_view_close_link(self): viewuser = User.objects.create_user( username="view", password="secret", is_staff=True ) viewuser.user_permissions.add( get_perm(User, get_permission_codename("view", User._meta)) ) self.client.force_login(viewuser) response = self.client.get(self.get_change_url()) close_link = re.search( '<a href="(.*?)" class="closelink">Close</a>', response.content.decode() ) close_link = close_link[1].replace("&amp;", "&") self.assertURLEqual(close_link, self.get_changelist_url()) def test_change_view_without_preserved_filters(self): response = self.client.get(self.get_change_url(add_preserved_filters=False)) # The action attribute is omitted. self.assertContains(response, '<form method="post" id="user_form" novalidate>') def test_add_view(self): # Get the `add_view`. response = self.client.get(self.get_add_url()) self.assertEqual(response.status_code, 200) # Check the form action. form_action = re.search( '<form action="(.*?)" method="post" id="user_form" novalidate>', response.content.decode(), ) self.assertURLEqual( form_action[1], "?%s" % self.get_preserved_filters_querystring() ) post_data = { "username": "dummy", "password1": "test", "password2": "test", } # Test redirect on "Save". post_data["_save"] = 1 response = self.client.post(self.get_add_url(), data=post_data) self.assertRedirects( response, self.get_change_url(User.objects.get(username="dummy").pk) ) post_data.pop("_save") # Test redirect on "Save and continue". post_data["username"] = "dummy2" post_data["_continue"] = 1 response = self.client.post(self.get_add_url(), data=post_data) self.assertRedirects( response, self.get_change_url(User.objects.get(username="dummy2").pk) ) post_data.pop("_continue") # Test redirect on "Save and add new". post_data["username"] = "dummy3" post_data["_addanother"] = 1 response = self.client.post(self.get_add_url(), data=post_data) self.assertRedirects(response, self.get_add_url()) post_data.pop("_addanother") def test_add_view_without_preserved_filters(self): response = self.client.get(self.get_add_url(add_preserved_filters=False)) # The action attribute is omitted. self.assertContains(response, '<form method="post" id="user_form" novalidate>') def test_delete_view(self): # Test redirect on "Delete". response = self.client.post(self.get_delete_url(), {"post": "yes"}) self.assertRedirects(response, self.get_changelist_url()) def test_url_prefix(self): context = { "preserved_filters": self.get_preserved_filters_querystring(), "opts": User._meta, } prefixes = ("", "/prefix/", "/後台/") for prefix in prefixes: with self.subTest(prefix=prefix), override_script_prefix(prefix): url = reverse( "admin:auth_user_changelist", current_app=self.admin_site.name ) self.assertURLEqual( self.get_changelist_url(), add_preserved_filters(context, url), ) class NamespacedAdminKeepChangeListFiltersTests(AdminKeepChangeListFiltersTests): admin_site = site2 @override_settings(ROOT_URLCONF="admin_views.urls") class TestLabelVisibility(TestCase): """#11277 -Labels of hidden fields in admin were not hidden.""" @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_all_fields_visible(self): response = self.client.get(reverse("admin:admin_views_emptymodelvisible_add")) self.assert_fieldline_visible(response) self.assert_field_visible(response, "first") self.assert_field_visible(response, "second") def test_all_fields_hidden(self): response = self.client.get(reverse("admin:admin_views_emptymodelhidden_add")) self.assert_fieldline_hidden(response) self.assert_field_hidden(response, "first") self.assert_field_hidden(response, "second") def test_mixin(self): response = self.client.get(reverse("admin:admin_views_emptymodelmixin_add")) self.assert_fieldline_visible(response) self.assert_field_hidden(response, "first") self.assert_field_visible(response, "second") def assert_field_visible(self, response, field_name): self.assertContains( response, f'<div class="flex-container fieldBox field-{field_name}">' ) def assert_field_hidden(self, response, field_name): self.assertContains( response, f'<div class="flex-container fieldBox field-{field_name} hidden">' ) def assert_fieldline_visible(self, response): self.assertContains(response, '<div class="form-row field-first field-second">') def assert_fieldline_hidden(self, response): self.assertContains(response, '<div class="form-row hidden') @override_settings(ROOT_URLCONF="admin_views.urls") class AdminViewOnSiteTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = State.objects.create(name="New York") cls.s2 = State.objects.create(name="Illinois") cls.s3 = State.objects.create(name="California") cls.c1 = City.objects.create(state=cls.s1, name="New York") cls.c2 = City.objects.create(state=cls.s2, name="Chicago") cls.c3 = City.objects.create(state=cls.s3, name="San Francisco") cls.r1 = Restaurant.objects.create(city=cls.c1, name="Italian Pizza") cls.r2 = Restaurant.objects.create(city=cls.c1, name="Boulevard") cls.r3 = Restaurant.objects.create(city=cls.c2, name="Chinese Dinner") cls.r4 = Restaurant.objects.create(city=cls.c2, name="Angels") cls.r5 = Restaurant.objects.create(city=cls.c2, name="Take Away") cls.r6 = Restaurant.objects.create(city=cls.c3, name="The Unknown Restaurant") cls.w1 = Worker.objects.create(work_at=cls.r1, name="Mario", surname="Rossi") cls.w2 = Worker.objects.create( work_at=cls.r1, name="Antonio", surname="Bianchi" ) cls.w3 = Worker.objects.create(work_at=cls.r1, name="John", surname="Doe") def setUp(self): self.client.force_login(self.superuser) def test_add_view_form_and_formsets_run_validation(self): """ Issue #20522 Verifying that if the parent form fails validation, the inlines also run validation even if validation is contingent on parent form data. Also, assertFormError() and assertFormSetError() is usable for admin forms and formsets. """ # The form validation should fail because 'some_required_info' is # not included on the parent form, and the family_name of the parent # does not match that of the child post_data = { "family_name": "Test1", "dependentchild_set-TOTAL_FORMS": "1", "dependentchild_set-INITIAL_FORMS": "0", "dependentchild_set-MAX_NUM_FORMS": "1", "dependentchild_set-0-id": "", "dependentchild_set-0-parent": "", "dependentchild_set-0-family_name": "Test2", } response = self.client.post( reverse("admin:admin_views_parentwithdependentchildren_add"), post_data ) self.assertFormError( response.context["adminform"], "some_required_info", ["This field is required."], ) self.assertFormError(response.context["adminform"], None, []) self.assertFormSetError( response.context["inline_admin_formset"], 0, None, [ "Children must share a family name with their parents in this " "contrived test case" ], ) self.assertFormSetError( response.context["inline_admin_formset"], None, None, [] ) def test_change_view_form_and_formsets_run_validation(self): """ Issue #20522 Verifying that if the parent form fails validation, the inlines also run validation even if validation is contingent on parent form data """ pwdc = ParentWithDependentChildren.objects.create( some_required_info=6, family_name="Test1" ) # The form validation should fail because 'some_required_info' is # not included on the parent form, and the family_name of the parent # does not match that of the child post_data = { "family_name": "Test2", "dependentchild_set-TOTAL_FORMS": "1", "dependentchild_set-INITIAL_FORMS": "0", "dependentchild_set-MAX_NUM_FORMS": "1", "dependentchild_set-0-id": "", "dependentchild_set-0-parent": str(pwdc.id), "dependentchild_set-0-family_name": "Test1", } response = self.client.post( reverse( "admin:admin_views_parentwithdependentchildren_change", args=(pwdc.id,) ), post_data, ) self.assertFormError( response.context["adminform"], "some_required_info", ["This field is required."], ) self.assertFormSetError( response.context["inline_admin_formset"], 0, None, [ "Children must share a family name with their parents in this " "contrived test case" ], ) def test_check(self): "The view_on_site value is either a boolean or a callable" try: admin = CityAdmin(City, AdminSite()) CityAdmin.view_on_site = True self.assertEqual(admin.check(), []) CityAdmin.view_on_site = False self.assertEqual(admin.check(), []) CityAdmin.view_on_site = lambda obj: obj.get_absolute_url() self.assertEqual(admin.check(), []) CityAdmin.view_on_site = [] self.assertEqual( admin.check(), [ Error( "The value of 'view_on_site' must be a callable or a boolean " "value.", obj=CityAdmin, id="admin.E025", ), ], ) finally: # Restore the original values for the benefit of other tests. CityAdmin.view_on_site = True def test_false(self): "The 'View on site' button is not displayed if view_on_site is False" response = self.client.get( reverse("admin:admin_views_restaurant_change", args=(self.r1.pk,)) ) content_type_pk = ContentType.objects.get_for_model(Restaurant).pk self.assertNotContains( response, reverse("admin:view_on_site", args=(content_type_pk, 1)) ) def test_true(self): "The default behavior is followed if view_on_site is True" response = self.client.get( reverse("admin:admin_views_city_change", args=(self.c1.pk,)) ) content_type_pk = ContentType.objects.get_for_model(City).pk self.assertContains( response, reverse("admin:view_on_site", args=(content_type_pk, self.c1.pk)) ) def test_callable(self): "The right link is displayed if view_on_site is a callable" response = self.client.get( reverse("admin:admin_views_worker_change", args=(self.w1.pk,)) ) self.assertContains( response, '"/worker/%s/%s/"' % (self.w1.surname, self.w1.name) ) def test_missing_get_absolute_url(self): "None is returned if model doesn't have get_absolute_url" model_admin = ModelAdmin(Worker, None) self.assertIsNone(model_admin.get_view_on_site_url(Worker())) def test_custom_admin_site(self): model_admin = ModelAdmin(City, customadmin.site) content_type_pk = ContentType.objects.get_for_model(City).pk redirect_url = model_admin.get_view_on_site_url(self.c1) self.assertEqual( redirect_url, reverse( f"{customadmin.site.name}:view_on_site", kwargs={ "content_type_id": content_type_pk, "object_id": self.c1.pk, }, ), ) @override_settings(ROOT_URLCONF="admin_views.urls") class InlineAdminViewOnSiteTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) cls.s1 = State.objects.create(name="New York") cls.s2 = State.objects.create(name="Illinois") cls.s3 = State.objects.create(name="California") cls.c1 = City.objects.create(state=cls.s1, name="New York") cls.c2 = City.objects.create(state=cls.s2, name="Chicago") cls.c3 = City.objects.create(state=cls.s3, name="San Francisco") cls.r1 = Restaurant.objects.create(city=cls.c1, name="Italian Pizza") cls.r2 = Restaurant.objects.create(city=cls.c1, name="Boulevard") cls.r3 = Restaurant.objects.create(city=cls.c2, name="Chinese Dinner") cls.r4 = Restaurant.objects.create(city=cls.c2, name="Angels") cls.r5 = Restaurant.objects.create(city=cls.c2, name="Take Away") cls.r6 = Restaurant.objects.create(city=cls.c3, name="The Unknown Restaurant") cls.w1 = Worker.objects.create(work_at=cls.r1, name="Mario", surname="Rossi") cls.w2 = Worker.objects.create( work_at=cls.r1, name="Antonio", surname="Bianchi" ) cls.w3 = Worker.objects.create(work_at=cls.r1, name="John", surname="Doe") def setUp(self): self.client.force_login(self.superuser) def test_false(self): "The 'View on site' button is not displayed if view_on_site is False" response = self.client.get( reverse("admin:admin_views_state_change", args=(self.s1.pk,)) ) content_type_pk = ContentType.objects.get_for_model(City).pk self.assertNotContains( response, reverse("admin:view_on_site", args=(content_type_pk, self.c1.pk)) ) def test_true(self): "The 'View on site' button is displayed if view_on_site is True" response = self.client.get( reverse("admin:admin_views_city_change", args=(self.c1.pk,)) ) content_type_pk = ContentType.objects.get_for_model(Restaurant).pk self.assertContains( response, reverse("admin:view_on_site", args=(content_type_pk, self.r1.pk)) ) def test_callable(self): "The right link is displayed if view_on_site is a callable" response = self.client.get( reverse("admin:admin_views_restaurant_change", args=(self.r1.pk,)) ) self.assertContains( response, '"/worker_inline/%s/%s/"' % (self.w1.surname, self.w1.name) ) @override_settings(ROOT_URLCONF="admin_views.urls") class GetFormsetsWithInlinesArgumentTest(TestCase): """ #23934 - When adding a new model instance in the admin, the 'obj' argument of get_formsets_with_inlines() should be None. When changing, it should be equal to the existing model instance. The GetFormsetsArgumentCheckingAdmin ModelAdmin throws an exception if obj is not None during add_view or obj is None during change_view. """ @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def setUp(self): self.client.force_login(self.superuser) def test_explicitly_provided_pk(self): post_data = {"name": "1"} response = self.client.post( reverse("admin:admin_views_explicitlyprovidedpk_add"), post_data ) self.assertEqual(response.status_code, 302) post_data = {"name": "2"} response = self.client.post( reverse("admin:admin_views_explicitlyprovidedpk_change", args=(1,)), post_data, ) self.assertEqual(response.status_code, 302) def test_implicitly_generated_pk(self): post_data = {"name": "1"} response = self.client.post( reverse("admin:admin_views_implicitlygeneratedpk_add"), post_data ) self.assertEqual(response.status_code, 302) post_data = {"name": "2"} response = self.client.post( reverse("admin:admin_views_implicitlygeneratedpk_change", args=(1,)), post_data, ) self.assertEqual(response.status_code, 302) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminSiteFinalCatchAllPatternTests(TestCase): """ Verifies the behaviour of the admin catch-all view. * Anonynous/non-staff users are redirected to login for all URLs, whether otherwise valid or not. * APPEND_SLASH is applied for staff if needed. * Otherwise Http404. * Catch-all view disabled via AdminSite.final_catch_all_view. """ @classmethod def setUpTestData(cls): cls.staff_user = User.objects.create_user( username="staff", password="secret", email="[email protected]", is_staff=True, ) cls.non_staff_user = User.objects.create_user( username="user", password="secret", email="[email protected]", is_staff=False, ) def test_unknown_url_redirects_login_if_not_authenticated(self): unknown_url = "/test_admin/admin/unknown/" response = self.client.get(unknown_url) self.assertRedirects( response, "%s?next=%s" % (reverse("admin:login"), unknown_url) ) def test_unknown_url_404_if_authenticated(self): self.client.force_login(self.staff_user) unknown_url = "/test_admin/admin/unknown/" response = self.client.get(unknown_url) self.assertEqual(response.status_code, 404) def test_known_url_redirects_login_if_not_authenticated(self): known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url) self.assertRedirects( response, "%s?next=%s" % (reverse("admin:login"), known_url) ) def test_known_url_missing_slash_redirects_login_if_not_authenticated(self): known_url = reverse("admin:admin_views_article_changelist")[:-1] response = self.client.get(known_url) # Redirects with the next URL also missing the slash. self.assertRedirects( response, "%s?next=%s" % (reverse("admin:login"), known_url) ) def test_non_admin_url_shares_url_prefix(self): url = reverse("non_admin")[:-1] response = self.client.get(url) # Redirects with the next URL also missing the slash. self.assertRedirects(response, "%s?next=%s" % (reverse("admin:login"), url)) def test_url_without_trailing_slash_if_not_authenticated(self): url = reverse("admin:article_extra_json") response = self.client.get(url) self.assertRedirects(response, "%s?next=%s" % (reverse("admin:login"), url)) def test_unkown_url_without_trailing_slash_if_not_authenticated(self): url = reverse("admin:article_extra_json")[:-1] response = self.client.get(url) self.assertRedirects(response, "%s?next=%s" % (reverse("admin:login"), url)) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_unknown_url(self): self.client.force_login(self.staff_user) unknown_url = "/test_admin/admin/unknown/" response = self.client.get(unknown_url[:-1]) self.assertEqual(response.status_code, 404) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true(self): self.client.force_login(self.staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertRedirects( response, known_url, status_code=301, target_status_code=403 ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_query_string(self): self.client.force_login(self.staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get("%s?id=1" % known_url[:-1]) self.assertRedirects( response, f"{known_url}?id=1", status_code=301, fetch_redirect_response=False, ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_script_name(self): self.client.force_login(self.staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url[:-1], SCRIPT_NAME="/prefix/") self.assertRedirects( response, "/prefix" + known_url, status_code=301, fetch_redirect_response=False, ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_script_name_query_string(self): self.client.force_login(self.staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get("%s?id=1" % known_url[:-1], SCRIPT_NAME="/prefix/") self.assertRedirects( response, f"/prefix{known_url}?id=1", status_code=301, fetch_redirect_response=False, ) @override_settings(APPEND_SLASH=True, FORCE_SCRIPT_NAME="/prefix/") def test_missing_slash_append_slash_true_force_script_name(self): self.client.force_login(self.staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertRedirects( response, "/prefix" + known_url, status_code=301, fetch_redirect_response=False, ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_non_staff_user(self): self.client.force_login(self.non_staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertRedirects( response, "/test_admin/admin/login/?next=/test_admin/admin/admin_views/article", ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_non_staff_user_query_string(self): self.client.force_login(self.non_staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get("%s?id=1" % known_url[:-1]) self.assertRedirects( response, "/test_admin/admin/login/?next=/test_admin/admin/admin_views/article" "%3Fid%3D1", ) @override_settings(APPEND_SLASH=False) def test_missing_slash_append_slash_false(self): self.client.force_login(self.staff_user) known_url = reverse("admin:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertEqual(response.status_code, 404) @override_settings(APPEND_SLASH=True) def test_single_model_no_append_slash(self): self.client.force_login(self.staff_user) known_url = reverse("admin9:admin_views_actor_changelist") response = self.client.get(known_url[:-1]) self.assertEqual(response.status_code, 404) # Same tests above with final_catch_all_view=False. def test_unknown_url_404_if_not_authenticated_without_final_catch_all_view(self): unknown_url = "/test_admin/admin10/unknown/" response = self.client.get(unknown_url) self.assertEqual(response.status_code, 404) def test_unknown_url_404_if_authenticated_without_final_catch_all_view(self): self.client.force_login(self.staff_user) unknown_url = "/test_admin/admin10/unknown/" response = self.client.get(unknown_url) self.assertEqual(response.status_code, 404) def test_known_url_redirects_login_if_not_auth_without_final_catch_all_view( self, ): known_url = reverse("admin10:admin_views_article_changelist") response = self.client.get(known_url) self.assertRedirects( response, "%s?next=%s" % (reverse("admin10:login"), known_url) ) def test_known_url_missing_slash_redirects_with_slash_if_not_auth_no_catch_all_view( self, ): known_url = reverse("admin10:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertRedirects( response, known_url, status_code=301, fetch_redirect_response=False ) def test_non_admin_url_shares_url_prefix_without_final_catch_all_view(self): url = reverse("non_admin10") response = self.client.get(url[:-1]) self.assertRedirects(response, url, status_code=301) def test_url_no_trailing_slash_if_not_auth_without_final_catch_all_view( self, ): url = reverse("admin10:article_extra_json") response = self.client.get(url) self.assertRedirects(response, "%s?next=%s" % (reverse("admin10:login"), url)) def test_unknown_url_no_trailing_slash_if_not_auth_without_final_catch_all_view( self, ): url = reverse("admin10:article_extra_json")[:-1] response = self.client.get(url) # Matches test_admin/admin10/admin_views/article/<path:object_id>/ self.assertRedirects( response, url + "/", status_code=301, fetch_redirect_response=False ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_unknown_url_without_final_catch_all_view( self, ): self.client.force_login(self.staff_user) unknown_url = "/test_admin/admin10/unknown/" response = self.client.get(unknown_url[:-1]) self.assertEqual(response.status_code, 404) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_without_final_catch_all_view(self): self.client.force_login(self.staff_user) known_url = reverse("admin10:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertRedirects( response, known_url, status_code=301, target_status_code=403 ) @override_settings(APPEND_SLASH=True) def test_missing_slash_append_slash_true_query_without_final_catch_all_view(self): self.client.force_login(self.staff_user) known_url = reverse("admin10:admin_views_article_changelist") response = self.client.get("%s?id=1" % known_url[:-1]) self.assertRedirects( response, f"{known_url}?id=1", status_code=301, fetch_redirect_response=False, ) @override_settings(APPEND_SLASH=False) def test_missing_slash_append_slash_false_without_final_catch_all_view(self): self.client.force_login(self.staff_user) known_url = reverse("admin10:admin_views_article_changelist") response = self.client.get(known_url[:-1]) self.assertEqual(response.status_code, 404) # Outside admin. def test_non_admin_url_404_if_not_authenticated(self): unknown_url = "/unknown/" response = self.client.get(unknown_url) # Does not redirect to the admin login. self.assertEqual(response.status_code, 404)
f5dfac7d83cd54cc665bddb07292f3b88bd2654e1e6957edce0752d6c80c8c5e
import datetime import sys import unittest from django.contrib.admin import ( AllValuesFieldListFilter, BooleanFieldListFilter, EmptyFieldListFilter, FieldListFilter, ModelAdmin, RelatedOnlyFieldListFilter, SimpleListFilter, site, ) from django.contrib.admin.filters import FacetsMixin from django.contrib.admin.options import IncorrectLookupParameters, ShowFacets from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.core.exceptions import ImproperlyConfigured from django.db import connection from django.test import RequestFactory, SimpleTestCase, TestCase, override_settings from .models import Book, Bookmark, Department, Employee, ImprovedBook, TaggedItem def select_by(dictlist, key, value): return [x for x in dictlist if x[key] == value][0] class DecadeListFilter(SimpleListFilter): def lookups(self, request, model_admin): return ( ("the 80s", "the 1980's"), ("the 90s", "the 1990's"), ("the 00s", "the 2000's"), ("other", "other decades"), ) def queryset(self, request, queryset): decade = self.value() if decade == "the 80s": return queryset.filter(year__gte=1980, year__lte=1989) if decade == "the 90s": return queryset.filter(year__gte=1990, year__lte=1999) if decade == "the 00s": return queryset.filter(year__gte=2000, year__lte=2009) class NotNinetiesListFilter(SimpleListFilter): title = "Not nineties books" parameter_name = "book_year" def lookups(self, request, model_admin): return (("the 90s", "the 1990's"),) def queryset(self, request, queryset): if self.value() == "the 90s": return queryset.filter(year__gte=1990, year__lte=1999) else: return queryset.exclude(year__gte=1990, year__lte=1999) class DecadeListFilterWithTitleAndParameter(DecadeListFilter): title = "publication decade" parameter_name = "publication-decade" class DecadeListFilterWithoutTitle(DecadeListFilter): parameter_name = "publication-decade" class DecadeListFilterWithoutParameter(DecadeListFilter): title = "publication decade" class DecadeListFilterWithNoneReturningLookups(DecadeListFilterWithTitleAndParameter): def lookups(self, request, model_admin): pass class DecadeListFilterWithFailingQueryset(DecadeListFilterWithTitleAndParameter): def queryset(self, request, queryset): raise 1 / 0 class DecadeListFilterWithQuerysetBasedLookups(DecadeListFilterWithTitleAndParameter): def lookups(self, request, model_admin): qs = model_admin.get_queryset(request) if qs.filter(year__gte=1980, year__lte=1989).exists(): yield ("the 80s", "the 1980's") if qs.filter(year__gte=1990, year__lte=1999).exists(): yield ("the 90s", "the 1990's") if qs.filter(year__gte=2000, year__lte=2009).exists(): yield ("the 00s", "the 2000's") class DecadeListFilterParameterEndsWith__In(DecadeListFilter): title = "publication decade" parameter_name = "decade__in" # Ends with '__in" class DecadeListFilterParameterEndsWith__Isnull(DecadeListFilter): title = "publication decade" parameter_name = "decade__isnull" # Ends with '__isnull" class DepartmentListFilterLookupWithNonStringValue(SimpleListFilter): title = "department" parameter_name = "department" def lookups(self, request, model_admin): return sorted( { ( employee.department.id, # Intentionally not a string (Refs #19318) employee.department.code, ) for employee in model_admin.get_queryset(request) } ) def queryset(self, request, queryset): if self.value(): return queryset.filter(department__id=self.value()) class DepartmentListFilterLookupWithUnderscoredParameter( DepartmentListFilterLookupWithNonStringValue ): parameter_name = "department__whatever" class DepartmentListFilterLookupWithDynamicValue(DecadeListFilterWithTitleAndParameter): def lookups(self, request, model_admin): if self.value() == "the 80s": return (("the 90s", "the 1990's"),) elif self.value() == "the 90s": return (("the 80s", "the 1980's"),) else: return ( ("the 80s", "the 1980's"), ("the 90s", "the 1990's"), ) class EmployeeNameCustomDividerFilter(FieldListFilter): list_separator = "|" def __init__(self, field, request, params, model, model_admin, field_path): self.lookup_kwarg = "%s__in" % field_path super().__init__(field, request, params, model, model_admin, field_path) def expected_parameters(self): return [self.lookup_kwarg] class CustomUserAdmin(UserAdmin): list_filter = ("books_authored", "books_contributed") class BookAdmin(ModelAdmin): list_filter = ( "year", "author", "contributors", "is_best_seller", "date_registered", "no", "availability", ) ordering = ("-id",) class BookAdminWithTupleBooleanFilter(BookAdmin): list_filter = ( "year", "author", "contributors", ("is_best_seller", BooleanFieldListFilter), "date_registered", "no", ("availability", BooleanFieldListFilter), ) class BookAdminWithUnderscoreLookupAndTuple(BookAdmin): list_filter = ( "year", ("author__email", AllValuesFieldListFilter), "contributors", "is_best_seller", "date_registered", "no", ) class BookAdminWithCustomQueryset(ModelAdmin): def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) list_filter = ("year",) def get_queryset(self, request): return super().get_queryset(request).filter(author=self.user) class BookAdminRelatedOnlyFilter(ModelAdmin): list_filter = ( "year", "is_best_seller", "date_registered", "no", ("author", RelatedOnlyFieldListFilter), ("contributors", RelatedOnlyFieldListFilter), ("employee__department", RelatedOnlyFieldListFilter), ) ordering = ("-id",) class DecadeFilterBookAdmin(ModelAdmin): empty_value_display = "???" list_filter = ( "author", DecadeListFilterWithTitleAndParameter, "is_best_seller", "category", "date_registered", ("author__email", AllValuesFieldListFilter), ("contributors", RelatedOnlyFieldListFilter), ("category", EmptyFieldListFilter), ) ordering = ("-id",) class DecadeFilterBookAdminWithAlwaysFacets(DecadeFilterBookAdmin): show_facets = ShowFacets.ALWAYS class DecadeFilterBookAdminDisallowFacets(DecadeFilterBookAdmin): show_facets = ShowFacets.NEVER class NotNinetiesListFilterAdmin(ModelAdmin): list_filter = (NotNinetiesListFilter,) class DecadeFilterBookAdminWithoutTitle(ModelAdmin): list_filter = (DecadeListFilterWithoutTitle,) class DecadeFilterBookAdminWithoutParameter(ModelAdmin): list_filter = (DecadeListFilterWithoutParameter,) class DecadeFilterBookAdminWithNoneReturningLookups(ModelAdmin): list_filter = (DecadeListFilterWithNoneReturningLookups,) class DecadeFilterBookAdminWithFailingQueryset(ModelAdmin): list_filter = (DecadeListFilterWithFailingQueryset,) class DecadeFilterBookAdminWithQuerysetBasedLookups(ModelAdmin): list_filter = (DecadeListFilterWithQuerysetBasedLookups,) class DecadeFilterBookAdminParameterEndsWith__In(ModelAdmin): list_filter = (DecadeListFilterParameterEndsWith__In,) class DecadeFilterBookAdminParameterEndsWith__Isnull(ModelAdmin): list_filter = (DecadeListFilterParameterEndsWith__Isnull,) class EmployeeAdmin(ModelAdmin): list_display = ["name", "department"] list_filter = ["department"] class EmployeeCustomDividerFilterAdmin(EmployeeAdmin): list_filter = [ ("name", EmployeeNameCustomDividerFilter), ] class DepartmentFilterEmployeeAdmin(EmployeeAdmin): list_filter = [DepartmentListFilterLookupWithNonStringValue] class DepartmentFilterUnderscoredEmployeeAdmin(EmployeeAdmin): list_filter = [DepartmentListFilterLookupWithUnderscoredParameter] class DepartmentFilterDynamicValueBookAdmin(EmployeeAdmin): list_filter = [DepartmentListFilterLookupWithDynamicValue] class BookmarkAdminGenericRelation(ModelAdmin): list_filter = ["tags__tag"] class BookAdminWithEmptyFieldListFilter(ModelAdmin): list_filter = [ ("author", EmptyFieldListFilter), ("title", EmptyFieldListFilter), ("improvedbook", EmptyFieldListFilter), ] class DepartmentAdminWithEmptyFieldListFilter(ModelAdmin): list_filter = [ ("description", EmptyFieldListFilter), ("employee", EmptyFieldListFilter), ] class ListFiltersTests(TestCase): request_factory = RequestFactory() @classmethod def setUpTestData(cls): cls.today = datetime.date.today() cls.tomorrow = cls.today + datetime.timedelta(days=1) cls.one_week_ago = cls.today - datetime.timedelta(days=7) if cls.today.month == 12: cls.next_month = cls.today.replace(year=cls.today.year + 1, month=1, day=1) else: cls.next_month = cls.today.replace(month=cls.today.month + 1, day=1) cls.next_year = cls.today.replace(year=cls.today.year + 1, month=1, day=1) # Users cls.alfred = User.objects.create_superuser( "alfred", "[email protected]", "password" ) cls.bob = User.objects.create_user("bob", "[email protected]") cls.lisa = User.objects.create_user("lisa", "[email protected]") # Books cls.djangonaut_book = Book.objects.create( title="Djangonaut: an art of living", year=2009, author=cls.alfred, is_best_seller=True, date_registered=cls.today, availability=True, category="non-fiction", ) cls.bio_book = Book.objects.create( title="Django: a biography", year=1999, author=cls.alfred, is_best_seller=False, no=207, availability=False, category="fiction", ) cls.django_book = Book.objects.create( title="The Django Book", year=None, author=cls.bob, is_best_seller=None, date_registered=cls.today, no=103, availability=True, ) cls.guitar_book = Book.objects.create( title="Guitar for dummies", year=2002, is_best_seller=True, date_registered=cls.one_week_ago, availability=None, category="", ) cls.guitar_book.contributors.set([cls.bob, cls.lisa]) # Departments cls.dev = Department.objects.create(code="DEV", description="Development") cls.design = Department.objects.create(code="DSN", description="Design") # Employees cls.john = Employee.objects.create(name="John Blue", department=cls.dev) cls.jack = Employee.objects.create(name="Jack Red", department=cls.design) def assertChoicesDisplay(self, choices, expected_displays): for choice, expected_display in zip(choices, expected_displays, strict=True): self.assertEqual(choice["display"], expected_display) def test_choicesfieldlistfilter_has_none_choice(self): """ The last choice is for the None value. """ class BookmarkChoicesAdmin(ModelAdmin): list_display = ["none_or_null"] list_filter = ["none_or_null"] modeladmin = BookmarkChoicesAdmin(Bookmark, site) request = self.request_factory.get("/", {}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) filterspec = changelist.get_filters(request)[0][0] choices = list(filterspec.choices(changelist)) self.assertEqual(choices[-1]["display"], "None") self.assertEqual(choices[-1]["query_string"], "?none_or_null__isnull=True") def test_datefieldlistfilter(self): modeladmin = BookAdmin(Book, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist(request) request = self.request_factory.get( "/", {"date_registered__gte": self.today, "date_registered__lt": self.tomorrow}, ) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.django_book, self.djangonaut_book]) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][4] self.assertEqual(filterspec.title, "date registered") choice = select_by(filterspec.choices(changelist), "display", "Today") self.assertIs(choice["selected"], True) self.assertEqual( choice["query_string"], "?date_registered__gte=%s&date_registered__lt=%s" % ( self.today, self.tomorrow, ), ) request = self.request_factory.get( "/", { "date_registered__gte": self.today.replace(day=1), "date_registered__lt": self.next_month, }, ) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) if (self.today.year, self.today.month) == ( self.one_week_ago.year, self.one_week_ago.month, ): # In case one week ago is in the same month. self.assertEqual( list(queryset), [self.guitar_book, self.django_book, self.djangonaut_book], ) else: self.assertEqual(list(queryset), [self.django_book, self.djangonaut_book]) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][4] self.assertEqual(filterspec.title, "date registered") choice = select_by(filterspec.choices(changelist), "display", "This month") self.assertIs(choice["selected"], True) self.assertEqual( choice["query_string"], "?date_registered__gte=%s&date_registered__lt=%s" % ( self.today.replace(day=1), self.next_month, ), ) request = self.request_factory.get( "/", { "date_registered__gte": self.today.replace(month=1, day=1), "date_registered__lt": self.next_year, }, ) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) if self.today.year == self.one_week_ago.year: # In case one week ago is in the same year. self.assertEqual( list(queryset), [self.guitar_book, self.django_book, self.djangonaut_book], ) else: self.assertEqual(list(queryset), [self.django_book, self.djangonaut_book]) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][4] self.assertEqual(filterspec.title, "date registered") choice = select_by(filterspec.choices(changelist), "display", "This year") self.assertIs(choice["selected"], True) self.assertEqual( choice["query_string"], "?date_registered__gte=%s&date_registered__lt=%s" % ( self.today.replace(month=1, day=1), self.next_year, ), ) request = self.request_factory.get( "/", { "date_registered__gte": str(self.one_week_ago), "date_registered__lt": str(self.tomorrow), }, ) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual( list(queryset), [self.guitar_book, self.django_book, self.djangonaut_book] ) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][4] self.assertEqual(filterspec.title, "date registered") choice = select_by(filterspec.choices(changelist), "display", "Past 7 days") self.assertIs(choice["selected"], True) self.assertEqual( choice["query_string"], "?date_registered__gte=%s&date_registered__lt=%s" % ( str(self.one_week_ago), str(self.tomorrow), ), ) # Null/not null queries request = self.request_factory.get("/", {"date_registered__isnull": "True"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(queryset.count(), 1) self.assertEqual(queryset[0], self.bio_book) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][4] self.assertEqual(filterspec.title, "date registered") choice = select_by(filterspec.choices(changelist), "display", "No date") self.assertIs(choice["selected"], True) self.assertEqual(choice["query_string"], "?date_registered__isnull=True") request = self.request_factory.get("/", {"date_registered__isnull": "False"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(queryset.count(), 3) self.assertEqual( list(queryset), [self.guitar_book, self.django_book, self.djangonaut_book] ) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][4] self.assertEqual(filterspec.title, "date registered") choice = select_by(filterspec.choices(changelist), "display", "Has date") self.assertIs(choice["selected"], True) self.assertEqual(choice["query_string"], "?date_registered__isnull=False") @unittest.skipIf( sys.platform == "win32", "Windows doesn't support setting a timezone that differs from the " "system timezone.", ) @override_settings(USE_TZ=True) def test_datefieldlistfilter_with_time_zone_support(self): # Regression for #17830 self.test_datefieldlistfilter() def test_allvaluesfieldlistfilter(self): modeladmin = BookAdmin(Book, site) request = self.request_factory.get("/", {"year__isnull": "True"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.django_book]) # Make sure the last choice is None and is selected filterspec = changelist.get_filters(request)[0][0] self.assertEqual(filterspec.title, "year") choices = list(filterspec.choices(changelist)) self.assertIs(choices[-1]["selected"], True) self.assertEqual(choices[-1]["query_string"], "?year__isnull=True") request = self.request_factory.get("/", {"year": "2002"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][0] self.assertEqual(filterspec.title, "year") choices = list(filterspec.choices(changelist)) self.assertIs(choices[2]["selected"], True) self.assertEqual(choices[2]["query_string"], "?year=2002") def test_allvaluesfieldlistfilter_custom_qs(self): # Make sure that correct filters are returned with custom querysets modeladmin = BookAdminWithCustomQueryset(self.alfred, Book, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) filterspec = changelist.get_filters(request)[0][0] choices = list(filterspec.choices(changelist)) # Should have 'All', 1999 and 2009 options i.e. the subset of years of # books written by alfred (which is the filtering criteria set by # BookAdminWithCustomQueryset.get_queryset()) self.assertEqual(3, len(choices)) self.assertEqual(choices[0]["query_string"], "?") self.assertEqual(choices[1]["query_string"], "?year=1999") self.assertEqual(choices[2]["query_string"], "?year=2009") def test_relatedfieldlistfilter_foreignkey(self): modeladmin = BookAdmin(Book, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure that all users are present in the author's list filter filterspec = changelist.get_filters(request)[0][1] expected = [ (self.alfred.pk, "alfred"), (self.bob.pk, "bob"), (self.lisa.pk, "lisa"), ] self.assertEqual(sorted(filterspec.lookup_choices), sorted(expected)) request = self.request_factory.get("/", {"author__isnull": "True"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.guitar_book]) # Make sure the last choice is None and is selected filterspec = changelist.get_filters(request)[0][1] self.assertEqual(filterspec.title, "Verbose Author") choices = list(filterspec.choices(changelist)) self.assertIs(choices[-1]["selected"], True) self.assertEqual(choices[-1]["query_string"], "?author__isnull=True") request = self.request_factory.get("/", {"author__id__exact": self.alfred.pk}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][1] self.assertEqual(filterspec.title, "Verbose Author") # order of choices depends on User model, which has no order choice = select_by(filterspec.choices(changelist), "display", "alfred") self.assertIs(choice["selected"], True) self.assertEqual( choice["query_string"], "?author__id__exact=%d" % self.alfred.pk ) def test_relatedfieldlistfilter_foreignkey_ordering(self): """RelatedFieldListFilter ordering respects ModelAdmin.ordering.""" class EmployeeAdminWithOrdering(ModelAdmin): ordering = ("name",) class BookAdmin(ModelAdmin): list_filter = ("employee",) site.register(Employee, EmployeeAdminWithOrdering) self.addCleanup(lambda: site.unregister(Employee)) modeladmin = BookAdmin(Book, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) filterspec = changelist.get_filters(request)[0][0] expected = [(self.jack.pk, "Jack Red"), (self.john.pk, "John Blue")] self.assertEqual(filterspec.lookup_choices, expected) def test_relatedfieldlistfilter_foreignkey_ordering_reverse(self): class EmployeeAdminWithOrdering(ModelAdmin): ordering = ("-name",) class BookAdmin(ModelAdmin): list_filter = ("employee",) site.register(Employee, EmployeeAdminWithOrdering) self.addCleanup(lambda: site.unregister(Employee)) modeladmin = BookAdmin(Book, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) filterspec = changelist.get_filters(request)[0][0] expected = [(self.john.pk, "John Blue"), (self.jack.pk, "Jack Red")] self.assertEqual(filterspec.lookup_choices, expected) def test_relatedfieldlistfilter_foreignkey_default_ordering(self): """RelatedFieldListFilter ordering respects Model.ordering.""" class BookAdmin(ModelAdmin): list_filter = ("employee",) self.addCleanup(setattr, Employee._meta, "ordering", Employee._meta.ordering) Employee._meta.ordering = ("name",) modeladmin = BookAdmin(Book, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) filterspec = changelist.get_filters(request)[0][0] expected = [(self.jack.pk, "Jack Red"), (self.john.pk, "John Blue")] self.assertEqual(filterspec.lookup_choices, expected) def test_relatedfieldlistfilter_manytomany(self): modeladmin = BookAdmin(Book, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure that all users are present in the contrib's list filter filterspec = changelist.get_filters(request)[0][2] expected = [ (self.alfred.pk, "alfred"), (self.bob.pk, "bob"), (self.lisa.pk, "lisa"), ] self.assertEqual(sorted(filterspec.lookup_choices), sorted(expected)) request = self.request_factory.get("/", {"contributors__isnull": "True"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual( list(queryset), [self.django_book, self.bio_book, self.djangonaut_book] ) # Make sure the last choice is None and is selected filterspec = changelist.get_filters(request)[0][2] self.assertEqual(filterspec.title, "Verbose Contributors") choices = list(filterspec.choices(changelist)) self.assertIs(choices[-1]["selected"], True) self.assertEqual(choices[-1]["query_string"], "?contributors__isnull=True") request = self.request_factory.get( "/", {"contributors__id__exact": self.bob.pk} ) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][2] self.assertEqual(filterspec.title, "Verbose Contributors") choice = select_by(filterspec.choices(changelist), "display", "bob") self.assertIs(choice["selected"], True) self.assertEqual( choice["query_string"], "?contributors__id__exact=%d" % self.bob.pk ) def test_relatedfieldlistfilter_reverse_relationships(self): modeladmin = CustomUserAdmin(User, site) # FK relationship ----- request = self.request_factory.get("/", {"books_authored__isnull": "True"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.lisa]) # Make sure the last choice is None and is selected filterspec = changelist.get_filters(request)[0][0] self.assertEqual(filterspec.title, "book") choices = list(filterspec.choices(changelist)) self.assertIs(choices[-1]["selected"], True) self.assertEqual(choices[-1]["query_string"], "?books_authored__isnull=True") request = self.request_factory.get( "/", {"books_authored__id__exact": self.bio_book.pk} ) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][0] self.assertEqual(filterspec.title, "book") choice = select_by( filterspec.choices(changelist), "display", self.bio_book.title ) self.assertIs(choice["selected"], True) self.assertEqual( choice["query_string"], "?books_authored__id__exact=%d" % self.bio_book.pk ) # M2M relationship ----- request = self.request_factory.get("/", {"books_contributed__isnull": "True"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.alfred]) # Make sure the last choice is None and is selected filterspec = changelist.get_filters(request)[0][1] self.assertEqual(filterspec.title, "book") choices = list(filterspec.choices(changelist)) self.assertIs(choices[-1]["selected"], True) self.assertEqual(choices[-1]["query_string"], "?books_contributed__isnull=True") request = self.request_factory.get( "/", {"books_contributed__id__exact": self.django_book.pk} ) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][1] self.assertEqual(filterspec.title, "book") choice = select_by( filterspec.choices(changelist), "display", self.django_book.title ) self.assertIs(choice["selected"], True) self.assertEqual( choice["query_string"], "?books_contributed__id__exact=%d" % self.django_book.pk, ) # With one book, the list filter should appear because there is also a # (None) option. Book.objects.exclude(pk=self.djangonaut_book.pk).delete() filterspec = changelist.get_filters(request)[0] self.assertEqual(len(filterspec), 2) # With no books remaining, no list filters should appear. Book.objects.all().delete() filterspec = changelist.get_filters(request)[0] self.assertEqual(len(filterspec), 0) def test_relatedfieldlistfilter_reverse_relationships_default_ordering(self): self.addCleanup(setattr, Book._meta, "ordering", Book._meta.ordering) Book._meta.ordering = ("title",) modeladmin = CustomUserAdmin(User, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) filterspec = changelist.get_filters(request)[0][0] expected = [ (self.bio_book.pk, "Django: a biography"), (self.djangonaut_book.pk, "Djangonaut: an art of living"), (self.guitar_book.pk, "Guitar for dummies"), (self.django_book.pk, "The Django Book"), ] self.assertEqual(filterspec.lookup_choices, expected) def test_relatedonlyfieldlistfilter_foreignkey(self): modeladmin = BookAdminRelatedOnlyFilter(Book, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure that only actual authors are present in author's list filter filterspec = changelist.get_filters(request)[0][4] expected = [(self.alfred.pk, "alfred"), (self.bob.pk, "bob")] self.assertEqual(sorted(filterspec.lookup_choices), sorted(expected)) def test_relatedonlyfieldlistfilter_foreignkey_reverse_relationships(self): class EmployeeAdminReverseRelationship(ModelAdmin): list_filter = (("book", RelatedOnlyFieldListFilter),) self.djangonaut_book.employee = self.john self.djangonaut_book.save() self.django_book.employee = self.jack self.django_book.save() modeladmin = EmployeeAdminReverseRelationship(Employee, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) filterspec = changelist.get_filters(request)[0][0] self.assertCountEqual( filterspec.lookup_choices, [ (self.djangonaut_book.pk, "Djangonaut: an art of living"), (self.django_book.pk, "The Django Book"), ], ) def test_relatedonlyfieldlistfilter_manytomany_reverse_relationships(self): class UserAdminReverseRelationship(ModelAdmin): list_filter = (("books_contributed", RelatedOnlyFieldListFilter),) modeladmin = UserAdminReverseRelationship(User, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) filterspec = changelist.get_filters(request)[0][0] self.assertEqual( filterspec.lookup_choices, [(self.guitar_book.pk, "Guitar for dummies")], ) def test_relatedonlyfieldlistfilter_foreignkey_ordering(self): """RelatedOnlyFieldListFilter ordering respects ModelAdmin.ordering.""" class EmployeeAdminWithOrdering(ModelAdmin): ordering = ("name",) class BookAdmin(ModelAdmin): list_filter = (("employee", RelatedOnlyFieldListFilter),) albert = Employee.objects.create(name="Albert Green", department=self.dev) self.djangonaut_book.employee = albert self.djangonaut_book.save() self.bio_book.employee = self.jack self.bio_book.save() site.register(Employee, EmployeeAdminWithOrdering) self.addCleanup(lambda: site.unregister(Employee)) modeladmin = BookAdmin(Book, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) filterspec = changelist.get_filters(request)[0][0] expected = [(albert.pk, "Albert Green"), (self.jack.pk, "Jack Red")] self.assertEqual(filterspec.lookup_choices, expected) def test_relatedonlyfieldlistfilter_foreignkey_default_ordering(self): """RelatedOnlyFieldListFilter ordering respects Meta.ordering.""" class BookAdmin(ModelAdmin): list_filter = (("employee", RelatedOnlyFieldListFilter),) albert = Employee.objects.create(name="Albert Green", department=self.dev) self.djangonaut_book.employee = albert self.djangonaut_book.save() self.bio_book.employee = self.jack self.bio_book.save() self.addCleanup(setattr, Employee._meta, "ordering", Employee._meta.ordering) Employee._meta.ordering = ("name",) modeladmin = BookAdmin(Book, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) filterspec = changelist.get_filters(request)[0][0] expected = [(albert.pk, "Albert Green"), (self.jack.pk, "Jack Red")] self.assertEqual(filterspec.lookup_choices, expected) def test_relatedonlyfieldlistfilter_underscorelookup_foreignkey(self): Department.objects.create(code="TEST", description="Testing") self.djangonaut_book.employee = self.john self.djangonaut_book.save() self.bio_book.employee = self.jack self.bio_book.save() modeladmin = BookAdminRelatedOnlyFilter(Book, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Only actual departments should be present in employee__department's # list filter. filterspec = changelist.get_filters(request)[0][6] expected = [ (self.dev.code, str(self.dev)), (self.design.code, str(self.design)), ] self.assertEqual(sorted(filterspec.lookup_choices), sorted(expected)) def test_relatedonlyfieldlistfilter_manytomany(self): modeladmin = BookAdminRelatedOnlyFilter(Book, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure that only actual contributors are present in contrib's list filter filterspec = changelist.get_filters(request)[0][5] expected = [(self.bob.pk, "bob"), (self.lisa.pk, "lisa")] self.assertEqual(sorted(filterspec.lookup_choices), sorted(expected)) def test_listfilter_genericrelation(self): django_bookmark = Bookmark.objects.create(url="https://www.djangoproject.com/") python_bookmark = Bookmark.objects.create(url="https://www.python.org/") kernel_bookmark = Bookmark.objects.create(url="https://www.kernel.org/") TaggedItem.objects.create(content_object=django_bookmark, tag="python") TaggedItem.objects.create(content_object=python_bookmark, tag="python") TaggedItem.objects.create(content_object=kernel_bookmark, tag="linux") modeladmin = BookmarkAdminGenericRelation(Bookmark, site) request = self.request_factory.get("/", {"tags__tag": "python"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) expected = [python_bookmark, django_bookmark] self.assertEqual(list(queryset), expected) def test_booleanfieldlistfilter(self): modeladmin = BookAdmin(Book, site) self.verify_booleanfieldlistfilter(modeladmin) def test_booleanfieldlistfilter_tuple(self): modeladmin = BookAdminWithTupleBooleanFilter(Book, site) self.verify_booleanfieldlistfilter(modeladmin) def verify_booleanfieldlistfilter(self, modeladmin): request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) request = self.request_factory.get("/", {"is_best_seller__exact": 0}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.bio_book]) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][3] self.assertEqual(filterspec.title, "is best seller") choice = select_by(filterspec.choices(changelist), "display", "No") self.assertIs(choice["selected"], True) self.assertEqual(choice["query_string"], "?is_best_seller__exact=0") request = self.request_factory.get("/", {"is_best_seller__exact": 1}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.guitar_book, self.djangonaut_book]) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][3] self.assertEqual(filterspec.title, "is best seller") choice = select_by(filterspec.choices(changelist), "display", "Yes") self.assertIs(choice["selected"], True) self.assertEqual(choice["query_string"], "?is_best_seller__exact=1") request = self.request_factory.get("/", {"is_best_seller__isnull": "True"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.django_book]) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][3] self.assertEqual(filterspec.title, "is best seller") choice = select_by(filterspec.choices(changelist), "display", "Unknown") self.assertIs(choice["selected"], True) self.assertEqual(choice["query_string"], "?is_best_seller__isnull=True") def test_booleanfieldlistfilter_choices(self): modeladmin = BookAdmin(Book, site) self.verify_booleanfieldlistfilter_choices(modeladmin) def test_booleanfieldlistfilter_tuple_choices(self): modeladmin = BookAdminWithTupleBooleanFilter(Book, site) self.verify_booleanfieldlistfilter_choices(modeladmin) def verify_booleanfieldlistfilter_choices(self, modeladmin): # False. request = self.request_factory.get("/", {"availability__exact": 0}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.bio_book]) filterspec = changelist.get_filters(request)[0][6] self.assertEqual(filterspec.title, "availability") choice = select_by(filterspec.choices(changelist), "display", "Paid") self.assertIs(choice["selected"], True) self.assertEqual(choice["query_string"], "?availability__exact=0") # True. request = self.request_factory.get("/", {"availability__exact": 1}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.django_book, self.djangonaut_book]) filterspec = changelist.get_filters(request)[0][6] self.assertEqual(filterspec.title, "availability") choice = select_by(filterspec.choices(changelist), "display", "Free") self.assertIs(choice["selected"], True) self.assertEqual(choice["query_string"], "?availability__exact=1") # None. request = self.request_factory.get("/", {"availability__isnull": "True"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.guitar_book]) filterspec = changelist.get_filters(request)[0][6] self.assertEqual(filterspec.title, "availability") choice = select_by(filterspec.choices(changelist), "display", "Obscure") self.assertIs(choice["selected"], True) self.assertEqual(choice["query_string"], "?availability__isnull=True") # All. request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) self.assertEqual( list(queryset), [self.guitar_book, self.django_book, self.bio_book, self.djangonaut_book], ) filterspec = changelist.get_filters(request)[0][6] self.assertEqual(filterspec.title, "availability") choice = select_by(filterspec.choices(changelist), "display", "All") self.assertIs(choice["selected"], True) self.assertEqual(choice["query_string"], "?") def test_fieldlistfilter_underscorelookup_tuple(self): """ Ensure ('fieldpath', ClassName ) lookups pass lookup_allowed checks when fieldpath contains double underscore in value (#19182). """ modeladmin = BookAdminWithUnderscoreLookupAndTuple(Book, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) request = self.request_factory.get("/", {"author__email": "[email protected]"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.bio_book, self.djangonaut_book]) def test_fieldlistfilter_invalid_lookup_parameters(self): """Filtering by an invalid value.""" modeladmin = BookAdmin(Book, site) request = self.request_factory.get( "/", {"author__id__exact": "StringNotInteger!"} ) request.user = self.alfred with self.assertRaises(IncorrectLookupParameters): modeladmin.get_changelist_instance(request) def test_fieldlistfilter_multiple_invalid_lookup_parameters(self): modeladmin = BookAdmin(Book, site) request = self.request_factory.get( "/", {"author__id__exact": f"{self.alfred.pk},{self.bob.pk}"} ) request.user = self.alfred with self.assertRaises(IncorrectLookupParameters): modeladmin.get_changelist_instance(request) def test_simplelistfilter(self): modeladmin = DecadeFilterBookAdmin(Book, site) # Make sure that the first option is 'All' --------------------------- request = self.request_factory.get("/", {}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), list(Book.objects.order_by("-id"))) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][1] self.assertEqual(filterspec.title, "publication decade") choices = list(filterspec.choices(changelist)) self.assertEqual(choices[0]["display"], "All") self.assertIs(choices[0]["selected"], True) self.assertEqual(choices[0]["query_string"], "?") # Look for books in the 1980s ---------------------------------------- request = self.request_factory.get("/", {"publication-decade": "the 80s"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), []) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][1] self.assertEqual(filterspec.title, "publication decade") choices = list(filterspec.choices(changelist)) self.assertEqual(choices[1]["display"], "the 1980's") self.assertIs(choices[1]["selected"], True) self.assertEqual(choices[1]["query_string"], "?publication-decade=the+80s") # Look for books in the 1990s ---------------------------------------- request = self.request_factory.get("/", {"publication-decade": "the 90s"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.bio_book]) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][1] self.assertEqual(filterspec.title, "publication decade") choices = list(filterspec.choices(changelist)) self.assertEqual(choices[2]["display"], "the 1990's") self.assertIs(choices[2]["selected"], True) self.assertEqual(choices[2]["query_string"], "?publication-decade=the+90s") # Look for books in the 2000s ---------------------------------------- request = self.request_factory.get("/", {"publication-decade": "the 00s"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.guitar_book, self.djangonaut_book]) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][1] self.assertEqual(filterspec.title, "publication decade") choices = list(filterspec.choices(changelist)) self.assertEqual(choices[3]["display"], "the 2000's") self.assertIs(choices[3]["selected"], True) self.assertEqual(choices[3]["query_string"], "?publication-decade=the+00s") # Combine multiple filters ------------------------------------------- request = self.request_factory.get( "/", {"publication-decade": "the 00s", "author__id__exact": self.alfred.pk} ) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.djangonaut_book]) # Make sure the correct choices are selected filterspec = changelist.get_filters(request)[0][1] self.assertEqual(filterspec.title, "publication decade") choices = list(filterspec.choices(changelist)) self.assertEqual(choices[3]["display"], "the 2000's") self.assertIs(choices[3]["selected"], True) self.assertEqual( choices[3]["query_string"], "?author__id__exact=%s&publication-decade=the+00s" % self.alfred.pk, ) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(filterspec.title, "Verbose Author") choice = select_by(filterspec.choices(changelist), "display", "alfred") self.assertIs(choice["selected"], True) self.assertEqual( choice["query_string"], "?author__id__exact=%s&publication-decade=the+00s" % self.alfred.pk, ) def test_listfilter_without_title(self): """ Any filter must define a title. """ modeladmin = DecadeFilterBookAdminWithoutTitle(Book, site) request = self.request_factory.get("/", {}) request.user = self.alfred msg = ( "The list filter 'DecadeListFilterWithoutTitle' does not specify a 'title'." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): modeladmin.get_changelist_instance(request) def test_simplelistfilter_without_parameter(self): """ Any SimpleListFilter must define a parameter_name. """ modeladmin = DecadeFilterBookAdminWithoutParameter(Book, site) request = self.request_factory.get("/", {}) request.user = self.alfred msg = ( "The list filter 'DecadeListFilterWithoutParameter' does not specify a " "'parameter_name'." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): modeladmin.get_changelist_instance(request) def test_simplelistfilter_with_none_returning_lookups(self): """ A SimpleListFilter lookups method can return None but disables the filter completely. """ modeladmin = DecadeFilterBookAdminWithNoneReturningLookups(Book, site) request = self.request_factory.get("/", {}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) filterspec = changelist.get_filters(request)[0] self.assertEqual(len(filterspec), 0) def test_filter_with_failing_queryset(self): """ When a filter's queryset method fails, it fails loudly and the corresponding exception doesn't get swallowed (#17828). """ modeladmin = DecadeFilterBookAdminWithFailingQueryset(Book, site) request = self.request_factory.get("/", {}) request.user = self.alfred with self.assertRaises(ZeroDivisionError): modeladmin.get_changelist_instance(request) def test_simplelistfilter_with_queryset_based_lookups(self): modeladmin = DecadeFilterBookAdminWithQuerysetBasedLookups(Book, site) request = self.request_factory.get("/", {}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(filterspec.title, "publication decade") choices = list(filterspec.choices(changelist)) self.assertEqual(len(choices), 3) self.assertEqual(choices[0]["display"], "All") self.assertIs(choices[0]["selected"], True) self.assertEqual(choices[0]["query_string"], "?") self.assertEqual(choices[1]["display"], "the 1990's") self.assertIs(choices[1]["selected"], False) self.assertEqual(choices[1]["query_string"], "?publication-decade=the+90s") self.assertEqual(choices[2]["display"], "the 2000's") self.assertIs(choices[2]["selected"], False) self.assertEqual(choices[2]["query_string"], "?publication-decade=the+00s") def _test_facets(self, modeladmin, request, query_string=None): request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) self.assertSequenceEqual(queryset, list(Book.objects.order_by("-id"))) filters = changelist.get_filters(request)[0] # Filters for DateFieldListFilter. expected_date_filters = ["Any date (4)", "Today (2)", "Past 7 days (3)"] if ( self.today.month == self.one_week_ago.month and self.today.year == self.one_week_ago.year ): expected_date_filters.extend(["This month (3)", "This year (3)"]) elif self.today.year == self.one_week_ago.year: expected_date_filters.extend(["This month (2)", "This year (3)"]) else: expected_date_filters.extend(["This month (2)", "This year (2)"]) expected_date_filters.extend(["No date (1)", "Has date (3)"]) empty_choice_count = ( 2 if connection.features.interprets_empty_strings_as_nulls else 1 ) tests = [ # RelatedFieldListFilter. ["All", "alfred (2)", "bob (1)", "lisa (0)", "??? (1)"], # SimpleListFilter. [ "All", "the 1980's (0)", "the 1990's (1)", "the 2000's (2)", "other decades (-)", ], # BooleanFieldListFilter. ["All", "Yes (2)", "No (1)", "Unknown (1)"], # ChoicesFieldListFilter. [ "All", "Non-Fictional (1)", "Fictional (1)", f"We don't know ({empty_choice_count})", f"Not categorized ({empty_choice_count})", ], # DateFieldListFilter. expected_date_filters, # AllValuesFieldListFilter. [ "All", "[email protected] (2)", "[email protected] (1)", "[email protected] (0)", ], # RelatedOnlyFieldListFilter. ["All", "bob (1)", "lisa (1)", "??? (3)"], # EmptyFieldListFilter. ["All", "Empty (2)", "Not empty (2)"], ] for filterspec, expected_displays in zip(filters, tests, strict=True): with self.subTest(filterspec.__class__.__name__): choices = list(filterspec.choices(changelist)) self.assertChoicesDisplay(choices, expected_displays) if query_string: for choice in choices: self.assertIn(query_string, choice["query_string"]) def test_facets_always(self): modeladmin = DecadeFilterBookAdminWithAlwaysFacets(Book, site) request = self.request_factory.get("/") self._test_facets(modeladmin, request) def test_facets_no_filter(self): modeladmin = DecadeFilterBookAdmin(Book, site) request = self.request_factory.get("/?_facets") self._test_facets(modeladmin, request, query_string="_facets") def test_facets_filter(self): modeladmin = DecadeFilterBookAdmin(Book, site) request = self.request_factory.get( "/", {"author__id__exact": self.alfred.pk, "_facets": ""} ) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) self.assertSequenceEqual( queryset, list(Book.objects.filter(author=self.alfred).order_by("-id")), ) filters = changelist.get_filters(request)[0] tests = [ # RelatedFieldListFilter. ["All", "alfred (2)", "bob (1)", "lisa (0)", "??? (1)"], # SimpleListFilter. [ "All", "the 1980's (0)", "the 1990's (1)", "the 2000's (1)", "other decades (-)", ], # BooleanFieldListFilter. ["All", "Yes (1)", "No (1)", "Unknown (0)"], # ChoicesFieldListFilter. [ "All", "Non-Fictional (1)", "Fictional (1)", "We don't know (0)", "Not categorized (0)", ], # DateFieldListFilter. [ "Any date (2)", "Today (1)", "Past 7 days (1)", "This month (1)", "This year (1)", "No date (1)", "Has date (1)", ], # AllValuesFieldListFilter. [ "All", "[email protected] (2)", "[email protected] (0)", "[email protected] (0)", ], # RelatedOnlyFieldListFilter. ["All", "bob (0)", "lisa (0)", "??? (2)"], # EmptyFieldListFilter. ["All", "Empty (0)", "Not empty (2)"], ] for filterspec, expected_displays in zip(filters, tests, strict=True): with self.subTest(filterspec.__class__.__name__): choices = list(filterspec.choices(changelist)) self.assertChoicesDisplay(choices, expected_displays) for choice in choices: self.assertIn("_facets", choice["query_string"]) def test_facets_disallowed(self): modeladmin = DecadeFilterBookAdminDisallowFacets(Book, site) # Facets are not visible even when in the url query. request = self.request_factory.get("/?_facets") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) self.assertSequenceEqual(queryset, list(Book.objects.order_by("-id"))) filters = changelist.get_filters(request)[0] tests = [ # RelatedFieldListFilter. ["All", "alfred", "bob", "lisa", "???"], # SimpleListFilter. ["All", "the 1980's", "the 1990's", "the 2000's", "other decades"], # BooleanFieldListFilter. ["All", "Yes", "No", "Unknown"], # ChoicesFieldListFilter. ["All", "Non-Fictional", "Fictional", "We don't know", "Not categorized"], # DateFieldListFilter. [ "Any date", "Today", "Past 7 days", "This month", "This year", "No date", "Has date", ], # AllValuesFieldListFilter. ["All", "[email protected]", "[email protected]", "[email protected]"], # RelatedOnlyFieldListFilter. ["All", "bob", "lisa", "???"], # EmptyFieldListFilter. ["All", "Empty", "Not empty"], ] for filterspec, expected_displays in zip(filters, tests, strict=True): with self.subTest(filterspec.__class__.__name__): self.assertChoicesDisplay( filterspec.choices(changelist), expected_displays, ) def test_multi_related_field_filter(self): modeladmin = DecadeFilterBookAdmin(Book, site) request = self.request_factory.get( "/", [("author__id__exact", self.alfred.pk), ("author__id__exact", self.bob.pk)], ) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) self.assertSequenceEqual( queryset, list( Book.objects.filter( author__pk__in=[self.alfred.pk, self.bob.pk] ).order_by("-id") ), ) filterspec = changelist.get_filters(request)[0][0] choices = list(filterspec.choices(changelist)) expected_choice_values = [ ("All", False, "?"), ("alfred", True, f"?author__id__exact={self.alfred.pk}"), ("bob", True, f"?author__id__exact={self.bob.pk}"), ("lisa", False, f"?author__id__exact={self.lisa.pk}"), ] for i, (display, selected, query_string) in enumerate(expected_choice_values): self.assertEqual(choices[i]["display"], display) self.assertIs(choices[i]["selected"], selected) self.assertEqual(choices[i]["query_string"], query_string) def test_multi_choice_field_filter(self): modeladmin = DecadeFilterBookAdmin(Book, site) request = self.request_factory.get( "/", [("category__exact", "non-fiction"), ("category__exact", "fiction")], ) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) self.assertSequenceEqual( queryset, list( Book.objects.filter(category__in=["non-fiction", "fiction"]).order_by( "-id" ) ), ) filterspec = changelist.get_filters(request)[0][3] choices = list(filterspec.choices(changelist)) expected_choice_values = [ ("All", False, "?"), ("Non-Fictional", True, "?category__exact=non-fiction"), ("Fictional", True, "?category__exact=fiction"), ("We don't know", False, "?category__exact="), ("Not categorized", False, "?category__isnull=True"), ] for i, (display, selected, query_string) in enumerate(expected_choice_values): self.assertEqual(choices[i]["display"], display) self.assertIs(choices[i]["selected"], selected) self.assertEqual(choices[i]["query_string"], query_string) def test_multi_all_values_field_filter(self): modeladmin = DecadeFilterBookAdmin(Book, site) request = self.request_factory.get( "/", [ ("author__email", "[email protected]"), ("author__email", "[email protected]"), ], ) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) self.assertSequenceEqual( queryset, list( Book.objects.filter( author__email__in=["[email protected]", "[email protected]"] ).order_by("-id") ), ) filterspec = changelist.get_filters(request)[0][5] choices = list(filterspec.choices(changelist)) expected_choice_values = [ ("All", False, "?"), ("[email protected]", False, "?author__email=alfred%40example.com"), ("[email protected]", True, "?author__email=bob%40example.com"), ("[email protected]", True, "?author__email=lisa%40example.com"), ] for i, (display, selected, query_string) in enumerate(expected_choice_values): self.assertEqual(choices[i]["display"], display) self.assertIs(choices[i]["selected"], selected) self.assertEqual(choices[i]["query_string"], query_string) def test_two_characters_long_field(self): """ list_filter works with two-characters long field names (#16080). """ modeladmin = BookAdmin(Book, site) request = self.request_factory.get("/", {"no": "207"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.bio_book]) filterspec = changelist.get_filters(request)[0][5] self.assertEqual(filterspec.title, "number") choices = list(filterspec.choices(changelist)) self.assertIs(choices[2]["selected"], True) self.assertEqual(choices[2]["query_string"], "?no=207") def test_parameter_ends_with__in__or__isnull(self): """ A SimpleListFilter's parameter name is not mistaken for a model field if it ends with '__isnull' or '__in' (#17091). """ # When it ends with '__in' ----------------------------------------- modeladmin = DecadeFilterBookAdminParameterEndsWith__In(Book, site) request = self.request_factory.get("/", {"decade__in": "the 90s"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.bio_book]) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][0] self.assertEqual(filterspec.title, "publication decade") choices = list(filterspec.choices(changelist)) self.assertEqual(choices[2]["display"], "the 1990's") self.assertIs(choices[2]["selected"], True) self.assertEqual(choices[2]["query_string"], "?decade__in=the+90s") # When it ends with '__isnull' --------------------------------------- modeladmin = DecadeFilterBookAdminParameterEndsWith__Isnull(Book, site) request = self.request_factory.get("/", {"decade__isnull": "the 90s"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.bio_book]) # Make sure the correct choice is selected filterspec = changelist.get_filters(request)[0][0] self.assertEqual(filterspec.title, "publication decade") choices = list(filterspec.choices(changelist)) self.assertEqual(choices[2]["display"], "the 1990's") self.assertIs(choices[2]["selected"], True) self.assertEqual(choices[2]["query_string"], "?decade__isnull=the+90s") def test_lookup_with_non_string_value(self): """ Ensure choices are set the selected class when using non-string values for lookups in SimpleListFilters (#19318). """ modeladmin = DepartmentFilterEmployeeAdmin(Employee, site) request = self.request_factory.get("/", {"department": self.john.department.pk}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.john]) filterspec = changelist.get_filters(request)[0][-1] self.assertEqual(filterspec.title, "department") choices = list(filterspec.choices(changelist)) self.assertEqual(choices[1]["display"], "DEV") self.assertIs(choices[1]["selected"], True) self.assertEqual( choices[1]["query_string"], "?department=%s" % self.john.department.pk ) def test_lookup_with_non_string_value_underscored(self): """ Ensure SimpleListFilter lookups pass lookup_allowed checks when parameter_name attribute contains double-underscore value (#19182). """ modeladmin = DepartmentFilterUnderscoredEmployeeAdmin(Employee, site) request = self.request_factory.get( "/", {"department__whatever": self.john.department.pk} ) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.john]) filterspec = changelist.get_filters(request)[0][-1] self.assertEqual(filterspec.title, "department") choices = list(filterspec.choices(changelist)) self.assertEqual(choices[1]["display"], "DEV") self.assertIs(choices[1]["selected"], True) self.assertEqual( choices[1]["query_string"], "?department__whatever=%s" % self.john.department.pk, ) def test_fk_with_to_field(self): """ A filter on a FK respects the FK's to_field attribute (#17972). """ modeladmin = EmployeeAdmin(Employee, site) request = self.request_factory.get("/", {}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.jack, self.john]) filterspec = changelist.get_filters(request)[0][-1] self.assertEqual(filterspec.title, "department") choices = [ (choice["display"], choice["selected"], choice["query_string"]) for choice in filterspec.choices(changelist) ] self.assertCountEqual( choices, [ ("All", True, "?"), ("Development", False, "?department__code__exact=DEV"), ("Design", False, "?department__code__exact=DSN"), ], ) # Filter by Department=='Development' -------------------------------- request = self.request_factory.get("/", {"department__code__exact": "DEV"}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [self.john]) filterspec = changelist.get_filters(request)[0][-1] self.assertEqual(filterspec.title, "department") choices = [ (choice["display"], choice["selected"], choice["query_string"]) for choice in filterspec.choices(changelist) ] self.assertCountEqual( choices, [ ("All", False, "?"), ("Development", True, "?department__code__exact=DEV"), ("Design", False, "?department__code__exact=DSN"), ], ) def test_lookup_with_dynamic_value(self): """ Ensure SimpleListFilter can access self.value() inside the lookup. """ modeladmin = DepartmentFilterDynamicValueBookAdmin(Book, site) def _test_choices(request, expected_displays): request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(filterspec.title, "publication decade") choices = tuple(c["display"] for c in filterspec.choices(changelist)) self.assertEqual(choices, expected_displays) _test_choices( self.request_factory.get("/", {}), ("All", "the 1980's", "the 1990's") ) _test_choices( self.request_factory.get("/", {"publication-decade": "the 80s"}), ("All", "the 1990's"), ) _test_choices( self.request_factory.get("/", {"publication-decade": "the 90s"}), ("All", "the 1980's"), ) def test_list_filter_queryset_filtered_by_default(self): """ A list filter that filters the queryset by default gives the correct full_result_count. """ modeladmin = NotNinetiesListFilterAdmin(Book, site) request = self.request_factory.get("/", {}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) changelist.get_results(request) self.assertEqual(changelist.full_result_count, 4) def test_emptylistfieldfilter(self): empty_description = Department.objects.create(code="EMPT", description="") none_description = Department.objects.create(code="NONE", description=None) empty_title = Book.objects.create(title="", author=self.alfred) department_admin = DepartmentAdminWithEmptyFieldListFilter(Department, site) book_admin = BookAdminWithEmptyFieldListFilter(Book, site) tests = [ # Allows nulls and empty strings. ( department_admin, {"description__isempty": "1"}, [empty_description, none_description], ), ( department_admin, {"description__isempty": "0"}, [self.dev, self.design], ), # Allows nulls. (book_admin, {"author__isempty": "1"}, [self.guitar_book]), ( book_admin, {"author__isempty": "0"}, [self.django_book, self.bio_book, self.djangonaut_book, empty_title], ), # Allows empty strings. (book_admin, {"title__isempty": "1"}, [empty_title]), ( book_admin, {"title__isempty": "0"}, [ self.django_book, self.bio_book, self.djangonaut_book, self.guitar_book, ], ), ] for modeladmin, query_string, expected_result in tests: with self.subTest( modeladmin=modeladmin.__class__.__name__, query_string=query_string, ): request = self.request_factory.get("/", query_string) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) self.assertCountEqual(queryset, expected_result) def test_emptylistfieldfilter_reverse_relationships(self): class UserAdminReverseRelationship(UserAdmin): list_filter = (("books_contributed", EmptyFieldListFilter),) ImprovedBook.objects.create(book=self.guitar_book) no_employees = Department.objects.create(code="NONE", description=None) book_admin = BookAdminWithEmptyFieldListFilter(Book, site) department_admin = DepartmentAdminWithEmptyFieldListFilter(Department, site) user_admin = UserAdminReverseRelationship(User, site) tests = [ # Reverse one-to-one relationship. ( book_admin, {"improvedbook__isempty": "1"}, [self.django_book, self.bio_book, self.djangonaut_book], ), (book_admin, {"improvedbook__isempty": "0"}, [self.guitar_book]), # Reverse foreign key relationship. (department_admin, {"employee__isempty": "1"}, [no_employees]), (department_admin, {"employee__isempty": "0"}, [self.dev, self.design]), # Reverse many-to-many relationship. (user_admin, {"books_contributed__isempty": "1"}, [self.alfred]), (user_admin, {"books_contributed__isempty": "0"}, [self.bob, self.lisa]), ] for modeladmin, query_string, expected_result in tests: with self.subTest( modeladmin=modeladmin.__class__.__name__, query_string=query_string, ): request = self.request_factory.get("/", query_string) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) self.assertCountEqual(queryset, expected_result) def test_emptylistfieldfilter_genericrelation(self): class BookmarkGenericRelation(ModelAdmin): list_filter = (("tags", EmptyFieldListFilter),) modeladmin = BookmarkGenericRelation(Bookmark, site) django_bookmark = Bookmark.objects.create(url="https://www.djangoproject.com/") python_bookmark = Bookmark.objects.create(url="https://www.python.org/") none_tags = Bookmark.objects.create(url="https://www.kernel.org/") TaggedItem.objects.create(content_object=django_bookmark, tag="python") TaggedItem.objects.create(content_object=python_bookmark, tag="python") tests = [ ({"tags__isempty": "1"}, [none_tags]), ({"tags__isempty": "0"}, [django_bookmark, python_bookmark]), ] for query_string, expected_result in tests: with self.subTest(query_string=query_string): request = self.request_factory.get("/", query_string) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) queryset = changelist.get_queryset(request) self.assertCountEqual(queryset, expected_result) def test_emptylistfieldfilter_choices(self): modeladmin = BookAdminWithEmptyFieldListFilter(Book, site) request = self.request_factory.get("/") request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(filterspec.title, "Verbose Author") choices = list(filterspec.choices(changelist)) self.assertEqual(len(choices), 3) self.assertEqual(choices[0]["display"], "All") self.assertIs(choices[0]["selected"], True) self.assertEqual(choices[0]["query_string"], "?") self.assertEqual(choices[1]["display"], "Empty") self.assertIs(choices[1]["selected"], False) self.assertEqual(choices[1]["query_string"], "?author__isempty=1") self.assertEqual(choices[2]["display"], "Not empty") self.assertIs(choices[2]["selected"], False) self.assertEqual(choices[2]["query_string"], "?author__isempty=0") def test_emptylistfieldfilter_non_empty_field(self): class EmployeeAdminWithEmptyFieldListFilter(ModelAdmin): list_filter = [("department", EmptyFieldListFilter)] modeladmin = EmployeeAdminWithEmptyFieldListFilter(Employee, site) request = self.request_factory.get("/") request.user = self.alfred msg = ( "The list filter 'EmptyFieldListFilter' cannot be used with field " "'department' which doesn't allow empty strings and nulls." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): modeladmin.get_changelist_instance(request) def test_emptylistfieldfilter_invalid_lookup_parameters(self): modeladmin = BookAdminWithEmptyFieldListFilter(Book, site) request = self.request_factory.get("/", {"author__isempty": 42}) request.user = self.alfred with self.assertRaises(IncorrectLookupParameters): modeladmin.get_changelist_instance(request) def test_lookup_using_custom_divider(self): """ Filter __in lookups with a custom divider. """ jane = Employee.objects.create(name="Jane,Green", department=self.design) modeladmin = EmployeeCustomDividerFilterAdmin(Employee, site) employees = [jane, self.jack] request = self.request_factory.get( "/", {"name__in": "|".join(e.name for e in employees)} ) # test for lookup with custom divider request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), employees) # test for lookup with comma in the lookup string request = self.request_factory.get("/", {"name": jane.name}) request.user = self.alfred changelist = modeladmin.get_changelist_instance(request) # Make sure the correct queryset is returned queryset = changelist.get_queryset(request) self.assertEqual(list(queryset), [jane]) class FacetsMixinTests(SimpleTestCase): def test_get_facet_counts(self): msg = "subclasses of FacetsMixin must provide a get_facet_counts() method." with self.assertRaisesMessage(NotImplementedError, msg): FacetsMixin().get_facet_counts(None, None)
57007a79167adb72c4598e5a62a79bfcb11117a22d3c4b5f52f3e356441101f2
import decimal import enum import json import unittest import uuid from django import forms from django.contrib.admin.utils import display_for_field from django.core import checks, exceptions, serializers, validators from django.core.exceptions import FieldError from django.core.management import call_command from django.db import IntegrityError, connection, models from django.db.models.expressions import Exists, OuterRef, RawSQL, Value from django.db.models.functions import Cast, JSONObject, Upper from django.test import TransactionTestCase, override_settings, skipUnlessDBFeature from django.test.utils import isolate_apps from django.utils import timezone from . import PostgreSQLSimpleTestCase, PostgreSQLTestCase, PostgreSQLWidgetTestCase from .models import ( ArrayEnumModel, ArrayFieldSubclass, CharArrayModel, DateTimeArrayModel, IntegerArrayModel, NestedIntegerArrayModel, NullableIntegerArrayModel, OtherTypesArrayModel, PostgreSQLModel, Tag, ) try: from django.contrib.postgres.aggregates import ArrayAgg from django.contrib.postgres.expressions import ArraySubquery from django.contrib.postgres.fields import ArrayField from django.contrib.postgres.fields.array import IndexTransform, SliceTransform from django.contrib.postgres.forms import ( SimpleArrayField, SplitArrayField, SplitArrayWidget, ) from django.db.backends.postgresql.psycopg_any import NumericRange except ImportError: pass @isolate_apps("postgres_tests") class BasicTests(PostgreSQLSimpleTestCase): def test_get_field_display(self): class MyModel(PostgreSQLModel): field = ArrayField( models.CharField(max_length=16), choices=[ ["Media", [(["vinyl", "cd"], "Audio")]], (("mp3", "mp4"), "Digital"), ], ) tests = ( (["vinyl", "cd"], "Audio"), (("mp3", "mp4"), "Digital"), (("a", "b"), "('a', 'b')"), (["c", "d"], "['c', 'd']"), ) for value, display in tests: with self.subTest(value=value, display=display): instance = MyModel(field=value) self.assertEqual(instance.get_field_display(), display) def test_get_field_display_nested_array(self): class MyModel(PostgreSQLModel): field = ArrayField( ArrayField(models.CharField(max_length=16)), choices=[ [ "Media", [([["vinyl", "cd"], ("x",)], "Audio")], ], ((["mp3"], ("mp4",)), "Digital"), ], ) tests = ( ([["vinyl", "cd"], ("x",)], "Audio"), ((["mp3"], ("mp4",)), "Digital"), ((("a", "b"), ("c",)), "(('a', 'b'), ('c',))"), ([["a", "b"], ["c"]], "[['a', 'b'], ['c']]"), ) for value, display in tests: with self.subTest(value=value, display=display): instance = MyModel(field=value) self.assertEqual(instance.get_field_display(), display) class TestSaveLoad(PostgreSQLTestCase): def test_integer(self): instance = IntegerArrayModel(field=[1, 2, 3]) instance.save() loaded = IntegerArrayModel.objects.get() self.assertEqual(instance.field, loaded.field) def test_char(self): instance = CharArrayModel(field=["hello", "goodbye"]) instance.save() loaded = CharArrayModel.objects.get() self.assertEqual(instance.field, loaded.field) def test_dates(self): instance = DateTimeArrayModel( datetimes=[timezone.now()], dates=[timezone.now().date()], times=[timezone.now().time()], ) instance.save() loaded = DateTimeArrayModel.objects.get() self.assertEqual(instance.datetimes, loaded.datetimes) self.assertEqual(instance.dates, loaded.dates) self.assertEqual(instance.times, loaded.times) def test_tuples(self): instance = IntegerArrayModel(field=(1,)) instance.save() loaded = IntegerArrayModel.objects.get() self.assertSequenceEqual(instance.field, loaded.field) def test_integers_passed_as_strings(self): # This checks that get_prep_value is deferred properly instance = IntegerArrayModel(field=["1"]) instance.save() loaded = IntegerArrayModel.objects.get() self.assertEqual(loaded.field, [1]) def test_default_null(self): instance = NullableIntegerArrayModel() instance.save() loaded = NullableIntegerArrayModel.objects.get(pk=instance.pk) self.assertIsNone(loaded.field) self.assertEqual(instance.field, loaded.field) def test_null_handling(self): instance = NullableIntegerArrayModel(field=None) instance.save() loaded = NullableIntegerArrayModel.objects.get() self.assertEqual(instance.field, loaded.field) instance = IntegerArrayModel(field=None) with self.assertRaises(IntegrityError): instance.save() def test_nested(self): instance = NestedIntegerArrayModel(field=[[1, 2], [3, 4]]) instance.save() loaded = NestedIntegerArrayModel.objects.get() self.assertEqual(instance.field, loaded.field) def test_other_array_types(self): instance = OtherTypesArrayModel( ips=["192.168.0.1", "::1"], uuids=[uuid.uuid4()], decimals=[decimal.Decimal(1.25), 1.75], tags=[Tag(1), Tag(2), Tag(3)], json=[{"a": 1}, {"b": 2}], int_ranges=[NumericRange(10, 20), NumericRange(30, 40)], bigint_ranges=[ NumericRange(7000000000, 10000000000), NumericRange(50000000000, 70000000000), ], ) instance.save() loaded = OtherTypesArrayModel.objects.get() self.assertEqual(instance.ips, loaded.ips) self.assertEqual(instance.uuids, loaded.uuids) self.assertEqual(instance.decimals, loaded.decimals) self.assertEqual(instance.tags, loaded.tags) self.assertEqual(instance.json, loaded.json) self.assertEqual(instance.int_ranges, loaded.int_ranges) self.assertEqual(instance.bigint_ranges, loaded.bigint_ranges) def test_null_from_db_value_handling(self): instance = OtherTypesArrayModel.objects.create( ips=["192.168.0.1", "::1"], uuids=[uuid.uuid4()], decimals=[decimal.Decimal(1.25), 1.75], tags=None, ) instance.refresh_from_db() self.assertIsNone(instance.tags) self.assertEqual(instance.json, []) self.assertIsNone(instance.int_ranges) self.assertIsNone(instance.bigint_ranges) def test_model_set_on_base_field(self): instance = IntegerArrayModel() field = instance._meta.get_field("field") self.assertEqual(field.model, IntegerArrayModel) self.assertEqual(field.base_field.model, IntegerArrayModel) def test_nested_nullable_base_field(self): instance = NullableIntegerArrayModel.objects.create( field_nested=[[None, None], [None, None]], ) self.assertEqual(instance.field_nested, [[None, None], [None, None]]) class TestQuerying(PostgreSQLTestCase): @classmethod def setUpTestData(cls): cls.objs = NullableIntegerArrayModel.objects.bulk_create( [ NullableIntegerArrayModel(order=1, field=[1]), NullableIntegerArrayModel(order=2, field=[2]), NullableIntegerArrayModel(order=3, field=[2, 3]), NullableIntegerArrayModel(order=4, field=[20, 30, 40]), NullableIntegerArrayModel(order=5, field=None), ] ) def test_empty_list(self): NullableIntegerArrayModel.objects.create(field=[]) obj = ( NullableIntegerArrayModel.objects.annotate( empty_array=models.Value( [], output_field=ArrayField(models.IntegerField()) ), ) .filter(field=models.F("empty_array")) .get() ) self.assertEqual(obj.field, []) self.assertEqual(obj.empty_array, []) def test_exact(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__exact=[1]), self.objs[:1] ) def test_exact_null_only_array(self): obj = NullableIntegerArrayModel.objects.create( field=[None], field_nested=[None, None] ) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__exact=[None]), [obj] ) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field_nested__exact=[None, None]), [obj], ) def test_exact_null_only_nested_array(self): obj1 = NullableIntegerArrayModel.objects.create(field_nested=[[None, None]]) obj2 = NullableIntegerArrayModel.objects.create( field_nested=[[None, None], [None, None]], ) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field_nested__exact=[[None, None]], ), [obj1], ) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field_nested__exact=[[None, None], [None, None]], ), [obj2], ) def test_exact_with_expression(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__exact=[Value(1)]), self.objs[:1], ) def test_exact_charfield(self): instance = CharArrayModel.objects.create(field=["text"]) self.assertSequenceEqual( CharArrayModel.objects.filter(field=["text"]), [instance] ) def test_exact_nested(self): instance = NestedIntegerArrayModel.objects.create(field=[[1, 2], [3, 4]]) self.assertSequenceEqual( NestedIntegerArrayModel.objects.filter(field=[[1, 2], [3, 4]]), [instance] ) def test_isnull(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__isnull=True), self.objs[-1:] ) def test_gt(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__gt=[0]), self.objs[:4] ) def test_lt(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__lt=[2]), self.objs[:1] ) def test_in(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__in=[[1], [2]]), self.objs[:2], ) def test_in_subquery(self): IntegerArrayModel.objects.create(field=[2, 3]) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__in=IntegerArrayModel.objects.values_list("field", flat=True) ), self.objs[2:3], ) @unittest.expectedFailure def test_in_including_F_object(self): # This test asserts that Array objects passed to filters can be # constructed to contain F objects. This currently doesn't work as the # psycopg mogrify method that generates the ARRAY() syntax is # expecting literals, not column references (#27095). self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__in=[[models.F("id")]]), self.objs[:2], ) def test_in_as_F_object(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__in=[models.F("field")]), self.objs[:4], ) def test_contained_by(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__contained_by=[1, 2]), self.objs[:2], ) def test_contained_by_including_F_object(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__contained_by=[models.F("order"), 2] ), self.objs[:3], ) def test_contains(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__contains=[2]), self.objs[1:3], ) def test_contains_subquery(self): IntegerArrayModel.objects.create(field=[2, 3]) inner_qs = IntegerArrayModel.objects.values_list("field", flat=True) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__contains=inner_qs[:1]), self.objs[2:3], ) inner_qs = IntegerArrayModel.objects.filter(field__contains=OuterRef("field")) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(Exists(inner_qs)), self.objs[1:3], ) def test_contains_including_expression(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__contains=[2, Value(6) / Value(2)], ), self.objs[2:3], ) def test_icontains(self): # Using the __icontains lookup with ArrayField is inefficient. instance = CharArrayModel.objects.create(field=["FoO"]) self.assertSequenceEqual( CharArrayModel.objects.filter(field__icontains="foo"), [instance] ) def test_contains_charfield(self): # Regression for #22907 self.assertSequenceEqual( CharArrayModel.objects.filter(field__contains=["text"]), [] ) def test_contained_by_charfield(self): self.assertSequenceEqual( CharArrayModel.objects.filter(field__contained_by=["text"]), [] ) def test_overlap_charfield(self): self.assertSequenceEqual( CharArrayModel.objects.filter(field__overlap=["text"]), [] ) def test_overlap_charfield_including_expression(self): obj_1 = CharArrayModel.objects.create(field=["TEXT", "lower text"]) obj_2 = CharArrayModel.objects.create(field=["lower text", "TEXT"]) CharArrayModel.objects.create(field=["lower text", "text"]) self.assertSequenceEqual( CharArrayModel.objects.filter( field__overlap=[ Upper(Value("text")), "other", ] ), [obj_1, obj_2], ) def test_overlap_values(self): qs = NullableIntegerArrayModel.objects.filter(order__lt=3) self.assertCountEqual( NullableIntegerArrayModel.objects.filter( field__overlap=qs.values_list("field"), ), self.objs[:3], ) self.assertCountEqual( NullableIntegerArrayModel.objects.filter( field__overlap=qs.values("field"), ), self.objs[:3], ) def test_lookups_autofield_array(self): qs = ( NullableIntegerArrayModel.objects.filter( field__0__isnull=False, ) .values("field__0") .annotate( arrayagg=ArrayAgg("id"), ) .order_by("field__0") ) tests = ( ("contained_by", [self.objs[1].pk, self.objs[2].pk, 0], [2]), ("contains", [self.objs[2].pk], [2]), ("exact", [self.objs[3].pk], [20]), ("overlap", [self.objs[1].pk, self.objs[3].pk], [2, 20]), ) for lookup, value, expected in tests: with self.subTest(lookup=lookup): self.assertSequenceEqual( qs.filter( **{"arrayagg__" + lookup: value}, ).values_list("field__0", flat=True), expected, ) @skipUnlessDBFeature("allows_group_by_select_index") def test_group_by_order_by_select_index(self): with self.assertNumQueries(1) as ctx: self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__0__isnull=False, ) .values("field__0") .annotate(arrayagg=ArrayAgg("id")) .order_by("field__0"), [ {"field__0": 1, "arrayagg": [self.objs[0].pk]}, {"field__0": 2, "arrayagg": [self.objs[1].pk, self.objs[2].pk]}, {"field__0": 20, "arrayagg": [self.objs[3].pk]}, ], ) sql = ctx[0]["sql"] self.assertIn("GROUP BY 2", sql) self.assertIn("ORDER BY 2", sql) def test_index(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__0=2), self.objs[1:3] ) def test_index_chained(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__0__lt=3), self.objs[0:3] ) def test_index_nested(self): instance = NestedIntegerArrayModel.objects.create(field=[[1, 2], [3, 4]]) self.assertSequenceEqual( NestedIntegerArrayModel.objects.filter(field__0__0=1), [instance] ) @unittest.expectedFailure def test_index_used_on_nested_data(self): instance = NestedIntegerArrayModel.objects.create(field=[[1, 2], [3, 4]]) self.assertSequenceEqual( NestedIntegerArrayModel.objects.filter(field__0=[1, 2]), [instance] ) def test_index_transform_expression(self): expr = RawSQL("string_to_array(%s, ';')", ["1;2"]) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__0=Cast( IndexTransform(1, models.IntegerField, expr), output_field=models.IntegerField(), ), ), self.objs[:1], ) def test_index_annotation(self): qs = NullableIntegerArrayModel.objects.annotate(second=models.F("field__1")) self.assertCountEqual( qs.values_list("second", flat=True), [None, None, None, 3, 30], ) def test_overlap(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__overlap=[1, 2]), self.objs[0:3], ) def test_len(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__len__lte=2), self.objs[0:3] ) def test_len_empty_array(self): obj = NullableIntegerArrayModel.objects.create(field=[]) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__len=0), [obj] ) def test_slice(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__0_1=[2]), self.objs[1:3] ) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__0_2=[2, 3]), self.objs[2:3] ) def test_order_by_slice(self): more_objs = ( NullableIntegerArrayModel.objects.create(field=[1, 637]), NullableIntegerArrayModel.objects.create(field=[2, 1]), NullableIntegerArrayModel.objects.create(field=[3, -98123]), NullableIntegerArrayModel.objects.create(field=[4, 2]), ) self.assertSequenceEqual( NullableIntegerArrayModel.objects.order_by("field__1"), [ more_objs[2], more_objs[1], more_objs[3], self.objs[2], self.objs[3], more_objs[0], self.objs[4], self.objs[1], self.objs[0], ], ) @unittest.expectedFailure def test_slice_nested(self): instance = NestedIntegerArrayModel.objects.create(field=[[1, 2], [3, 4]]) self.assertSequenceEqual( NestedIntegerArrayModel.objects.filter(field__0__0_1=[1]), [instance] ) def test_slice_transform_expression(self): expr = RawSQL("string_to_array(%s, ';')", ["9;2;3"]) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__0_2=SliceTransform(2, 3, expr) ), self.objs[2:3], ) def test_slice_annotation(self): qs = NullableIntegerArrayModel.objects.annotate( first_two=models.F("field__0_2"), ) self.assertCountEqual( qs.values_list("first_two", flat=True), [None, [1], [2], [2, 3], [20, 30]], ) def test_usage_in_subquery(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( id__in=NullableIntegerArrayModel.objects.filter(field__len=3) ), [self.objs[3]], ) def test_enum_lookup(self): class TestEnum(enum.Enum): VALUE_1 = "value_1" instance = ArrayEnumModel.objects.create(array_of_enums=[TestEnum.VALUE_1]) self.assertSequenceEqual( ArrayEnumModel.objects.filter(array_of_enums__contains=[TestEnum.VALUE_1]), [instance], ) def test_unsupported_lookup(self): msg = ( "Unsupported lookup '0_bar' for ArrayField or join on the field not " "permitted." ) with self.assertRaisesMessage(FieldError, msg): list(NullableIntegerArrayModel.objects.filter(field__0_bar=[2])) msg = ( "Unsupported lookup '0bar' for ArrayField or join on the field not " "permitted." ) with self.assertRaisesMessage(FieldError, msg): list(NullableIntegerArrayModel.objects.filter(field__0bar=[2])) def test_grouping_by_annotations_with_array_field_param(self): value = models.Value([1], output_field=ArrayField(models.IntegerField())) self.assertEqual( NullableIntegerArrayModel.objects.annotate( array_length=models.Func( value, 1, function="ARRAY_LENGTH", output_field=models.IntegerField(), ), ) .values("array_length") .annotate( count=models.Count("pk"), ) .get()["array_length"], 1, ) def test_filter_by_array_subquery(self): inner_qs = NullableIntegerArrayModel.objects.filter( field__len=models.OuterRef("field__len"), ).values("field") self.assertSequenceEqual( NullableIntegerArrayModel.objects.alias( same_sized_fields=ArraySubquery(inner_qs), ).filter(same_sized_fields__len__gt=1), self.objs[0:2], ) def test_annotated_array_subquery(self): inner_qs = NullableIntegerArrayModel.objects.exclude( pk=models.OuterRef("pk") ).values("order") self.assertSequenceEqual( NullableIntegerArrayModel.objects.annotate( sibling_ids=ArraySubquery(inner_qs), ) .get(order=1) .sibling_ids, [2, 3, 4, 5], ) def test_group_by_with_annotated_array_subquery(self): inner_qs = NullableIntegerArrayModel.objects.exclude( pk=models.OuterRef("pk") ).values("order") self.assertSequenceEqual( NullableIntegerArrayModel.objects.annotate( sibling_ids=ArraySubquery(inner_qs), sibling_count=models.Max("sibling_ids__len"), ).values_list("sibling_count", flat=True), [len(self.objs) - 1] * len(self.objs), ) def test_annotated_ordered_array_subquery(self): inner_qs = NullableIntegerArrayModel.objects.order_by("-order").values("order") self.assertSequenceEqual( NullableIntegerArrayModel.objects.annotate( ids=ArraySubquery(inner_qs), ) .first() .ids, [5, 4, 3, 2, 1], ) def test_annotated_array_subquery_with_json_objects(self): inner_qs = NullableIntegerArrayModel.objects.exclude( pk=models.OuterRef("pk") ).values(json=JSONObject(order="order", field="field")) siblings_json = ( NullableIntegerArrayModel.objects.annotate( siblings_json=ArraySubquery(inner_qs), ) .values_list("siblings_json", flat=True) .get(order=1) ) self.assertSequenceEqual( siblings_json, [ {"field": [2], "order": 2}, {"field": [2, 3], "order": 3}, {"field": [20, 30, 40], "order": 4}, {"field": None, "order": 5}, ], ) class TestDateTimeExactQuerying(PostgreSQLTestCase): @classmethod def setUpTestData(cls): now = timezone.now() cls.datetimes = [now] cls.dates = [now.date()] cls.times = [now.time()] cls.objs = [ DateTimeArrayModel.objects.create( datetimes=cls.datetimes, dates=cls.dates, times=cls.times ), ] def test_exact_datetimes(self): self.assertSequenceEqual( DateTimeArrayModel.objects.filter(datetimes=self.datetimes), self.objs ) def test_exact_dates(self): self.assertSequenceEqual( DateTimeArrayModel.objects.filter(dates=self.dates), self.objs ) def test_exact_times(self): self.assertSequenceEqual( DateTimeArrayModel.objects.filter(times=self.times), self.objs ) class TestOtherTypesExactQuerying(PostgreSQLTestCase): @classmethod def setUpTestData(cls): cls.ips = ["192.168.0.1", "::1"] cls.uuids = [uuid.uuid4()] cls.decimals = [decimal.Decimal(1.25), 1.75] cls.tags = [Tag(1), Tag(2), Tag(3)] cls.objs = [ OtherTypesArrayModel.objects.create( ips=cls.ips, uuids=cls.uuids, decimals=cls.decimals, tags=cls.tags, ) ] def test_exact_ip_addresses(self): self.assertSequenceEqual( OtherTypesArrayModel.objects.filter(ips=self.ips), self.objs ) def test_exact_uuids(self): self.assertSequenceEqual( OtherTypesArrayModel.objects.filter(uuids=self.uuids), self.objs ) def test_exact_decimals(self): self.assertSequenceEqual( OtherTypesArrayModel.objects.filter(decimals=self.decimals), self.objs ) def test_exact_tags(self): self.assertSequenceEqual( OtherTypesArrayModel.objects.filter(tags=self.tags), self.objs ) @isolate_apps("postgres_tests") class TestChecks(PostgreSQLSimpleTestCase): def test_field_checks(self): class MyModel(PostgreSQLModel): field = ArrayField(models.CharField(max_length=-1)) model = MyModel() errors = model.check() self.assertEqual(len(errors), 1) # The inner CharField has a non-positive max_length. self.assertEqual(errors[0].id, "postgres.E001") self.assertIn("max_length", errors[0].msg) def test_invalid_base_fields(self): class MyModel(PostgreSQLModel): field = ArrayField( models.ManyToManyField("postgres_tests.IntegerArrayModel") ) model = MyModel() errors = model.check() self.assertEqual(len(errors), 1) self.assertEqual(errors[0].id, "postgres.E002") def test_invalid_default(self): class MyModel(PostgreSQLModel): field = ArrayField(models.IntegerField(), default=[]) model = MyModel() self.assertEqual( model.check(), [ checks.Warning( msg=( "ArrayField default should be a callable instead of an " "instance so that it's not shared between all field " "instances." ), hint="Use a callable instead, e.g., use `list` instead of `[]`.", obj=MyModel._meta.get_field("field"), id="fields.E010", ) ], ) def test_valid_default(self): class MyModel(PostgreSQLModel): field = ArrayField(models.IntegerField(), default=list) model = MyModel() self.assertEqual(model.check(), []) def test_valid_default_none(self): class MyModel(PostgreSQLModel): field = ArrayField(models.IntegerField(), default=None) model = MyModel() self.assertEqual(model.check(), []) def test_nested_field_checks(self): """ Nested ArrayFields are permitted. """ class MyModel(PostgreSQLModel): field = ArrayField(ArrayField(models.CharField(max_length=-1))) model = MyModel() errors = model.check() self.assertEqual(len(errors), 1) # The inner CharField has a non-positive max_length. self.assertEqual(errors[0].id, "postgres.E001") self.assertIn("max_length", errors[0].msg) def test_choices_tuple_list(self): class MyModel(PostgreSQLModel): field = ArrayField( models.CharField(max_length=16), choices=[ [ "Media", [(["vinyl", "cd"], "Audio"), (("vhs", "dvd"), "Video")], ], (["mp3", "mp4"], "Digital"), ], ) self.assertEqual(MyModel._meta.get_field("field").check(), []) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests") class TestMigrations(TransactionTestCase): available_apps = ["postgres_tests"] def test_deconstruct(self): field = ArrayField(models.IntegerField()) name, path, args, kwargs = field.deconstruct() new = ArrayField(*args, **kwargs) self.assertEqual(type(new.base_field), type(field.base_field)) self.assertIsNot(new.base_field, field.base_field) def test_deconstruct_with_size(self): field = ArrayField(models.IntegerField(), size=3) name, path, args, kwargs = field.deconstruct() new = ArrayField(*args, **kwargs) self.assertEqual(new.size, field.size) def test_deconstruct_args(self): field = ArrayField(models.CharField(max_length=20)) name, path, args, kwargs = field.deconstruct() new = ArrayField(*args, **kwargs) self.assertEqual(new.base_field.max_length, field.base_field.max_length) def test_subclass_deconstruct(self): field = ArrayField(models.IntegerField()) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.contrib.postgres.fields.ArrayField") field = ArrayFieldSubclass() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "postgres_tests.models.ArrayFieldSubclass") @override_settings( MIGRATION_MODULES={ "postgres_tests": "postgres_tests.array_default_migrations", } ) def test_adding_field_with_default(self): # See #22962 table_name = "postgres_tests_integerarraydefaultmodel" with connection.cursor() as cursor: self.assertNotIn(table_name, connection.introspection.table_names(cursor)) call_command("migrate", "postgres_tests", verbosity=0) with connection.cursor() as cursor: self.assertIn(table_name, connection.introspection.table_names(cursor)) call_command("migrate", "postgres_tests", "zero", verbosity=0) with connection.cursor() as cursor: self.assertNotIn(table_name, connection.introspection.table_names(cursor)) @override_settings( MIGRATION_MODULES={ "postgres_tests": "postgres_tests.array_index_migrations", } ) def test_adding_arrayfield_with_index(self): """ ArrayField shouldn't have varchar_patterns_ops or text_patterns_ops indexes. """ table_name = "postgres_tests_chartextarrayindexmodel" call_command("migrate", "postgres_tests", verbosity=0) with connection.cursor() as cursor: like_constraint_columns_list = [ v["columns"] for k, v in list( connection.introspection.get_constraints(cursor, table_name).items() ) if k.endswith("_like") ] # Only the CharField should have a LIKE index. self.assertEqual(like_constraint_columns_list, [["char2"]]) # All fields should have regular indexes. with connection.cursor() as cursor: indexes = [ c["columns"][0] for c in connection.introspection.get_constraints( cursor, table_name ).values() if c["index"] and len(c["columns"]) == 1 ] self.assertIn("char", indexes) self.assertIn("char2", indexes) self.assertIn("text", indexes) call_command("migrate", "postgres_tests", "zero", verbosity=0) with connection.cursor() as cursor: self.assertNotIn(table_name, connection.introspection.table_names(cursor)) class TestSerialization(PostgreSQLSimpleTestCase): test_data = ( '[{"fields": {"field": "[\\"1\\", \\"2\\", null]"}, ' '"model": "postgres_tests.integerarraymodel", "pk": null}]' ) def test_dumping(self): instance = IntegerArrayModel(field=[1, 2, None]) data = serializers.serialize("json", [instance]) self.assertEqual(json.loads(data), json.loads(self.test_data)) def test_loading(self): instance = list(serializers.deserialize("json", self.test_data))[0].object self.assertEqual(instance.field, [1, 2, None]) class TestValidation(PostgreSQLSimpleTestCase): def test_unbounded(self): field = ArrayField(models.IntegerField()) with self.assertRaises(exceptions.ValidationError) as cm: field.clean([1, None], None) self.assertEqual(cm.exception.code, "item_invalid") self.assertEqual( cm.exception.message % cm.exception.params, "Item 2 in the array did not validate: This field cannot be null.", ) def test_blank_true(self): field = ArrayField(models.IntegerField(blank=True, null=True)) # This should not raise a validation error field.clean([1, None], None) def test_with_size(self): field = ArrayField(models.IntegerField(), size=3) field.clean([1, 2, 3], None) with self.assertRaises(exceptions.ValidationError) as cm: field.clean([1, 2, 3, 4], None) self.assertEqual( cm.exception.messages[0], "List contains 4 items, it should contain no more than 3.", ) def test_nested_array_mismatch(self): field = ArrayField(ArrayField(models.IntegerField())) field.clean([[1, 2], [3, 4]], None) with self.assertRaises(exceptions.ValidationError) as cm: field.clean([[1, 2], [3, 4, 5]], None) self.assertEqual(cm.exception.code, "nested_array_mismatch") self.assertEqual( cm.exception.messages[0], "Nested arrays must have the same length." ) def test_with_base_field_error_params(self): field = ArrayField(models.CharField(max_length=2)) with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["abc"], None) self.assertEqual(len(cm.exception.error_list), 1) exception = cm.exception.error_list[0] self.assertEqual( exception.message, "Item 1 in the array did not validate: Ensure this value has at most 2 " "characters (it has 3).", ) self.assertEqual(exception.code, "item_invalid") self.assertEqual( exception.params, {"nth": 1, "value": "abc", "limit_value": 2, "show_value": 3}, ) def test_with_validators(self): field = ArrayField( models.IntegerField(validators=[validators.MinValueValidator(1)]) ) field.clean([1, 2], None) with self.assertRaises(exceptions.ValidationError) as cm: field.clean([0], None) self.assertEqual(len(cm.exception.error_list), 1) exception = cm.exception.error_list[0] self.assertEqual( exception.message, "Item 1 in the array did not validate: Ensure this value is greater than " "or equal to 1.", ) self.assertEqual(exception.code, "item_invalid") self.assertEqual( exception.params, {"nth": 1, "value": 0, "limit_value": 1, "show_value": 0} ) class TestSimpleFormField(PostgreSQLSimpleTestCase): def test_valid(self): field = SimpleArrayField(forms.CharField()) value = field.clean("a,b,c") self.assertEqual(value, ["a", "b", "c"]) def test_to_python_fail(self): field = SimpleArrayField(forms.IntegerField()) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("a,b,9") self.assertEqual( cm.exception.messages[0], "Item 1 in the array did not validate: Enter a whole number.", ) def test_validate_fail(self): field = SimpleArrayField(forms.CharField(required=True)) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("a,b,") self.assertEqual( cm.exception.messages[0], "Item 3 in the array did not validate: This field is required.", ) def test_validate_fail_base_field_error_params(self): field = SimpleArrayField(forms.CharField(max_length=2)) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("abc,c,defg") errors = cm.exception.error_list self.assertEqual(len(errors), 2) first_error = errors[0] self.assertEqual( first_error.message, "Item 1 in the array did not validate: Ensure this value has at most 2 " "characters (it has 3).", ) self.assertEqual(first_error.code, "item_invalid") self.assertEqual( first_error.params, {"nth": 1, "value": "abc", "limit_value": 2, "show_value": 3}, ) second_error = errors[1] self.assertEqual( second_error.message, "Item 3 in the array did not validate: Ensure this value has at most 2 " "characters (it has 4).", ) self.assertEqual(second_error.code, "item_invalid") self.assertEqual( second_error.params, {"nth": 3, "value": "defg", "limit_value": 2, "show_value": 4}, ) def test_validators_fail(self): field = SimpleArrayField(forms.RegexField("[a-e]{2}")) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("a,bc,de") self.assertEqual( cm.exception.messages[0], "Item 1 in the array did not validate: Enter a valid value.", ) def test_delimiter(self): field = SimpleArrayField(forms.CharField(), delimiter="|") value = field.clean("a|b|c") self.assertEqual(value, ["a", "b", "c"]) def test_delimiter_with_nesting(self): field = SimpleArrayField(SimpleArrayField(forms.CharField()), delimiter="|") value = field.clean("a,b|c,d") self.assertEqual(value, [["a", "b"], ["c", "d"]]) def test_prepare_value(self): field = SimpleArrayField(forms.CharField()) value = field.prepare_value(["a", "b", "c"]) self.assertEqual(value, "a,b,c") def test_max_length(self): field = SimpleArrayField(forms.CharField(), max_length=2) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("a,b,c") self.assertEqual( cm.exception.messages[0], "List contains 3 items, it should contain no more than 2.", ) def test_min_length(self): field = SimpleArrayField(forms.CharField(), min_length=4) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("a,b,c") self.assertEqual( cm.exception.messages[0], "List contains 3 items, it should contain no fewer than 4.", ) def test_required(self): field = SimpleArrayField(forms.CharField(), required=True) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("") self.assertEqual(cm.exception.messages[0], "This field is required.") def test_model_field_formfield(self): model_field = ArrayField(models.CharField(max_length=27)) form_field = model_field.formfield() self.assertIsInstance(form_field, SimpleArrayField) self.assertIsInstance(form_field.base_field, forms.CharField) self.assertEqual(form_field.base_field.max_length, 27) def test_model_field_formfield_size(self): model_field = ArrayField(models.CharField(max_length=27), size=4) form_field = model_field.formfield() self.assertIsInstance(form_field, SimpleArrayField) self.assertEqual(form_field.max_length, 4) def test_model_field_choices(self): model_field = ArrayField(models.IntegerField(choices=((1, "A"), (2, "B")))) form_field = model_field.formfield() self.assertEqual(form_field.clean("1,2"), [1, 2]) def test_already_converted_value(self): field = SimpleArrayField(forms.CharField()) vals = ["a", "b", "c"] self.assertEqual(field.clean(vals), vals) def test_has_changed(self): field = SimpleArrayField(forms.IntegerField()) self.assertIs(field.has_changed([1, 2], [1, 2]), False) self.assertIs(field.has_changed([1, 2], "1,2"), False) self.assertIs(field.has_changed([1, 2], "1,2,3"), True) self.assertIs(field.has_changed([1, 2], "a,b"), True) def test_has_changed_empty(self): field = SimpleArrayField(forms.CharField()) self.assertIs(field.has_changed(None, None), False) self.assertIs(field.has_changed(None, ""), False) self.assertIs(field.has_changed(None, []), False) self.assertIs(field.has_changed([], None), False) self.assertIs(field.has_changed([], ""), False) class TestSplitFormField(PostgreSQLSimpleTestCase): def test_valid(self): class SplitForm(forms.Form): array = SplitArrayField(forms.CharField(), size=3) data = {"array_0": "a", "array_1": "b", "array_2": "c"} form = SplitForm(data) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data, {"array": ["a", "b", "c"]}) def test_required(self): class SplitForm(forms.Form): array = SplitArrayField(forms.CharField(), required=True, size=3) data = {"array_0": "", "array_1": "", "array_2": ""} form = SplitForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {"array": ["This field is required."]}) def test_remove_trailing_nulls(self): class SplitForm(forms.Form): array = SplitArrayField( forms.CharField(required=False), size=5, remove_trailing_nulls=True ) data = { "array_0": "a", "array_1": "", "array_2": "b", "array_3": "", "array_4": "", } form = SplitForm(data) self.assertTrue(form.is_valid(), form.errors) self.assertEqual(form.cleaned_data, {"array": ["a", "", "b"]}) def test_remove_trailing_nulls_not_required(self): class SplitForm(forms.Form): array = SplitArrayField( forms.CharField(required=False), size=2, remove_trailing_nulls=True, required=False, ) data = {"array_0": "", "array_1": ""} form = SplitForm(data) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data, {"array": []}) def test_required_field(self): class SplitForm(forms.Form): array = SplitArrayField(forms.CharField(), size=3) data = {"array_0": "a", "array_1": "b", "array_2": ""} form = SplitForm(data) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, { "array": [ "Item 3 in the array did not validate: This field is required." ] }, ) def test_invalid_integer(self): msg = ( "Item 2 in the array did not validate: Ensure this value is less than or " "equal to 100." ) with self.assertRaisesMessage(exceptions.ValidationError, msg): SplitArrayField(forms.IntegerField(max_value=100), size=2).clean([0, 101]) def test_rendering(self): class SplitForm(forms.Form): array = SplitArrayField(forms.CharField(), size=3) self.assertHTMLEqual( str(SplitForm()), """ <div> <label for="id_array_0">Array:</label> <input id="id_array_0" name="array_0" type="text" required> <input id="id_array_1" name="array_1" type="text" required> <input id="id_array_2" name="array_2" type="text" required> </div> """, ) def test_invalid_char_length(self): field = SplitArrayField(forms.CharField(max_length=2), size=3) with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["abc", "c", "defg"]) self.assertEqual( cm.exception.messages, [ "Item 1 in the array did not validate: Ensure this value has at most 2 " "characters (it has 3).", "Item 3 in the array did not validate: Ensure this value has at most 2 " "characters (it has 4).", ], ) def test_splitarraywidget_value_omitted_from_data(self): class Form(forms.ModelForm): field = SplitArrayField(forms.IntegerField(), required=False, size=2) class Meta: model = IntegerArrayModel fields = ("field",) form = Form({"field_0": "1", "field_1": "2"}) self.assertEqual(form.errors, {}) obj = form.save(commit=False) self.assertEqual(obj.field, [1, 2]) def test_splitarrayfield_has_changed(self): class Form(forms.ModelForm): field = SplitArrayField(forms.IntegerField(), required=False, size=2) class Meta: model = IntegerArrayModel fields = ("field",) tests = [ ({}, {"field_0": "", "field_1": ""}, True), ({"field": None}, {"field_0": "", "field_1": ""}, True), ({"field": [1]}, {"field_0": "", "field_1": ""}, True), ({"field": [1]}, {"field_0": "1", "field_1": "0"}, True), ({"field": [1, 2]}, {"field_0": "1", "field_1": "2"}, False), ({"field": [1, 2]}, {"field_0": "a", "field_1": "b"}, True), ] for initial, data, expected_result in tests: with self.subTest(initial=initial, data=data): obj = IntegerArrayModel(**initial) form = Form(data, instance=obj) self.assertIs(form.has_changed(), expected_result) def test_splitarrayfield_remove_trailing_nulls_has_changed(self): class Form(forms.ModelForm): field = SplitArrayField( forms.IntegerField(), required=False, size=2, remove_trailing_nulls=True ) class Meta: model = IntegerArrayModel fields = ("field",) tests = [ ({}, {"field_0": "", "field_1": ""}, False), ({"field": None}, {"field_0": "", "field_1": ""}, False), ({"field": []}, {"field_0": "", "field_1": ""}, False), ({"field": [1]}, {"field_0": "1", "field_1": ""}, False), ] for initial, data, expected_result in tests: with self.subTest(initial=initial, data=data): obj = IntegerArrayModel(**initial) form = Form(data, instance=obj) self.assertIs(form.has_changed(), expected_result) class TestSplitFormWidget(PostgreSQLWidgetTestCase): def test_get_context(self): self.assertEqual( SplitArrayWidget(forms.TextInput(), size=2).get_context( "name", ["val1", "val2"] ), { "widget": { "name": "name", "is_hidden": False, "required": False, "value": "['val1', 'val2']", "attrs": {}, "template_name": "postgres/widgets/split_array.html", "subwidgets": [ { "name": "name_0", "is_hidden": False, "required": False, "value": "val1", "attrs": {}, "template_name": "django/forms/widgets/text.html", "type": "text", }, { "name": "name_1", "is_hidden": False, "required": False, "value": "val2", "attrs": {}, "template_name": "django/forms/widgets/text.html", "type": "text", }, ], } }, ) def test_checkbox_get_context_attrs(self): context = SplitArrayWidget( forms.CheckboxInput(), size=2, ).get_context("name", [True, False]) self.assertEqual(context["widget"]["value"], "[True, False]") self.assertEqual( [subwidget["attrs"] for subwidget in context["widget"]["subwidgets"]], [{"checked": True}, {}], ) def test_render(self): self.check_html( SplitArrayWidget(forms.TextInput(), size=2), "array", None, """ <input name="array_0" type="text"> <input name="array_1" type="text"> """, ) def test_render_attrs(self): self.check_html( SplitArrayWidget(forms.TextInput(), size=2), "array", ["val1", "val2"], attrs={"id": "foo"}, html=( """ <input id="foo_0" name="array_0" type="text" value="val1"> <input id="foo_1" name="array_1" type="text" value="val2"> """ ), ) def test_value_omitted_from_data(self): widget = SplitArrayWidget(forms.TextInput(), size=2) self.assertIs(widget.value_omitted_from_data({}, {}, "field"), True) self.assertIs( widget.value_omitted_from_data({"field_0": "value"}, {}, "field"), False ) self.assertIs( widget.value_omitted_from_data({"field_1": "value"}, {}, "field"), False ) self.assertIs( widget.value_omitted_from_data( {"field_0": "value", "field_1": "value"}, {}, "field" ), False, ) class TestAdminUtils(PostgreSQLTestCase): empty_value = "-empty-" def test_array_display_for_field(self): array_field = ArrayField(models.IntegerField()) display_value = display_for_field( [1, 2], array_field, self.empty_value, ) self.assertEqual(display_value, "1, 2") def test_array_with_choices_display_for_field(self): array_field = ArrayField( models.IntegerField(), choices=[ ([1, 2, 3], "1st choice"), ([1, 2], "2nd choice"), ], ) display_value = display_for_field( [1, 2], array_field, self.empty_value, ) self.assertEqual(display_value, "2nd choice") display_value = display_for_field( [99, 99], array_field, self.empty_value, ) self.assertEqual(display_value, self.empty_value)
0b2ca1018e06976340cbac6e17bd8be9e06ceaa6c47f7cc4a7bc998fa2a960c1
import datetime from decimal import Decimal from django.core.exceptions import FieldDoesNotExist, FieldError from django.db.models import ( BooleanField, Case, CharField, Count, DateTimeField, DecimalField, Exists, ExpressionWrapper, F, FloatField, Func, IntegerField, Max, OuterRef, Q, Subquery, Sum, Value, When, ) from django.db.models.expressions import RawSQL from django.db.models.functions import ( Cast, Coalesce, ExtractYear, Floor, Length, Lower, Trim, ) from django.db.models.sql.query import get_field_names_from_opts from django.test import TestCase, skipUnlessDBFeature from django.test.utils import register_lookup from .models import ( Author, Book, Company, DepartmentStore, Employee, Publisher, Store, Ticket, ) class NonAggregateAnnotationTestCase(TestCase): @classmethod def setUpTestData(cls): cls.a1 = Author.objects.create(name="Adrian Holovaty", age=34) cls.a2 = Author.objects.create(name="Jacob Kaplan-Moss", age=35) cls.a3 = Author.objects.create(name="Brad Dayley", age=45) cls.a4 = Author.objects.create(name="James Bennett", age=29) cls.a5 = Author.objects.create(name="Jeffrey Forcier", age=37) cls.a6 = Author.objects.create(name="Paul Bissex", age=29) cls.a7 = Author.objects.create(name="Wesley J. Chun", age=25) cls.a8 = Author.objects.create(name="Peter Norvig", age=57) cls.a9 = Author.objects.create(name="Stuart Russell", age=46) cls.a1.friends.add(cls.a2, cls.a4) cls.a2.friends.add(cls.a1, cls.a7) cls.a4.friends.add(cls.a1) cls.a5.friends.add(cls.a6, cls.a7) cls.a6.friends.add(cls.a5, cls.a7) cls.a7.friends.add(cls.a2, cls.a5, cls.a6) cls.a8.friends.add(cls.a9) cls.a9.friends.add(cls.a8) cls.p1 = Publisher.objects.create(name="Apress", num_awards=3) cls.p2 = Publisher.objects.create(name="Sams", num_awards=1) cls.p3 = Publisher.objects.create(name="Prentice Hall", num_awards=7) cls.p4 = Publisher.objects.create(name="Morgan Kaufmann", num_awards=9) cls.p5 = Publisher.objects.create(name="Jonno's House of Books", num_awards=0) cls.b1 = Book.objects.create( isbn="159059725", name="The Definitive Guide to Django: Web Development Done Right", pages=447, rating=4.5, price=Decimal("30.00"), contact=cls.a1, publisher=cls.p1, pubdate=datetime.date(2007, 12, 6), ) cls.b2 = Book.objects.create( isbn="067232959", name="Sams Teach Yourself Django in 24 Hours", pages=528, rating=3.0, price=Decimal("23.09"), contact=cls.a3, publisher=cls.p2, pubdate=datetime.date(2008, 3, 3), ) cls.b3 = Book.objects.create( isbn="159059996", name="Practical Django Projects", pages=300, rating=4.0, price=Decimal("29.69"), contact=cls.a4, publisher=cls.p1, pubdate=datetime.date(2008, 6, 23), ) cls.b4 = Book.objects.create( isbn="013235613", name="Python Web Development with Django", pages=350, rating=4.0, price=Decimal("29.69"), contact=cls.a5, publisher=cls.p3, pubdate=datetime.date(2008, 11, 3), ) cls.b5 = Book.objects.create( isbn="013790395", name="Artificial Intelligence: A Modern Approach", pages=1132, rating=4.0, price=Decimal("82.80"), contact=cls.a8, publisher=cls.p3, pubdate=datetime.date(1995, 1, 15), ) cls.b6 = Book.objects.create( isbn="155860191", name=( "Paradigms of Artificial Intelligence Programming: Case Studies in " "Common Lisp" ), pages=946, rating=5.0, price=Decimal("75.00"), contact=cls.a8, publisher=cls.p4, pubdate=datetime.date(1991, 10, 15), ) cls.b1.authors.add(cls.a1, cls.a2) cls.b2.authors.add(cls.a3) cls.b3.authors.add(cls.a4) cls.b4.authors.add(cls.a5, cls.a6, cls.a7) cls.b5.authors.add(cls.a8, cls.a9) cls.b6.authors.add(cls.a8) cls.s1 = Store.objects.create( name="Amazon.com", original_opening=datetime.datetime(1994, 4, 23, 9, 17, 42), friday_night_closing=datetime.time(23, 59, 59), ) cls.s2 = Store.objects.create( name="Books.com", original_opening=datetime.datetime(2001, 3, 15, 11, 23, 37), friday_night_closing=datetime.time(23, 59, 59), ) cls.s3 = Store.objects.create( name="Mamma and Pappa's Books", original_opening=datetime.datetime(1945, 4, 25, 16, 24, 14), friday_night_closing=datetime.time(21, 30), ) cls.s1.books.add(cls.b1, cls.b2, cls.b3, cls.b4, cls.b5, cls.b6) cls.s2.books.add(cls.b1, cls.b3, cls.b5, cls.b6) cls.s3.books.add(cls.b3, cls.b4, cls.b6) def test_basic_annotation(self): books = Book.objects.annotate(is_book=Value(1)) for book in books: self.assertEqual(book.is_book, 1) def test_basic_f_annotation(self): books = Book.objects.annotate(another_rating=F("rating")) for book in books: self.assertEqual(book.another_rating, book.rating) def test_joined_annotation(self): books = Book.objects.select_related("publisher").annotate( num_awards=F("publisher__num_awards") ) for book in books: self.assertEqual(book.num_awards, book.publisher.num_awards) def test_joined_transformed_annotation(self): Employee.objects.bulk_create( [ Employee( first_name="John", last_name="Doe", age=18, store=self.s1, salary=15000, ), Employee( first_name="Jane", last_name="Jones", age=30, store=self.s2, salary=30000, ), Employee( first_name="Jo", last_name="Smith", age=55, store=self.s3, salary=50000, ), ] ) employees = Employee.objects.annotate( store_opened_year=F("store__original_opening__year"), ) for employee in employees: self.assertEqual( employee.store_opened_year, employee.store.original_opening.year, ) def test_custom_transform_annotation(self): with register_lookup(DecimalField, Floor): books = Book.objects.annotate(floor_price=F("price__floor")) self.assertCountEqual( books.values_list("pk", "floor_price"), [ (self.b1.pk, 30), (self.b2.pk, 23), (self.b3.pk, 29), (self.b4.pk, 29), (self.b5.pk, 82), (self.b6.pk, 75), ], ) def test_chaining_transforms(self): Company.objects.create(name=" Django Software Foundation ") Company.objects.create(name="Yahoo") with register_lookup(CharField, Trim), register_lookup(CharField, Length): for expr in [Length("name__trim"), F("name__trim__length")]: with self.subTest(expr=expr): self.assertCountEqual( Company.objects.annotate(length=expr).values("name", "length"), [ {"name": " Django Software Foundation ", "length": 26}, {"name": "Yahoo", "length": 5}, ], ) def test_mixed_type_annotation_date_interval(self): active = datetime.datetime(2015, 3, 20, 14, 0, 0) duration = datetime.timedelta(hours=1) expires = datetime.datetime(2015, 3, 20, 14, 0, 0) + duration Ticket.objects.create(active_at=active, duration=duration) t = Ticket.objects.annotate( expires=ExpressionWrapper( F("active_at") + F("duration"), output_field=DateTimeField() ) ).first() self.assertEqual(t.expires, expires) def test_mixed_type_annotation_numbers(self): test = self.b1 b = Book.objects.annotate( combined=ExpressionWrapper( F("pages") + F("rating"), output_field=IntegerField() ) ).get(isbn=test.isbn) combined = int(test.pages + test.rating) self.assertEqual(b.combined, combined) def test_empty_expression_annotation(self): books = Book.objects.annotate( selected=ExpressionWrapper(Q(pk__in=[]), output_field=BooleanField()) ) self.assertEqual(len(books), Book.objects.count()) self.assertTrue(all(not book.selected for book in books)) books = Book.objects.annotate( selected=ExpressionWrapper( Q(pk__in=Book.objects.none()), output_field=BooleanField() ) ) self.assertEqual(len(books), Book.objects.count()) self.assertTrue(all(not book.selected for book in books)) def test_full_expression_annotation(self): books = Book.objects.annotate( selected=ExpressionWrapper(~Q(pk__in=[]), output_field=BooleanField()), ) self.assertEqual(len(books), Book.objects.count()) self.assertTrue(all(book.selected for book in books)) def test_full_expression_wrapped_annotation(self): books = Book.objects.annotate( selected=Coalesce(~Q(pk__in=[]), True), ) self.assertEqual(len(books), Book.objects.count()) self.assertTrue(all(book.selected for book in books)) def test_full_expression_annotation_with_aggregation(self): qs = Book.objects.filter(isbn="159059725").annotate( selected=ExpressionWrapper(~Q(pk__in=[]), output_field=BooleanField()), rating_count=Count("rating"), ) self.assertEqual([book.rating_count for book in qs], [1]) def test_aggregate_over_full_expression_annotation(self): qs = Book.objects.annotate( selected=ExpressionWrapper(~Q(pk__in=[]), output_field=BooleanField()), ).aggregate(selected__sum=Sum(Cast("selected", IntegerField()))) self.assertEqual(qs["selected__sum"], Book.objects.count()) def test_empty_queryset_annotation(self): qs = Author.objects.annotate(empty=Subquery(Author.objects.values("id").none())) self.assertIsNone(qs.first().empty) def test_annotate_with_aggregation(self): books = Book.objects.annotate(is_book=Value(1), rating_count=Count("rating")) for book in books: self.assertEqual(book.is_book, 1) self.assertEqual(book.rating_count, 1) def test_combined_expression_annotation_with_aggregation(self): book = Book.objects.annotate( combined=ExpressionWrapper( Value(3) * Value(4), output_field=IntegerField() ), rating_count=Count("rating"), ).first() self.assertEqual(book.combined, 12) self.assertEqual(book.rating_count, 1) def test_combined_f_expression_annotation_with_aggregation(self): book = ( Book.objects.filter(isbn="159059725") .annotate( combined=ExpressionWrapper( F("price") * F("pages"), output_field=FloatField() ), rating_count=Count("rating"), ) .first() ) self.assertEqual(book.combined, 13410.0) self.assertEqual(book.rating_count, 1) @skipUnlessDBFeature("supports_boolean_expr_in_select_clause") def test_q_expression_annotation_with_aggregation(self): book = ( Book.objects.filter(isbn="159059725") .annotate( isnull_pubdate=ExpressionWrapper( Q(pubdate__isnull=True), output_field=BooleanField(), ), rating_count=Count("rating"), ) .first() ) self.assertIs(book.isnull_pubdate, False) self.assertEqual(book.rating_count, 1) @skipUnlessDBFeature("supports_boolean_expr_in_select_clause") def test_grouping_by_q_expression_annotation(self): authors = ( Author.objects.annotate( under_40=ExpressionWrapper(Q(age__lt=40), output_field=BooleanField()), ) .values("under_40") .annotate( count_id=Count("id"), ) .values("under_40", "count_id") ) self.assertCountEqual( authors, [ {"under_40": False, "count_id": 3}, {"under_40": True, "count_id": 6}, ], ) def test_aggregate_over_annotation(self): agg = Author.objects.annotate(other_age=F("age")).aggregate( otherage_sum=Sum("other_age") ) other_agg = Author.objects.aggregate(age_sum=Sum("age")) self.assertEqual(agg["otherage_sum"], other_agg["age_sum"]) @skipUnlessDBFeature("can_distinct_on_fields") def test_distinct_on_with_annotation(self): store = Store.objects.create( name="test store", original_opening=datetime.datetime.now(), friday_night_closing=datetime.time(21, 00, 00), ) names = [ "Theodore Roosevelt", "Eleanor Roosevelt", "Franklin Roosevelt", "Ned Stark", "Catelyn Stark", ] for name in names: Employee.objects.create( store=store, first_name=name.split()[0], last_name=name.split()[1], age=30, salary=2000, ) people = Employee.objects.annotate( name_lower=Lower("last_name"), ).distinct("name_lower") self.assertEqual({p.last_name for p in people}, {"Stark", "Roosevelt"}) self.assertEqual(len(people), 2) people2 = Employee.objects.annotate( test_alias=F("store__name"), ).distinct("test_alias") self.assertEqual(len(people2), 1) lengths = ( Employee.objects.annotate( name_len=Length("first_name"), ) .distinct("name_len") .values_list("name_len", flat=True) ) self.assertCountEqual(lengths, [3, 7, 8]) def test_filter_annotation(self): books = Book.objects.annotate(is_book=Value(1)).filter(is_book=1) for book in books: self.assertEqual(book.is_book, 1) def test_filter_annotation_with_f(self): books = Book.objects.annotate(other_rating=F("rating")).filter(other_rating=3.5) for book in books: self.assertEqual(book.other_rating, 3.5) def test_filter_annotation_with_double_f(self): books = Book.objects.annotate(other_rating=F("rating")).filter( other_rating=F("rating") ) for book in books: self.assertEqual(book.other_rating, book.rating) def test_filter_agg_with_double_f(self): books = Book.objects.annotate(sum_rating=Sum("rating")).filter( sum_rating=F("sum_rating") ) for book in books: self.assertEqual(book.sum_rating, book.rating) def test_filter_wrong_annotation(self): with self.assertRaisesMessage( FieldError, "Cannot resolve keyword 'nope' into field." ): list( Book.objects.annotate(sum_rating=Sum("rating")).filter( sum_rating=F("nope") ) ) def test_values_wrong_annotation(self): expected_message = ( "Cannot resolve keyword 'annotation_typo' into field. Choices are: %s" ) article_fields = ", ".join( ["annotation"] + sorted(get_field_names_from_opts(Book._meta)) ) with self.assertRaisesMessage(FieldError, expected_message % article_fields): Book.objects.annotate(annotation=Value(1)).values_list("annotation_typo") def test_decimal_annotation(self): salary = Decimal(10) ** -Employee._meta.get_field("salary").decimal_places Employee.objects.create( first_name="Max", last_name="Paine", store=Store.objects.first(), age=23, salary=salary, ) self.assertEqual( Employee.objects.annotate(new_salary=F("salary") / 10).get().new_salary, salary / 10, ) def test_filter_decimal_annotation(self): qs = ( Book.objects.annotate(new_price=F("price") + 1) .filter(new_price=Decimal(31)) .values_list("new_price") ) self.assertEqual(qs.get(), (Decimal(31),)) def test_combined_annotation_commutative(self): book1 = Book.objects.annotate(adjusted_rating=F("rating") + 2).get( pk=self.b1.pk ) book2 = Book.objects.annotate(adjusted_rating=2 + F("rating")).get( pk=self.b1.pk ) self.assertEqual(book1.adjusted_rating, book2.adjusted_rating) book1 = Book.objects.annotate(adjusted_rating=F("rating") + None).get( pk=self.b1.pk ) book2 = Book.objects.annotate(adjusted_rating=None + F("rating")).get( pk=self.b1.pk ) self.assertIs(book1.adjusted_rating, None) self.assertEqual(book1.adjusted_rating, book2.adjusted_rating) def test_update_with_annotation(self): book_preupdate = Book.objects.get(pk=self.b2.pk) Book.objects.annotate(other_rating=F("rating") - 1).update( rating=F("other_rating") ) book_postupdate = Book.objects.get(pk=self.b2.pk) self.assertEqual(book_preupdate.rating - 1, book_postupdate.rating) def test_annotation_with_m2m(self): books = ( Book.objects.annotate(author_age=F("authors__age")) .filter(pk=self.b1.pk) .order_by("author_age") ) self.assertEqual(books[0].author_age, 34) self.assertEqual(books[1].author_age, 35) def test_annotation_reverse_m2m(self): books = ( Book.objects.annotate( store_name=F("store__name"), ) .filter( name="Practical Django Projects", ) .order_by("store_name") ) self.assertQuerySetEqual( books, ["Amazon.com", "Books.com", "Mamma and Pappa's Books"], lambda b: b.store_name, ) def test_values_annotation(self): """ Annotations can reference fields in a values clause, and contribute to an existing values clause. """ # annotate references a field in values() qs = Book.objects.values("rating").annotate(other_rating=F("rating") - 1) book = qs.get(pk=self.b1.pk) self.assertEqual(book["rating"] - 1, book["other_rating"]) # filter refs the annotated value book = qs.get(other_rating=4) self.assertEqual(book["other_rating"], 4) # can annotate an existing values with a new field book = qs.annotate(other_isbn=F("isbn")).get(other_rating=4) self.assertEqual(book["other_rating"], 4) self.assertEqual(book["other_isbn"], "155860191") def test_values_with_pk_annotation(self): # annotate references a field in values() with pk publishers = Publisher.objects.values("id", "book__rating").annotate( total=Sum("book__rating") ) for publisher in publishers.filter(pk=self.p1.pk): self.assertEqual(publisher["book__rating"], publisher["total"]) def test_defer_annotation(self): """ Deferred attributes can be referenced by an annotation, but they are not themselves deferred, and cannot be deferred. """ qs = Book.objects.defer("rating").annotate(other_rating=F("rating") - 1) with self.assertNumQueries(2): book = qs.get(other_rating=4) self.assertEqual(book.rating, 5) self.assertEqual(book.other_rating, 4) with self.assertRaisesMessage( FieldDoesNotExist, "Book has no field named 'other_rating'" ): book = qs.defer("other_rating").get(other_rating=4) def test_mti_annotations(self): """ Fields on an inherited model can be referenced by an annotated field. """ d = DepartmentStore.objects.create( name="Angus & Robinson", original_opening=datetime.date(2014, 3, 8), friday_night_closing=datetime.time(21, 00, 00), chain="Westfield", ) books = Book.objects.filter(rating__gt=4) for b in books: d.books.add(b) qs = ( DepartmentStore.objects.annotate( other_name=F("name"), other_chain=F("chain"), is_open=Value(True, BooleanField()), book_isbn=F("books__isbn"), ) .order_by("book_isbn") .filter(chain="Westfield") ) self.assertQuerySetEqual( qs, [ ("Angus & Robinson", "Westfield", True, "155860191"), ("Angus & Robinson", "Westfield", True, "159059725"), ], lambda d: (d.other_name, d.other_chain, d.is_open, d.book_isbn), ) def test_null_annotation(self): """ Annotating None onto a model round-trips """ book = Book.objects.annotate( no_value=Value(None, output_field=IntegerField()) ).first() self.assertIsNone(book.no_value) def test_order_by_annotation(self): authors = Author.objects.annotate(other_age=F("age")).order_by("other_age") self.assertQuerySetEqual( authors, [ 25, 29, 29, 34, 35, 37, 45, 46, 57, ], lambda a: a.other_age, ) def test_order_by_aggregate(self): authors = ( Author.objects.values("age") .annotate(age_count=Count("age")) .order_by("age_count", "age") ) self.assertQuerySetEqual( authors, [ (25, 1), (34, 1), (35, 1), (37, 1), (45, 1), (46, 1), (57, 1), (29, 2), ], lambda a: (a["age"], a["age_count"]), ) def test_raw_sql_with_inherited_field(self): DepartmentStore.objects.create( name="Angus & Robinson", original_opening=datetime.date(2014, 3, 8), friday_night_closing=datetime.time(21), chain="Westfield", area=123, ) tests = ( ("name", "Angus & Robinson"), ("surface", 123), ("case when name='Angus & Robinson' then chain else name end", "Westfield"), ) for sql, expected_result in tests: with self.subTest(sql=sql): self.assertSequenceEqual( DepartmentStore.objects.annotate( annotation=RawSQL(sql, ()), ).values_list("annotation", flat=True), [expected_result], ) def test_annotate_exists(self): authors = Author.objects.annotate(c=Count("id")).filter(c__gt=1) self.assertFalse(authors.exists()) def test_column_field_ordering(self): """ Columns are aligned in the correct order for resolve_columns. This test will fail on MySQL if column ordering is out. Column fields should be aligned as: 1. extra_select 2. model_fields 3. annotation_fields 4. model_related_fields """ store = Store.objects.first() Employee.objects.create( id=1, first_name="Max", manager=True, last_name="Paine", store=store, age=23, salary=Decimal(50000.00), ) Employee.objects.create( id=2, first_name="Buffy", manager=False, last_name="Summers", store=store, age=18, salary=Decimal(40000.00), ) qs = ( Employee.objects.extra(select={"random_value": "42"}) .select_related("store") .annotate( annotated_value=Value(17), ) ) rows = [ (1, "Max", True, 42, "Paine", 23, Decimal(50000.00), store.name, 17), (2, "Buffy", False, 42, "Summers", 18, Decimal(40000.00), store.name, 17), ] self.assertQuerySetEqual( qs.order_by("id"), rows, lambda e: ( e.id, e.first_name, e.manager, e.random_value, e.last_name, e.age, e.salary, e.store.name, e.annotated_value, ), ) def test_column_field_ordering_with_deferred(self): store = Store.objects.first() Employee.objects.create( id=1, first_name="Max", manager=True, last_name="Paine", store=store, age=23, salary=Decimal(50000.00), ) Employee.objects.create( id=2, first_name="Buffy", manager=False, last_name="Summers", store=store, age=18, salary=Decimal(40000.00), ) qs = ( Employee.objects.extra(select={"random_value": "42"}) .select_related("store") .annotate( annotated_value=Value(17), ) ) rows = [ (1, "Max", True, 42, "Paine", 23, Decimal(50000.00), store.name, 17), (2, "Buffy", False, 42, "Summers", 18, Decimal(40000.00), store.name, 17), ] # and we respect deferred columns! self.assertQuerySetEqual( qs.defer("age").order_by("id"), rows, lambda e: ( e.id, e.first_name, e.manager, e.random_value, e.last_name, e.age, e.salary, e.store.name, e.annotated_value, ), ) def test_custom_functions(self): Company( name="Apple", motto=None, ticker_name="APPL", description="Beautiful Devices", ).save() Company( name="Django Software Foundation", motto=None, ticker_name=None, description=None, ).save() Company( name="Google", motto="Do No Evil", ticker_name="GOOG", description="Internet Company", ).save() Company( name="Yahoo", motto=None, ticker_name=None, description="Internet Company" ).save() qs = Company.objects.annotate( tagline=Func( F("motto"), F("ticker_name"), F("description"), Value("No Tag"), function="COALESCE", ) ).order_by("name") self.assertQuerySetEqual( qs, [ ("Apple", "APPL"), ("Django Software Foundation", "No Tag"), ("Google", "Do No Evil"), ("Yahoo", "Internet Company"), ], lambda c: (c.name, c.tagline), ) def test_custom_functions_can_ref_other_functions(self): Company( name="Apple", motto=None, ticker_name="APPL", description="Beautiful Devices", ).save() Company( name="Django Software Foundation", motto=None, ticker_name=None, description=None, ).save() Company( name="Google", motto="Do No Evil", ticker_name="GOOG", description="Internet Company", ).save() Company( name="Yahoo", motto=None, ticker_name=None, description="Internet Company" ).save() class Lower(Func): function = "LOWER" qs = ( Company.objects.annotate( tagline=Func( F("motto"), F("ticker_name"), F("description"), Value("No Tag"), function="COALESCE", ) ) .annotate( tagline_lower=Lower(F("tagline")), ) .order_by("name") ) # LOWER function supported by: # oracle, postgres, mysql, sqlite, sqlserver self.assertQuerySetEqual( qs, [ ("Apple", "APPL".lower()), ("Django Software Foundation", "No Tag".lower()), ("Google", "Do No Evil".lower()), ("Yahoo", "Internet Company".lower()), ], lambda c: (c.name, c.tagline_lower), ) def test_boolean_value_annotation(self): books = Book.objects.annotate( is_book=Value(True, output_field=BooleanField()), is_pony=Value(False, output_field=BooleanField()), is_none=Value(None, output_field=BooleanField(null=True)), ) self.assertGreater(len(books), 0) for book in books: self.assertIs(book.is_book, True) self.assertIs(book.is_pony, False) self.assertIsNone(book.is_none) def test_annotation_in_f_grouped_by_annotation(self): qs = ( Publisher.objects.annotate(multiplier=Value(3)) # group by option => sum of value * multiplier .values("name") .annotate(multiplied_value_sum=Sum(F("multiplier") * F("num_awards"))) .order_by() ) self.assertCountEqual( qs, [ {"multiplied_value_sum": 9, "name": "Apress"}, {"multiplied_value_sum": 0, "name": "Jonno's House of Books"}, {"multiplied_value_sum": 27, "name": "Morgan Kaufmann"}, {"multiplied_value_sum": 21, "name": "Prentice Hall"}, {"multiplied_value_sum": 3, "name": "Sams"}, ], ) def test_arguments_must_be_expressions(self): msg = "QuerySet.annotate() received non-expression(s): %s." with self.assertRaisesMessage(TypeError, msg % BooleanField()): Book.objects.annotate(BooleanField()) with self.assertRaisesMessage(TypeError, msg % True): Book.objects.annotate(is_book=True) with self.assertRaisesMessage( TypeError, msg % ", ".join([str(BooleanField()), "True"]) ): Book.objects.annotate(BooleanField(), Value(False), is_book=True) def test_chaining_annotation_filter_with_m2m(self): qs = ( Author.objects.filter( name="Adrian Holovaty", friends__age=35, ) .annotate( jacob_name=F("friends__name"), ) .filter( friends__age=29, ) .annotate( james_name=F("friends__name"), ) .values("jacob_name", "james_name") ) self.assertCountEqual( qs, [{"jacob_name": "Jacob Kaplan-Moss", "james_name": "James Bennett"}], ) def test_annotation_filter_with_subquery(self): long_books_qs = ( Book.objects.filter( publisher=OuterRef("pk"), pages__gt=400, ) .values("publisher") .annotate(count=Count("pk")) .values("count") ) publisher_books_qs = ( Publisher.objects.annotate( total_books=Count("book"), ) .filter( total_books=Subquery(long_books_qs, output_field=IntegerField()), ) .values("name") ) self.assertCountEqual( publisher_books_qs, [{"name": "Sams"}, {"name": "Morgan Kaufmann"}] ) def test_annotation_and_alias_filter_in_subquery(self): awarded_publishers_qs = ( Publisher.objects.filter(num_awards__gt=4) .annotate(publisher_annotate=Value(1)) .alias(publisher_alias=Value(1)) ) qs = Publisher.objects.filter(pk__in=awarded_publishers_qs) self.assertCountEqual(qs, [self.p3, self.p4]) def test_annotation_and_alias_filter_related_in_subquery(self): long_books_qs = ( Book.objects.filter(pages__gt=400) .annotate(book_annotate=Value(1)) .alias(book_alias=Value(1)) ) publisher_books_qs = Publisher.objects.filter( book__in=long_books_qs, ).values("name") self.assertCountEqual( publisher_books_qs, [ {"name": "Apress"}, {"name": "Sams"}, {"name": "Prentice Hall"}, {"name": "Morgan Kaufmann"}, ], ) def test_annotation_exists_none_query(self): self.assertIs( Author.objects.annotate(exists=Exists(Company.objects.none())) .get(pk=self.a1.pk) .exists, False, ) def test_annotation_exists_aggregate_values_chaining(self): qs = ( Book.objects.values("publisher") .annotate( has_authors=Exists( Book.authors.through.objects.filter(book=OuterRef("pk")) ), max_pubdate=Max("pubdate"), ) .values_list("max_pubdate", flat=True) .order_by("max_pubdate") ) self.assertCountEqual( qs, [ datetime.date(1991, 10, 15), datetime.date(2008, 3, 3), datetime.date(2008, 6, 23), datetime.date(2008, 11, 3), ], ) @skipUnlessDBFeature("supports_subqueries_in_group_by") def test_annotation_subquery_and_aggregate_values_chaining(self): qs = ( Book.objects.annotate(pub_year=ExtractYear("pubdate")) .values("pub_year") .annotate( top_rating=Subquery( Book.objects.filter(pubdate__year=OuterRef("pub_year")) .order_by("-rating") .values("rating")[:1] ), total_pages=Sum("pages"), ) .values("pub_year", "total_pages", "top_rating") ) self.assertCountEqual( qs, [ {"pub_year": 1991, "top_rating": 5.0, "total_pages": 946}, {"pub_year": 1995, "top_rating": 4.0, "total_pages": 1132}, {"pub_year": 2007, "top_rating": 4.5, "total_pages": 447}, {"pub_year": 2008, "top_rating": 4.0, "total_pages": 1178}, ], ) def test_annotation_subquery_outerref_transform(self): qs = Book.objects.annotate( top_rating_year=Subquery( Book.objects.filter(pubdate__year=OuterRef("pubdate__year")) .order_by("-rating") .values("rating")[:1] ), ).values("pubdate__year", "top_rating_year") self.assertCountEqual( qs, [ {"pubdate__year": 1991, "top_rating_year": 5.0}, {"pubdate__year": 1995, "top_rating_year": 4.0}, {"pubdate__year": 2007, "top_rating_year": 4.5}, {"pubdate__year": 2008, "top_rating_year": 4.0}, {"pubdate__year": 2008, "top_rating_year": 4.0}, {"pubdate__year": 2008, "top_rating_year": 4.0}, ], ) def test_annotation_aggregate_with_m2o(self): qs = ( Author.objects.filter(age__lt=30) .annotate( max_pages=Case( When(book_contact_set__isnull=True, then=Value(0)), default=Max(F("book__pages")), ), ) .values("name", "max_pages") ) self.assertCountEqual( qs, [ {"name": "James Bennett", "max_pages": 300}, {"name": "Paul Bissex", "max_pages": 0}, {"name": "Wesley J. Chun", "max_pages": 0}, ], ) def test_alias_sql_injection(self): crafted_alias = """injected_name" from "annotations_book"; --""" msg = ( "Column aliases cannot contain whitespace characters, quotation marks, " "semicolons, or SQL comments." ) with self.assertRaisesMessage(ValueError, msg): Book.objects.annotate(**{crafted_alias: Value(1)}) def test_alias_forbidden_chars(self): tests = [ 'al"ias', "a'lias", "ali`as", "alia s", "alias\t", "ali\nas", "alias--", "ali/*as", "alias*/", "alias;", # [] are used by MSSQL. "alias[", "alias]", ] msg = ( "Column aliases cannot contain whitespace characters, quotation marks, " "semicolons, or SQL comments." ) for crafted_alias in tests: with self.subTest(crafted_alias): with self.assertRaisesMessage(ValueError, msg): Book.objects.annotate(**{crafted_alias: Value(1)}) class AliasTests(TestCase): @classmethod def setUpTestData(cls): cls.a1 = Author.objects.create(name="Adrian Holovaty", age=34) cls.a2 = Author.objects.create(name="Jacob Kaplan-Moss", age=35) cls.a3 = Author.objects.create(name="James Bennett", age=34) cls.a4 = Author.objects.create(name="Peter Norvig", age=57) cls.a5 = Author.objects.create(name="Stuart Russell", age=46) p1 = Publisher.objects.create(name="Apress", num_awards=3) cls.b1 = Book.objects.create( isbn="159059725", pages=447, rating=4.5, price=Decimal("30.00"), contact=cls.a1, publisher=p1, pubdate=datetime.date(2007, 12, 6), name="The Definitive Guide to Django: Web Development Done Right", ) cls.b2 = Book.objects.create( isbn="159059996", pages=300, rating=4.0, price=Decimal("29.69"), contact=cls.a3, publisher=p1, pubdate=datetime.date(2008, 6, 23), name="Practical Django Projects", ) cls.b3 = Book.objects.create( isbn="013790395", pages=1132, rating=4.0, price=Decimal("82.80"), contact=cls.a4, publisher=p1, pubdate=datetime.date(1995, 1, 15), name="Artificial Intelligence: A Modern Approach", ) cls.b4 = Book.objects.create( isbn="155860191", pages=946, rating=5.0, price=Decimal("75.00"), contact=cls.a4, publisher=p1, pubdate=datetime.date(1991, 10, 15), name=( "Paradigms of Artificial Intelligence Programming: Case Studies in " "Common Lisp" ), ) cls.b1.authors.add(cls.a1, cls.a2) cls.b2.authors.add(cls.a3) cls.b3.authors.add(cls.a4, cls.a5) cls.b4.authors.add(cls.a4) Store.objects.create( name="Amazon.com", original_opening=datetime.datetime(1994, 4, 23, 9, 17, 42), friday_night_closing=datetime.time(23, 59, 59), ) Store.objects.create( name="Books.com", original_opening=datetime.datetime(2001, 3, 15, 11, 23, 37), friday_night_closing=datetime.time(23, 59, 59), ) def test_basic_alias(self): qs = Book.objects.alias(is_book=Value(1)) self.assertIs(hasattr(qs.first(), "is_book"), False) def test_basic_alias_annotation(self): qs = Book.objects.alias( is_book_alias=Value(1), ).annotate(is_book=F("is_book_alias")) self.assertIs(hasattr(qs.first(), "is_book_alias"), False) for book in qs: with self.subTest(book=book): self.assertEqual(book.is_book, 1) def test_basic_alias_f_annotation(self): qs = Book.objects.alias(another_rating_alias=F("rating")).annotate( another_rating=F("another_rating_alias") ) self.assertIs(hasattr(qs.first(), "another_rating_alias"), False) for book in qs: with self.subTest(book=book): self.assertEqual(book.another_rating, book.rating) def test_basic_alias_f_transform_annotation(self): qs = Book.objects.alias( pubdate_alias=F("pubdate"), ).annotate(pubdate_year=F("pubdate_alias__year")) self.assertIs(hasattr(qs.first(), "pubdate_alias"), False) for book in qs: with self.subTest(book=book): self.assertEqual(book.pubdate_year, book.pubdate.year) def test_alias_after_annotation(self): qs = Book.objects.annotate( is_book=Value(1), ).alias(is_book_alias=F("is_book")) book = qs.first() self.assertIs(hasattr(book, "is_book"), True) self.assertIs(hasattr(book, "is_book_alias"), False) def test_overwrite_annotation_with_alias(self): qs = Book.objects.annotate(is_book=Value(1)).alias(is_book=F("is_book")) self.assertIs(hasattr(qs.first(), "is_book"), False) def test_overwrite_alias_with_annotation(self): qs = Book.objects.alias(is_book=Value(1)).annotate(is_book=F("is_book")) for book in qs: with self.subTest(book=book): self.assertEqual(book.is_book, 1) def test_alias_annotation_expression(self): qs = Book.objects.alias( is_book_alias=Value(1), ).annotate(is_book=Coalesce("is_book_alias", 0)) self.assertIs(hasattr(qs.first(), "is_book_alias"), False) for book in qs: with self.subTest(book=book): self.assertEqual(book.is_book, 1) def test_alias_default_alias_expression(self): qs = Author.objects.alias( Sum("book__pages"), ).filter(book__pages__sum__gt=2000) self.assertIs(hasattr(qs.first(), "book__pages__sum"), False) self.assertSequenceEqual(qs, [self.a4]) def test_joined_alias_annotation(self): qs = ( Book.objects.select_related("publisher") .alias( num_awards_alias=F("publisher__num_awards"), ) .annotate(num_awards=F("num_awards_alias")) ) self.assertIs(hasattr(qs.first(), "num_awards_alias"), False) for book in qs: with self.subTest(book=book): self.assertEqual(book.num_awards, book.publisher.num_awards) def test_alias_annotate_with_aggregation(self): qs = Book.objects.alias( is_book_alias=Value(1), rating_count_alias=Count("rating"), ).annotate( is_book=F("is_book_alias"), rating_count=F("rating_count_alias"), ) book = qs.first() self.assertIs(hasattr(book, "is_book_alias"), False) self.assertIs(hasattr(book, "rating_count_alias"), False) for book in qs: with self.subTest(book=book): self.assertEqual(book.is_book, 1) self.assertEqual(book.rating_count, 1) def test_filter_alias_with_f(self): qs = Book.objects.alias( other_rating=F("rating"), ).filter(other_rating=4.5) self.assertIs(hasattr(qs.first(), "other_rating"), False) self.assertSequenceEqual(qs, [self.b1]) def test_filter_alias_with_double_f(self): qs = Book.objects.alias( other_rating=F("rating"), ).filter(other_rating=F("rating")) self.assertIs(hasattr(qs.first(), "other_rating"), False) self.assertEqual(qs.count(), Book.objects.count()) def test_filter_alias_agg_with_double_f(self): qs = Book.objects.alias( sum_rating=Sum("rating"), ).filter(sum_rating=F("sum_rating")) self.assertIs(hasattr(qs.first(), "sum_rating"), False) self.assertEqual(qs.count(), Book.objects.count()) def test_update_with_alias(self): Book.objects.alias( other_rating=F("rating") - 1, ).update(rating=F("other_rating")) self.b1.refresh_from_db() self.assertEqual(self.b1.rating, 3.5) def test_order_by_alias(self): qs = Author.objects.alias(other_age=F("age")).order_by("other_age") self.assertIs(hasattr(qs.first(), "other_age"), False) self.assertQuerySetEqual(qs, [34, 34, 35, 46, 57], lambda a: a.age) def test_order_by_alias_aggregate(self): qs = ( Author.objects.values("age") .alias(age_count=Count("age")) .order_by("age_count", "age") ) self.assertIs(hasattr(qs.first(), "age_count"), False) self.assertQuerySetEqual(qs, [35, 46, 57, 34], lambda a: a["age"]) def test_dates_alias(self): qs = Book.objects.alias( pubdate_alias=F("pubdate"), ).dates("pubdate_alias", "month") self.assertCountEqual( qs, [ datetime.date(1991, 10, 1), datetime.date(1995, 1, 1), datetime.date(2007, 12, 1), datetime.date(2008, 6, 1), ], ) def test_datetimes_alias(self): qs = Store.objects.alias( original_opening_alias=F("original_opening"), ).datetimes("original_opening_alias", "year") self.assertCountEqual( qs, [ datetime.datetime(1994, 1, 1), datetime.datetime(2001, 1, 1), ], ) def test_aggregate_alias(self): msg = ( "Cannot aggregate over the 'other_age' alias. Use annotate() to promote it." ) with self.assertRaisesMessage(FieldError, msg): Author.objects.alias( other_age=F("age"), ).aggregate(otherage_sum=Sum("other_age")) def test_defer_only_alias(self): qs = Book.objects.alias(rating_alias=F("rating") - 1) msg = "Book has no field named 'rating_alias'" for operation in ["defer", "only"]: with self.subTest(operation=operation): with self.assertRaisesMessage(FieldDoesNotExist, msg): getattr(qs, operation)("rating_alias").first() @skipUnlessDBFeature("can_distinct_on_fields") def test_distinct_on_alias(self): qs = Book.objects.alias(rating_alias=F("rating") - 1) msg = "Cannot resolve keyword 'rating_alias' into field." with self.assertRaisesMessage(FieldError, msg): qs.distinct("rating_alias").first() def test_values_alias(self): qs = Book.objects.alias(rating_alias=F("rating") - 1) msg = "Cannot select the 'rating_alias' alias. Use annotate() to promote it." for operation in ["values", "values_list"]: with self.subTest(operation=operation): with self.assertRaisesMessage(FieldError, msg): getattr(qs, operation)("rating_alias") def test_alias_sql_injection(self): crafted_alias = """injected_name" from "annotations_book"; --""" msg = ( "Column aliases cannot contain whitespace characters, quotation marks, " "semicolons, or SQL comments." ) with self.assertRaisesMessage(ValueError, msg): Book.objects.alias(**{crafted_alias: Value(1)})
1d38be11828cf47e1eae99e3f98e86b1c48502aacebe0532b0d4285b08164fd2
import asyncio import sys import threading from pathlib import Path from asgiref.testing import ApplicationCommunicator from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler from django.core.asgi import get_asgi_application from django.core.signals import request_finished, request_started from django.db import close_old_connections from django.test import ( AsyncRequestFactory, SimpleTestCase, ignore_warnings, modify_settings, override_settings, ) from django.utils.http import http_date from .urls import sync_waiter, test_filename TEST_STATIC_ROOT = Path(__file__).parent / "project" / "static" @override_settings(ROOT_URLCONF="asgi.urls") class ASGITest(SimpleTestCase): async_request_factory = AsyncRequestFactory() def setUp(self): request_started.disconnect(close_old_connections) def tearDown(self): request_started.connect(close_old_connections) async def test_get_asgi_application(self): """ get_asgi_application() returns a functioning ASGI callable. """ application = get_asgi_application() # Construct HTTP request. scope = self.async_request_factory._base_scope(path="/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) # Read the response. response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) self.assertEqual( set(response_start["headers"]), { (b"Content-Length", b"12"), (b"Content-Type", b"text/html; charset=utf-8"), }, ) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello World!") # Allow response.close() to finish. await communicator.wait() # Python's file API is not async compatible. A third-party library such # as https://github.com/Tinche/aiofiles allows passing the file to # FileResponse as an async iterator. With a sync iterator # StreamingHTTPResponse triggers a warning when iterating the file. # assertWarnsMessage is not async compatible, so ignore_warnings for the # test. @ignore_warnings(module="django.http.response") async def test_file_response(self): """ Makes sure that FileResponse works over ASGI. """ application = get_asgi_application() # Construct HTTP request. scope = self.async_request_factory._base_scope(path="/file/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) # Get the file content. with open(test_filename, "rb") as test_file: test_file_contents = test_file.read() # Read the response. response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) headers = response_start["headers"] self.assertEqual(len(headers), 3) expected_headers = { b"Content-Length": str(len(test_file_contents)).encode("ascii"), b"Content-Type": b"text/x-python", b"Content-Disposition": b'inline; filename="urls.py"', } for key, value in headers: try: self.assertEqual(value, expected_headers[key]) except AssertionError: # Windows registry may not be configured with correct # mimetypes. if sys.platform == "win32" and key == b"Content-Type": self.assertEqual(value, b"text/plain") else: raise # Warning ignored here. response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], test_file_contents) # Allow response.close() to finish. await communicator.wait() @modify_settings(INSTALLED_APPS={"append": "django.contrib.staticfiles"}) @override_settings( STATIC_URL="static/", STATIC_ROOT=TEST_STATIC_ROOT, STATICFILES_DIRS=[TEST_STATIC_ROOT], STATICFILES_FINDERS=[ "django.contrib.staticfiles.finders.FileSystemFinder", ], ) async def test_static_file_response(self): application = ASGIStaticFilesHandler(get_asgi_application()) # Construct HTTP request. scope = self.async_request_factory._base_scope(path="/static/file.txt") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) # Get the file content. file_path = TEST_STATIC_ROOT / "file.txt" with open(file_path, "rb") as test_file: test_file_contents = test_file.read() # Read the response. stat = file_path.stat() response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) self.assertEqual( set(response_start["headers"]), { (b"Content-Length", str(len(test_file_contents)).encode("ascii")), (b"Content-Type", b"text/plain"), (b"Content-Disposition", b'inline; filename="file.txt"'), (b"Last-Modified", http_date(stat.st_mtime).encode("ascii")), }, ) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], test_file_contents) # Allow response.close() to finish. await communicator.wait() async def test_headers(self): application = get_asgi_application() communicator = ApplicationCommunicator( application, self.async_request_factory._base_scope( path="/meta/", headers=[ [b"content-type", b"text/plain; charset=utf-8"], [b"content-length", b"77"], [b"referer", b"Scotland"], [b"referer", b"Wales"], ], ), ) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) self.assertEqual( set(response_start["headers"]), { (b"Content-Length", b"19"), (b"Content-Type", b"text/plain; charset=utf-8"), }, ) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"From Scotland,Wales") # Allow response.close() to finish await communicator.wait() async def test_post_body(self): application = get_asgi_application() scope = self.async_request_factory._base_scope( method="POST", path="/post/", query_string="echo=1", ) communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request", "body": b"Echo!"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Echo!") async def test_untouched_request_body_gets_closed(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(method="POST", path="/post/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 204) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"") # Allow response.close() to finish await communicator.wait() async def test_get_query_string(self): application = get_asgi_application() for query_string in (b"name=Andrew", "name=Andrew"): with self.subTest(query_string=query_string): scope = self.async_request_factory._base_scope( path="/", query_string=query_string, ) communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello Andrew!") # Allow response.close() to finish await communicator.wait() async def test_disconnect(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.disconnect"}) with self.assertRaises(asyncio.TimeoutError): await communicator.receive_output() async def test_wrong_connection_type(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/", type="other") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) msg = "Django can only handle ASGI/HTTP connections, not other." with self.assertRaisesMessage(ValueError, msg): await communicator.receive_output() async def test_non_unicode_query_string(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/", query_string=b"\xff") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 400) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"") async def test_request_lifecycle_signals_dispatched_with_thread_sensitive(self): class SignalHandler: """Track threads handler is dispatched on.""" threads = [] def __call__(self, **kwargs): self.threads.append(threading.current_thread()) signal_handler = SignalHandler() request_started.connect(signal_handler) request_finished.connect(signal_handler) # Perform a basic request. application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello World!") # Give response.close() time to finish. await communicator.wait() # AsyncToSync should have executed the signals in the same thread. request_started_thread, request_finished_thread = signal_handler.threads self.assertEqual(request_started_thread, request_finished_thread) request_started.disconnect(signal_handler) request_finished.disconnect(signal_handler) async def test_concurrent_async_uses_multiple_thread_pools(self): sync_waiter.active_threads.clear() # Send 2 requests concurrently application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/wait/") communicators = [] for _ in range(2): communicators.append(ApplicationCommunicator(application, scope)) await communicators[-1].send_input({"type": "http.request"}) # Each request must complete with a status code of 200 # If requests aren't scheduled concurrently, the barrier in the # sync_wait view will time out, resulting in a 500 status code. for communicator in communicators: response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello World!") # Give response.close() time to finish. await communicator.wait() # The requests should have scheduled on different threads. Note # active_threads is a set (a thread can only appear once), therefore # length is a sufficient check. self.assertEqual(len(sync_waiter.active_threads), 2) sync_waiter.active_threads.clear()
bd3e58de044b44b45c13a989443ab896ef636fd187d6520cc976fa547f136ffe
import json import random from unittest import TestCase from django.conf import settings from django.contrib.messages import constants from django.contrib.messages.storage.base import Message from django.contrib.messages.storage.cookie import ( CookieStorage, MessageDecoder, MessageEncoder, bisect_keep_left, bisect_keep_right, ) from django.test import SimpleTestCase, override_settings from django.utils.crypto import get_random_string from django.utils.safestring import SafeData, mark_safe from .base import BaseTests def set_cookie_data(storage, messages, invalid=False, encode_empty=False): """ Set ``request.COOKIES`` with the encoded data and remove the storage backend's loaded data cache. """ encoded_data = storage._encode(messages, encode_empty=encode_empty) if invalid: # Truncate the first character so that the hash is invalid. encoded_data = encoded_data[1:] storage.request.COOKIES = {CookieStorage.cookie_name: encoded_data} if hasattr(storage, "_loaded_data"): del storage._loaded_data def stored_cookie_messages_count(storage, response): """ Return an integer containing the number of messages stored. """ # Get a list of cookies, excluding ones with a max-age of 0 (because # they have been marked for deletion). cookie = response.cookies.get(storage.cookie_name) if not cookie or cookie["max-age"] == 0: return 0 data = storage._decode(cookie.value) if not data: return 0 if data[-1] == CookieStorage.not_finished: data.pop() return len(data) @override_settings( SESSION_COOKIE_DOMAIN=".example.com", SESSION_COOKIE_SECURE=True, SESSION_COOKIE_HTTPONLY=True, ) class CookieTests(BaseTests, SimpleTestCase): storage_class = CookieStorage def stored_messages_count(self, storage, response): return stored_cookie_messages_count(storage, response) def encode_decode(self, *args, **kwargs): storage = self.get_storage() message = [Message(constants.DEBUG, *args, **kwargs)] encoded = storage._encode(message) return storage._decode(encoded)[0] def test_get(self): storage = self.storage_class(self.get_request()) # Set initial data. example_messages = ["test", "me"] set_cookie_data(storage, example_messages) # The message contains what's expected. self.assertEqual(list(storage), example_messages) @override_settings(SESSION_COOKIE_SAMESITE="Strict") def test_cookie_settings(self): """ CookieStorage honors SESSION_COOKIE_DOMAIN, SESSION_COOKIE_SECURE, and SESSION_COOKIE_HTTPONLY (#15618, #20972). """ # Test before the messages have been consumed storage = self.get_storage() response = self.get_response() storage.add(constants.INFO, "test") storage.update(response) messages = storage._decode(response.cookies["messages"].value) self.assertEqual(len(messages), 1) self.assertEqual(messages[0].message, "test") self.assertEqual(response.cookies["messages"]["domain"], ".example.com") self.assertEqual(response.cookies["messages"]["expires"], "") self.assertIs(response.cookies["messages"]["secure"], True) self.assertIs(response.cookies["messages"]["httponly"], True) self.assertEqual(response.cookies["messages"]["samesite"], "Strict") # Deletion of the cookie (storing with an empty value) after the # messages have been consumed. storage = self.get_storage() response = self.get_response() storage.add(constants.INFO, "test") for m in storage: pass # Iterate through the storage to simulate consumption of messages. storage.update(response) self.assertEqual(response.cookies["messages"].value, "") self.assertEqual(response.cookies["messages"]["domain"], ".example.com") self.assertEqual( response.cookies["messages"]["expires"], "Thu, 01 Jan 1970 00:00:00 GMT" ) self.assertEqual( response.cookies["messages"]["samesite"], settings.SESSION_COOKIE_SAMESITE, ) def test_get_bad_cookie(self): request = self.get_request() storage = self.storage_class(request) # Set initial (invalid) data. example_messages = ["test", "me"] set_cookie_data(storage, example_messages, invalid=True) # The message actually contains what we expect. self.assertEqual(list(storage), []) def test_max_cookie_length(self): """ If the data exceeds what is allowed in a cookie, older messages are removed before saving (and returned by the ``update`` method). """ storage = self.get_storage() response = self.get_response() # When storing as a cookie, the cookie has constant overhead of approx # 54 chars, and each message has a constant overhead of about 37 chars # and a variable overhead of zero in the best case. We aim for a message # size which will fit 4 messages into the cookie, but not 5. # See also FallbackTest.test_session_fallback msg_size = int((CookieStorage.max_cookie_size - 54) / 4.5 - 37) first_msg = None # Generate the same (tested) content every time that does not get run # through zlib compression. random.seed(42) for i in range(5): msg = get_random_string(msg_size) storage.add(constants.INFO, msg) if i == 0: first_msg = msg unstored_messages = storage.update(response) cookie_storing = self.stored_messages_count(storage, response) self.assertEqual(cookie_storing, 4) self.assertEqual(len(unstored_messages), 1) self.assertEqual(unstored_messages[0].message, first_msg) def test_message_rfc6265(self): non_compliant_chars = ["\\", ",", ";", '"'] messages = ["\\te,st", ';m"e', "\u2019", '123"NOTRECEIVED"'] storage = self.get_storage() encoded = storage._encode(messages) for illegal in non_compliant_chars: self.assertEqual(encoded.find(illegal), -1) def test_json_encoder_decoder(self): """ A complex nested data structure containing Message instances is properly encoded/decoded by the custom JSON encoder/decoder classes. """ messages = [ { "message": Message(constants.INFO, "Test message"), "message_list": [ Message(constants.INFO, "message %s") for x in range(5) ] + [{"another-message": Message(constants.ERROR, "error")}], }, Message(constants.INFO, "message %s"), ] encoder = MessageEncoder() value = encoder.encode(messages) decoded_messages = json.loads(value, cls=MessageDecoder) self.assertEqual(messages, decoded_messages) def test_safedata(self): """ A message containing SafeData is keeping its safe status when retrieved from the message storage. """ self.assertIsInstance( self.encode_decode(mark_safe("<b>Hello Django!</b>")).message, SafeData, ) self.assertNotIsInstance( self.encode_decode("<b>Hello Django!</b>").message, SafeData, ) def test_extra_tags(self): """ A message's extra_tags attribute is correctly preserved when retrieved from the message storage. """ for extra_tags in ["", None, "some tags"]: with self.subTest(extra_tags=extra_tags): self.assertEqual( self.encode_decode("message", extra_tags=extra_tags).extra_tags, extra_tags, ) class BisectTests(TestCase): def test_bisect_keep_left(self): self.assertEqual(bisect_keep_left([1, 1, 1], fn=lambda arr: sum(arr) != 2), 2) self.assertEqual(bisect_keep_left([1, 1, 1], fn=lambda arr: sum(arr) != 0), 0) self.assertEqual(bisect_keep_left([], fn=lambda arr: sum(arr) != 0), 0) def test_bisect_keep_right(self): self.assertEqual(bisect_keep_right([1, 1, 1], fn=lambda arr: sum(arr) != 2), 1) self.assertEqual( bisect_keep_right([1, 1, 1, 1], fn=lambda arr: sum(arr) != 2), 2 ) self.assertEqual( bisect_keep_right([1, 1, 1, 1, 1], fn=lambda arr: sum(arr) != 1), 4 ) self.assertEqual(bisect_keep_right([], fn=lambda arr: sum(arr) != 0), 0)
93da2bb6e039b48d0946c12f96a60d81a2f77b6bcb12ecfb007c966c8d69dabe
import json import os import shutil import sys import tempfile import unittest from io import StringIO from pathlib import Path from unittest import mock from django.conf import STATICFILES_STORAGE_ALIAS, settings from django.contrib.staticfiles import finders, storage from django.contrib.staticfiles.management.commands.collectstatic import ( Command as CollectstaticCommand, ) from django.core.management import call_command from django.test import SimpleTestCase, override_settings from .cases import CollectionTestCase from .settings import TEST_ROOT def hashed_file_path(test, path): fullpath = test.render_template(test.static_template_snippet(path)) return fullpath.replace(settings.STATIC_URL, "") class TestHashedFiles: hashed_file_path = hashed_file_path def tearDown(self): # Clear hashed files to avoid side effects among tests. storage.staticfiles_storage.hashed_files.clear() def assertPostCondition(self): """ Assert post conditions for a test are met. Must be manually called at the end of each test. """ pass def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.dad0999e4f8f.txt") self.assertStaticRenders( "test/file.txt", "/static/test/file.dad0999e4f8f.txt", asvar=True ) self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.5e0040571e1a.css" ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") self.assertPostCondition() def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_ignored_completely(self): relpath = self.hashed_file_path("cached/css/ignored.css") self.assertEqual(relpath, "cached/css/ignored.55e7c226dda1.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"#foobar", content) self.assertIn(b"http:foobar", content) self.assertIn(b"https:foobar", content) self.assertIn(b"data:foobar", content) self.assertIn(b"chrome:foobar", content) self.assertIn(b"//foobar", content) self.assertIn(b"url()", content) self.assertPostCondition() def test_path_with_querystring(self): relpath = self.hashed_file_path("cached/styles.css?spam=eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css?spam=eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_fragment(self): relpath = self.hashed_file_path("cached/styles.css#eggs") self.assertEqual(relpath, "cached/styles.5e0040571e1a.css#eggs") with storage.staticfiles_storage.open( "cached/styles.5e0040571e1a.css" ) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_path_with_querystring_and_fragment(self): relpath = self.hashed_file_path("cached/css/fragments.css") self.assertEqual(relpath, "cached/css/fragments.a60c0e74834f.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"fonts/font.b9b105392eb8.eot?#iefix", content) self.assertIn(b"fonts/font.b8d603e42714.svg#webfontIyfZbseF", content) self.assertIn( b"fonts/font.b8d603e42714.svg#path/to/../../fonts/font.svg", content ) self.assertIn( b"data:font/woff;charset=utf-8;" b"base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA", content, ) self.assertIn(b"#default#VML", content) self.assertPostCondition() def test_template_tag_absolute(self): relpath = self.hashed_file_path("cached/absolute.css") self.assertEqual(relpath, "cached/absolute.eb04def9f9a4.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/cached/styles.css", content) self.assertIn(b"/static/cached/styles.5e0040571e1a.css", content) self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertIn(b"/static/cached/img/relative.acae32e4532b.png", content) self.assertPostCondition() def test_template_tag_absolute_root(self): """ Like test_template_tag_absolute, but for a file in STATIC_ROOT (#26249). """ relpath = self.hashed_file_path("absolute_root.css") self.assertEqual(relpath, "absolute_root.f821df1b64f7.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/static/styles_root.css", content) self.assertIn(b"/static/styles_root.401f2509a628.css", content) self.assertPostCondition() def test_template_tag_relative(self): relpath = self.hashed_file_path("cached/relative.css") self.assertEqual(relpath, "cached/relative.c3e9e1ea6f2e.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"../cached/styles.css", content) self.assertNotIn(b'@import "styles.css"', content) self.assertNotIn(b"url(img/relative.png)", content) self.assertIn(b'url("img/relative.acae32e4532b.png")', content) self.assertIn(b"../cached/styles.5e0040571e1a.css", content) self.assertPostCondition() def test_import_replacement(self): "See #18050" relpath = self.hashed_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"""import url("styles.5e0040571e1a.css")""", relfile.read()) self.assertPostCondition() def test_template_tag_deep_relative(self): relpath = self.hashed_file_path("cached/css/window.css") self.assertEqual(relpath, "cached/css/window.5d5c10836967.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"url(img/window.png)", content) self.assertIn(b'url("img/window.acae32e4532b.png")', content) self.assertPostCondition() def test_template_tag_url(self): relpath = self.hashed_file_path("cached/url.css") self.assertEqual(relpath, "cached/url.902310b73412.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b"https://", relfile.read()) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "loop")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_import_loop(self): finders.get_finder.cache_clear() err = StringIO() with self.assertRaisesMessage(RuntimeError, "Max post-process passes exceeded"): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'All' failed!\n\n", err.getvalue()) self.assertPostCondition() def test_post_processing(self): """ post_processing behaves correctly. Files that are alterable should always be post-processed; files that aren't should be skipped. collectstatic has already been called once in setUp() for this testcase, therefore we check by verifying behavior on a second run. """ collectstatic_args = { "interactive": False, "verbosity": 0, "link": False, "clear": False, "dry_run": False, "post_process": True, "use_default_ignore_patterns": True, "ignore_patterns": ["*.ignoreme"], } collectstatic_cmd = CollectstaticCommand() collectstatic_cmd.set_options(**collectstatic_args) stats = collectstatic_cmd.collect() self.assertIn( os.path.join("cached", "css", "window.css"), stats["post_processed"] ) self.assertIn( os.path.join("cached", "css", "img", "window.png"), stats["unmodified"] ) self.assertIn(os.path.join("test", "nonascii.css"), stats["post_processed"]) # No file should be yielded twice. self.assertCountEqual(stats["post_processed"], set(stats["post_processed"])) self.assertPostCondition() def test_css_import_case_insensitive(self): relpath = self.hashed_file_path("cached/styles_insensitive.css") self.assertEqual(relpath, "cached/styles_insensitive.3fa427592a53.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.d41d8cd98f00.css", content) self.assertPostCondition() def test_css_source_map(self): relpath = self.hashed_file_path("cached/source_map.css") self.assertEqual(relpath, "cached/source_map.b2fceaf426aa.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/*# sourceMappingURL=source_map.css.map*/", content) self.assertIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_tabs(self): relpath = self.hashed_file_path("cached/source_map_tabs.css") self.assertEqual(relpath, "cached/source_map_tabs.b2fceaf426aa.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"/*#\tsourceMappingURL=source_map.css.map\t*/", content) self.assertIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_css_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.css") self.assertEqual(relpath, "cached/source_map_sensitive.456683f2106f.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"/*# sOuRcEMaPpInGURL=source_map.css.map */", content) self.assertNotIn( b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */", content, ) self.assertPostCondition() def test_js_source_map(self): relpath = self.hashed_file_path("cached/source_map.js") self.assertEqual(relpath, "cached/source_map.cd45b8534a87.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"//# sourceMappingURL=source_map.js.map", content) self.assertIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_trailing_whitespace(self): relpath = self.hashed_file_path("cached/source_map_trailing_whitespace.js") self.assertEqual( relpath, "cached/source_map_trailing_whitespace.cd45b8534a87.js" ) with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"//# sourceMappingURL=source_map.js.map\t ", content) self.assertIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() def test_js_source_map_sensitive(self): relpath = self.hashed_file_path("cached/source_map_sensitive.js") self.assertEqual(relpath, "cached/source_map_sensitive.5da96fdd3cb3.js") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"//# sOuRcEMaPpInGURL=source_map.js.map", content) self.assertNotIn( b"//# sourceMappingURL=source_map.js.99914b932bd3.map", content, ) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "faulty")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_post_processing_failure(self): """ post_processing indicates the origin of the error when it fails. """ finders.get_finder.cache_clear() err = StringIO() with self.assertRaises(Exception): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue()) self.assertPostCondition() @override_settings( STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "nonutf8")], STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"], ) def test_post_processing_nonutf8(self): finders.get_finder.cache_clear() err = StringIO() with self.assertRaises(UnicodeDecodeError): call_command("collectstatic", interactive=False, verbosity=0, stderr=err) self.assertEqual("Post-processing 'nonutf8.css' failed!\n\n", err.getvalue()) self.assertPostCondition() @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.ExtraPatternsStorage", }, } ) class TestExtraPatternsStorage(CollectionTestCase): def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def cached_file_path(self, path): fullpath = self.render_template(self.static_template_snippet(path)) return fullpath.replace(settings.STATIC_URL, "") def test_multi_extension_patterns(self): """ With storage classes having several file extension patterns, only the files matching a specific file pattern should be affected by the substitution (#19670). """ # CSS files shouldn't be touched by JS patterns. relpath = self.cached_file_path("cached/import.css") self.assertEqual(relpath, "cached/import.f53576679e5a.css") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'import url("styles.5e0040571e1a.css")', relfile.read()) # Confirm JS patterns have been applied to JS files. relpath = self.cached_file_path("cached/test.js") self.assertEqual(relpath, "cached/test.388d7a790d46.js") with storage.staticfiles_storage.open(relpath) as relfile: self.assertIn(b'JS_URL("import.f53576679e5a.css")', relfile.read()) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, } ) class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase): """ Tests for the Cache busting storage """ def setUp(self): super().setUp() temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self._clear_filename = os.path.join(temp_dir, "test", "cleared.txt") with open(self._clear_filename, "w") as f: f.write("to be deleted in one test") self.patched_settings = self.settings( STATICFILES_DIRS=settings.STATICFILES_DIRS + [temp_dir], ) self.patched_settings.enable() self.addCleanup(shutil.rmtree, temp_dir) self._manifest_strict = storage.staticfiles_storage.manifest_strict def tearDown(self): self.patched_settings.disable() if os.path.exists(self._clear_filename): os.unlink(self._clear_filename) storage.staticfiles_storage.manifest_strict = self._manifest_strict super().tearDown() def assertPostCondition(self): hashed_files = storage.staticfiles_storage.hashed_files # The in-memory version of the manifest matches the one on disk # since a properly created manifest should cover all filenames. if hashed_files: manifest, _ = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_manifest_exists(self): filename = storage.staticfiles_storage.manifest_name path = storage.staticfiles_storage.path(filename) self.assertTrue(os.path.exists(path)) def test_manifest_does_not_exist(self): storage.staticfiles_storage.manifest_name = "does.not.exist.json" self.assertIsNone(storage.staticfiles_storage.read_manifest()) def test_manifest_does_not_ignore_permission_error(self): with mock.patch("builtins.open", side_effect=PermissionError): with self.assertRaises(PermissionError): storage.staticfiles_storage.read_manifest() def test_loaded_cache(self): self.assertNotEqual(storage.staticfiles_storage.hashed_files, {}) manifest_content = storage.staticfiles_storage.read_manifest() self.assertIn( '"version": "%s"' % storage.staticfiles_storage.manifest_version, manifest_content, ) def test_parse_cache(self): hashed_files = storage.staticfiles_storage.hashed_files manifest, _ = storage.staticfiles_storage.load_manifest() self.assertEqual(hashed_files, manifest) def test_clear_empties_manifest(self): cleared_file_name = storage.staticfiles_storage.clean_name( os.path.join("test", "cleared.txt") ) # collect the additional file self.run_collectstatic() hashed_files = storage.staticfiles_storage.hashed_files self.assertIn(cleared_file_name, hashed_files) manifest_content, _ = storage.staticfiles_storage.load_manifest() self.assertIn(cleared_file_name, manifest_content) original_path = storage.staticfiles_storage.path(cleared_file_name) self.assertTrue(os.path.exists(original_path)) # delete the original file form the app, collect with clear os.unlink(self._clear_filename) self.run_collectstatic(clear=True) self.assertFileNotFound(original_path) hashed_files = storage.staticfiles_storage.hashed_files self.assertNotIn(cleared_file_name, hashed_files) manifest_content, _ = storage.staticfiles_storage.load_manifest() self.assertNotIn(cleared_file_name, manifest_content) def test_missing_entry(self): missing_file_name = "cached/missing.css" configured_storage = storage.staticfiles_storage self.assertNotIn(missing_file_name, configured_storage.hashed_files) # File name not found in manifest with self.assertRaisesMessage( ValueError, "Missing staticfiles manifest entry for '%s'" % missing_file_name, ): self.hashed_file_path(missing_file_name) configured_storage.manifest_strict = False # File doesn't exist on disk err_msg = "The file '%s' could not be found with %r." % ( missing_file_name, configured_storage._wrapped, ) with self.assertRaisesMessage(ValueError, err_msg): self.hashed_file_path(missing_file_name) content = StringIO() content.write("Found") configured_storage.save(missing_file_name, content) # File exists on disk self.hashed_file_path(missing_file_name) def test_intermediate_files(self): cached_files = os.listdir(os.path.join(settings.STATIC_ROOT, "cached")) # Intermediate files shouldn't be created for reference. self.assertEqual( len( [ cached_file for cached_file in cached_files if cached_file.startswith("relative.") ] ), 2, ) def test_manifest_hash(self): # Collect the additional file. self.run_collectstatic() _, manifest_hash_orig = storage.staticfiles_storage.load_manifest() self.assertNotEqual(manifest_hash_orig, "") self.assertEqual(storage.staticfiles_storage.manifest_hash, manifest_hash_orig) # Saving doesn't change the hash. storage.staticfiles_storage.save_manifest() self.assertEqual(storage.staticfiles_storage.manifest_hash, manifest_hash_orig) # Delete the original file from the app, collect with clear. os.unlink(self._clear_filename) self.run_collectstatic(clear=True) # Hash is changed. _, manifest_hash = storage.staticfiles_storage.load_manifest() self.assertNotEqual(manifest_hash, manifest_hash_orig) def test_manifest_hash_v1(self): storage.staticfiles_storage.manifest_name = "staticfiles_v1.json" manifest_content, manifest_hash = storage.staticfiles_storage.load_manifest() self.assertEqual(manifest_hash, "") self.assertEqual(manifest_content, {"dummy.txt": "dummy.txt"}) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.NoneHashStorage", }, } ) class TestCollectionNoneHashStorage(CollectionTestCase): hashed_file_path = hashed_file_path def test_hashed_name(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.css") @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.NoPostProcessReplacedPathStorage", }, } ) class TestCollectionNoPostProcessReplacedPaths(CollectionTestCase): run_collectstatic_in_setUp = False def test_collectstatistic_no_post_process_replaced_paths(self): stdout = StringIO() self.run_collectstatic(verbosity=1, stdout=stdout) self.assertIn("post-processed", stdout.getvalue()) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.storage.SimpleStorage", }, } ) class TestCollectionSimpleStorage(CollectionTestCase): hashed_file_path = hashed_file_path def setUp(self): storage.staticfiles_storage.hashed_files.clear() # avoid cache interference super().setUp() def test_template_tag_return(self): self.assertStaticRaises( ValueError, "does/not/exist.png", "/static/does/not/exist.png" ) self.assertStaticRenders("test/file.txt", "/static/test/file.deploy12345.txt") self.assertStaticRenders( "cached/styles.css", "/static/cached/styles.deploy12345.css" ) self.assertStaticRenders("path/", "/static/path/") self.assertStaticRenders("path/?query", "/static/path/?query") def test_template_tag_simple_content(self): relpath = self.hashed_file_path("cached/styles.css") self.assertEqual(relpath, "cached/styles.deploy12345.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertNotIn(b"cached/other.css", content) self.assertIn(b"other.deploy12345.css", content) class JSModuleImportAggregationManifestStorage(storage.ManifestStaticFilesStorage): support_js_module_import_aggregation = True @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": ( "staticfiles_tests.test_storage." "JSModuleImportAggregationManifestStorage" ), }, } ) class TestCollectionJSModuleImportAggregationManifestStorage(CollectionTestCase): hashed_file_path = hashed_file_path def test_module_import(self): relpath = self.hashed_file_path("cached/module.js") self.assertEqual(relpath, "cached/module.55fd6938fbc5.js") tests = [ # Relative imports. b'import testConst from "./module_test.477bbebe77f0.js";', b'import relativeModule from "../nested/js/nested.866475c46bb4.js";', b'import { firstConst, secondConst } from "./module_test.477bbebe77f0.js";', # Absolute import. b'import rootConst from "/static/absolute_root.5586327fe78c.js";', # Dynamic import. b'const dynamicModule = import("./module_test.477bbebe77f0.js");', # Creating a module object. b'import * as NewModule from "./module_test.477bbebe77f0.js";', # Aliases. b'import { testConst as alias } from "./module_test.477bbebe77f0.js";', b"import {\n" b" firstVar1 as firstVarAlias,\n" b" $second_var_2 as secondVarAlias\n" b'} from "./module_test.477bbebe77f0.js";', ] with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() for module_import in tests: with self.subTest(module_import=module_import): self.assertIn(module_import, content) def test_aggregating_modules(self): relpath = self.hashed_file_path("cached/module.js") self.assertEqual(relpath, "cached/module.55fd6938fbc5.js") tests = [ b'export * from "./module_test.477bbebe77f0.js";', b'export { testConst } from "./module_test.477bbebe77f0.js";', b"export {\n" b" firstVar as firstVarAlias,\n" b" secondVar as secondVarAlias\n" b'} from "./module_test.477bbebe77f0.js";', ] with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() for module_import in tests: with self.subTest(module_import=module_import): self.assertIn(module_import, content) class CustomManifestStorage(storage.ManifestStaticFilesStorage): def __init__(self, *args, manifest_storage=None, **kwargs): manifest_storage = storage.StaticFilesStorage( location=kwargs.pop("manifest_location"), ) super().__init__(*args, manifest_storage=manifest_storage, **kwargs) class TestCustomManifestStorage(SimpleTestCase): def setUp(self): self.manifest_path = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, self.manifest_path) self.staticfiles_storage = CustomManifestStorage( manifest_location=self.manifest_path, ) self.manifest_file = self.manifest_path / self.staticfiles_storage.manifest_name # Manifest without paths. self.manifest = {"version": self.staticfiles_storage.manifest_version} with self.manifest_file.open("w") as manifest_file: json.dump(self.manifest, manifest_file) def test_read_manifest(self): self.assertEqual( self.staticfiles_storage.read_manifest(), json.dumps(self.manifest), ) def test_read_manifest_nonexistent(self): os.remove(self.manifest_file) self.assertIsNone(self.staticfiles_storage.read_manifest()) def test_save_manifest_override(self): self.assertIs(self.manifest_file.exists(), True) self.staticfiles_storage.save_manifest() self.assertIs(self.manifest_file.exists(), True) new_manifest = json.loads(self.staticfiles_storage.read_manifest()) self.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) def test_save_manifest_create(self): os.remove(self.manifest_file) self.staticfiles_storage.save_manifest() self.assertIs(self.manifest_file.exists(), True) new_manifest = json.loads(self.staticfiles_storage.read_manifest()) self.assertIn("paths", new_manifest) self.assertNotEqual(new_manifest, self.manifest) class CustomStaticFilesStorage(storage.StaticFilesStorage): """ Used in TestStaticFilePermissions """ def __init__(self, *args, **kwargs): kwargs["file_permissions_mode"] = 0o640 kwargs["directory_permissions_mode"] = 0o740 super().__init__(*args, **kwargs) @unittest.skipIf(sys.platform == "win32", "Windows only partially supports chmod.") class TestStaticFilePermissions(CollectionTestCase): command_params = { "interactive": False, "verbosity": 0, "ignore_patterns": ["*.ignoreme"], } def setUp(self): self.umask = 0o027 self.old_umask = os.umask(self.umask) super().setUp() def tearDown(self): os.umask(self.old_umask) super().tearDown() # Don't run collectstatic command in this test class. def run_collectstatic(self, **kwargs): pass @override_settings( FILE_UPLOAD_PERMISSIONS=0o655, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, ) def test_collect_static_files_permissions(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o655) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o765) @override_settings( FILE_UPLOAD_PERMISSIONS=None, FILE_UPLOAD_DIRECTORY_PERMISSIONS=None, ) def test_collect_static_files_default_permissions(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o666 & ~self.umask) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o777 & ~self.umask) @override_settings( FILE_UPLOAD_PERMISSIONS=0o655, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765, STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "staticfiles_tests.test_storage.CustomStaticFilesStorage", }, }, ) def test_collect_static_files_subclass_of_static_storage(self): call_command("collectstatic", **self.command_params) static_root = Path(settings.STATIC_ROOT) test_file = static_root / "test.txt" file_mode = test_file.stat().st_mode & 0o777 self.assertEqual(file_mode, 0o640) tests = [ static_root / "subdir", static_root / "nested", static_root / "nested" / "css", ] for directory in tests: with self.subTest(directory=directory): dir_mode = directory.stat().st_mode & 0o777 self.assertEqual(dir_mode, 0o740) @override_settings( STORAGES={ STATICFILES_STORAGE_ALIAS: { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, } ) class TestCollectionHashedFilesCache(CollectionTestCase): """ Files referenced from CSS use the correct final hashed name regardless of the order in which the files are post-processed. """ hashed_file_path = hashed_file_path def setUp(self): super().setUp() self._temp_dir = temp_dir = tempfile.mkdtemp() os.makedirs(os.path.join(temp_dir, "test")) self.addCleanup(shutil.rmtree, temp_dir) def _get_filename_path(self, filename): return os.path.join(self._temp_dir, "test", filename) def test_file_change_after_collectstatic(self): # Create initial static files. file_contents = ( ("foo.png", "foo"), ("bar.css", 'url("foo.png")\nurl("xyz.png")'), ("xyz.png", "xyz"), ) for filename, content in file_contents: with open(self._get_filename_path(filename), "w") as f: f.write(content) with self.modify_settings(STATICFILES_DIRS={"append": self._temp_dir}): finders.get_finder.cache_clear() err = StringIO() # First collectstatic run. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.acbd18db4cc2.png", content) self.assertIn(b"xyz.d16fb36f0911.png", content) # Change the contents of the png files. for filename in ("foo.png", "xyz.png"): with open(self._get_filename_path(filename), "w+b") as f: f.write(b"new content of file to change its hash") # The hashes of the png files in the CSS file are updated after # a second collectstatic. call_command("collectstatic", interactive=False, verbosity=0, stderr=err) relpath = self.hashed_file_path("test/bar.css") with storage.staticfiles_storage.open(relpath) as relfile: content = relfile.read() self.assertIn(b"foo.57a5cb9ba68d.png", content) self.assertIn(b"xyz.57a5cb9ba68d.png", content)
d5fd2a386a2d4891389422c8e8846b0d8631cc7623cc87a1e5ba9afe32084520
import io import itertools import os import sys import tempfile from unittest import skipIf from django.core.files.base import ContentFile from django.http import FileResponse from django.test import SimpleTestCase class UnseekableBytesIO(io.BytesIO): def seekable(self): return False class FileResponseTests(SimpleTestCase): def test_content_length_file(self): response = FileResponse(open(__file__, "rb")) response.close() self.assertEqual( response.headers["Content-Length"], str(os.path.getsize(__file__)) ) def test_content_length_buffer(self): response = FileResponse(io.BytesIO(b"binary content")) self.assertEqual(response.headers["Content-Length"], "14") def test_content_length_nonzero_starting_position_file(self): file = open(__file__, "rb") file.seek(10) response = FileResponse(file) response.close() self.assertEqual( response.headers["Content-Length"], str(os.path.getsize(__file__) - 10) ) def test_content_length_nonzero_starting_position_buffer(self): test_tuples = ( ("BytesIO", io.BytesIO), ("UnseekableBytesIO", UnseekableBytesIO), ) for buffer_class_name, BufferClass in test_tuples: with self.subTest(buffer_class_name=buffer_class_name): buffer = BufferClass(b"binary content") buffer.seek(10) response = FileResponse(buffer) self.assertEqual(response.headers["Content-Length"], "4") def test_content_length_nonzero_starting_position_file_seekable_no_tell(self): class TestFile: def __init__(self, path, *args, **kwargs): self._file = open(path, *args, **kwargs) def read(self, n_bytes=-1): return self._file.read(n_bytes) def seek(self, offset, whence=io.SEEK_SET): return self._file.seek(offset, whence) def seekable(self): return True @property def name(self): return self._file.name def close(self): if self._file: self._file.close() self._file = None def __enter__(self): return self def __exit__(self, e_type, e_val, e_tb): self.close() file = TestFile(__file__, "rb") file.seek(10) response = FileResponse(file) response.close() self.assertEqual( response.headers["Content-Length"], str(os.path.getsize(__file__) - 10) ) def test_content_type_file(self): response = FileResponse(open(__file__, "rb")) response.close() self.assertIn(response.headers["Content-Type"], ["text/x-python", "text/plain"]) def test_content_type_buffer(self): response = FileResponse(io.BytesIO(b"binary content")) self.assertEqual(response.headers["Content-Type"], "application/octet-stream") def test_content_type_buffer_explicit(self): response = FileResponse( io.BytesIO(b"binary content"), content_type="video/webm" ) self.assertEqual(response.headers["Content-Type"], "video/webm") def test_content_type_buffer_explicit_default(self): response = FileResponse( io.BytesIO(b"binary content"), content_type="text/html; charset=utf-8" ) self.assertEqual(response.headers["Content-Type"], "text/html; charset=utf-8") def test_content_type_buffer_named(self): test_tuples = ( (__file__, ["text/x-python", "text/plain"]), (__file__ + "nosuchfile", ["application/octet-stream"]), ("test_fileresponse.py", ["text/x-python", "text/plain"]), ("test_fileresponse.pynosuchfile", ["application/octet-stream"]), ) for filename, content_types in test_tuples: with self.subTest(filename=filename): buffer = io.BytesIO(b"binary content") buffer.name = filename response = FileResponse(buffer) self.assertIn(response.headers["Content-Type"], content_types) def test_content_disposition_file(self): filenames = ( ("", "test_fileresponse.py"), ("custom_name.py", "custom_name.py"), ) dispositions = ( (False, "inline"), (True, "attachment"), ) for (filename, header_filename), ( as_attachment, header_disposition, ) in itertools.product(filenames, dispositions): with self.subTest(filename=filename, disposition=header_disposition): response = FileResponse( open(__file__, "rb"), filename=filename, as_attachment=as_attachment ) response.close() self.assertEqual( response.headers["Content-Disposition"], '%s; filename="%s"' % (header_disposition, header_filename), ) def test_content_disposition_escaping(self): # fmt: off tests = [ ( 'multi-part-one";\" dummy".txt', r"multi-part-one\";\" dummy\".txt" ), ] # fmt: on # Non-escape sequence backslashes are path segments on Windows, and are # eliminated by an os.path.basename() check in FileResponse. if sys.platform != "win32": # fmt: off tests += [ ( 'multi-part-one\\";\" dummy".txt', r"multi-part-one\\\";\" dummy\".txt" ), ( 'multi-part-one\\";\\\" dummy".txt', r"multi-part-one\\\";\\\" dummy\".txt" ) ] # fmt: on for filename, escaped in tests: with self.subTest(filename=filename, escaped=escaped): response = FileResponse( io.BytesIO(b"binary content"), filename=filename, as_attachment=True ) response.close() self.assertEqual( response.headers["Content-Disposition"], f'attachment; filename="{escaped}"', ) def test_content_disposition_buffer(self): response = FileResponse(io.BytesIO(b"binary content")) self.assertFalse(response.has_header("Content-Disposition")) def test_content_disposition_buffer_attachment(self): response = FileResponse(io.BytesIO(b"binary content"), as_attachment=True) self.assertEqual(response.headers["Content-Disposition"], "attachment") def test_content_disposition_buffer_explicit_filename(self): dispositions = ( (False, "inline"), (True, "attachment"), ) for as_attachment, header_disposition in dispositions: response = FileResponse( io.BytesIO(b"binary content"), as_attachment=as_attachment, filename="custom_name.py", ) self.assertEqual( response.headers["Content-Disposition"], '%s; filename="custom_name.py"' % header_disposition, ) def test_response_buffer(self): response = FileResponse(io.BytesIO(b"binary content")) self.assertEqual(list(response), [b"binary content"]) def test_response_nonzero_starting_position(self): test_tuples = ( ("BytesIO", io.BytesIO), ("UnseekableBytesIO", UnseekableBytesIO), ) for buffer_class_name, BufferClass in test_tuples: with self.subTest(buffer_class_name=buffer_class_name): buffer = BufferClass(b"binary content") buffer.seek(10) response = FileResponse(buffer) self.assertEqual(list(response), [b"tent"]) def test_buffer_explicit_absolute_filename(self): """ Headers are set correctly with a buffer when an absolute filename is provided. """ response = FileResponse(io.BytesIO(b"binary content"), filename=__file__) self.assertEqual(response.headers["Content-Length"], "14") self.assertEqual( response.headers["Content-Disposition"], 'inline; filename="test_fileresponse.py"', ) @skipIf(sys.platform == "win32", "Named pipes are Unix-only.") def test_file_from_named_pipe_response(self): with tempfile.TemporaryDirectory() as temp_dir: pipe_file = os.path.join(temp_dir, "named_pipe") os.mkfifo(pipe_file) pipe_for_read = os.open(pipe_file, os.O_RDONLY | os.O_NONBLOCK) with open(pipe_file, "wb") as pipe_for_write: pipe_for_write.write(b"binary content") response = FileResponse(os.fdopen(pipe_for_read, mode="rb")) response_content = list(response) response.close() self.assertEqual(response_content, [b"binary content"]) self.assertFalse(response.has_header("Content-Length")) def test_compressed_response(self): """ If compressed responses are served with the uncompressed Content-Type and a compression Content-Encoding, browsers might automatically uncompress the file, which is most probably not wanted. """ test_tuples = ( (".tar.gz", "application/gzip"), (".tar.br", "application/x-brotli"), (".tar.bz2", "application/x-bzip"), (".tar.xz", "application/x-xz"), (".tar.Z", "application/x-compress"), ) for extension, mimetype in test_tuples: with self.subTest(ext=extension): with tempfile.NamedTemporaryFile(suffix=extension) as tmp: response = FileResponse(tmp) self.assertEqual(response.headers["Content-Type"], mimetype) self.assertFalse(response.has_header("Content-Encoding")) def test_unicode_attachment(self): response = FileResponse( ContentFile(b"binary content", name="祝您平安.odt"), as_attachment=True, content_type="application/vnd.oasis.opendocument.text", ) self.assertEqual( response.headers["Content-Type"], "application/vnd.oasis.opendocument.text", ) self.assertEqual( response.headers["Content-Disposition"], "attachment; filename*=utf-8''%E7%A5%9D%E6%82%A8%E5%B9%B3%E5%AE%89.odt", ) def test_repr(self): response = FileResponse(io.BytesIO(b"binary content")) self.assertEqual( repr(response), '<FileResponse status_code=200, "application/octet-stream">', )
f6ebf304bf0ba7c823b41bd2c2dce25f9146444dfd1d07322b904ae10eab37b7
import unittest from django.core.exceptions import FieldError from django.db import IntegrityError, connection, transaction from django.db.models import Case, CharField, Count, F, IntegerField, Max, When from django.db.models.functions import Abs, Concat, Lower from django.test import TestCase from django.test.utils import register_lookup from .models import ( A, B, Bar, D, DataPoint, Foo, RelatedPoint, UniqueNumber, UniqueNumberChild, ) class SimpleTest(TestCase): @classmethod def setUpTestData(cls): cls.a1 = A.objects.create() cls.a2 = A.objects.create() for x in range(20): B.objects.create(a=cls.a1) D.objects.create(a=cls.a1) def test_nonempty_update(self): """ Update changes the right number of rows for a nonempty queryset """ num_updated = self.a1.b_set.update(y=100) self.assertEqual(num_updated, 20) cnt = B.objects.filter(y=100).count() self.assertEqual(cnt, 20) def test_empty_update(self): """ Update changes the right number of rows for an empty queryset """ num_updated = self.a2.b_set.update(y=100) self.assertEqual(num_updated, 0) cnt = B.objects.filter(y=100).count() self.assertEqual(cnt, 0) def test_nonempty_update_with_inheritance(self): """ Update changes the right number of rows for an empty queryset when the update affects only a base table """ num_updated = self.a1.d_set.update(y=100) self.assertEqual(num_updated, 20) cnt = D.objects.filter(y=100).count() self.assertEqual(cnt, 20) def test_empty_update_with_inheritance(self): """ Update changes the right number of rows for an empty queryset when the update affects only a base table """ num_updated = self.a2.d_set.update(y=100) self.assertEqual(num_updated, 0) cnt = D.objects.filter(y=100).count() self.assertEqual(cnt, 0) def test_foreign_key_update_with_id(self): """ Update works using <field>_id for foreign keys """ num_updated = self.a1.d_set.update(a_id=self.a2) self.assertEqual(num_updated, 20) self.assertEqual(self.a2.d_set.count(), 20) class AdvancedTests(TestCase): @classmethod def setUpTestData(cls): cls.d0 = DataPoint.objects.create(name="d0", value="apple") cls.d2 = DataPoint.objects.create(name="d2", value="banana") cls.d3 = DataPoint.objects.create(name="d3", value="banana", is_active=False) cls.r1 = RelatedPoint.objects.create(name="r1", data=cls.d3) def test_update(self): """ Objects are updated by first filtering the candidates into a queryset and then calling the update() method. It executes immediately and returns nothing. """ resp = DataPoint.objects.filter(value="apple").update(name="d1") self.assertEqual(resp, 1) resp = DataPoint.objects.filter(value="apple") self.assertEqual(list(resp), [self.d0]) def test_update_multiple_objects(self): """ We can update multiple objects at once. """ resp = DataPoint.objects.filter(value="banana").update(value="pineapple") self.assertEqual(resp, 2) self.assertEqual(DataPoint.objects.get(name="d2").value, "pineapple") def test_update_fk(self): """ Foreign key fields can also be updated, although you can only update the object referred to, not anything inside the related object. """ resp = RelatedPoint.objects.filter(name="r1").update(data=self.d0) self.assertEqual(resp, 1) resp = RelatedPoint.objects.filter(data__name="d0") self.assertEqual(list(resp), [self.r1]) def test_update_multiple_fields(self): """ Multiple fields can be updated at once """ resp = DataPoint.objects.filter(value="apple").update( value="fruit", another_value="peach" ) self.assertEqual(resp, 1) d = DataPoint.objects.get(name="d0") self.assertEqual(d.value, "fruit") self.assertEqual(d.another_value, "peach") def test_update_all(self): """ In the rare case you want to update every instance of a model, update() is also a manager method. """ self.assertEqual(DataPoint.objects.update(value="thing"), 3) resp = DataPoint.objects.values("value").distinct() self.assertEqual(list(resp), [{"value": "thing"}]) def test_update_slice_fail(self): """ We do not support update on already sliced query sets. """ method = DataPoint.objects.all()[:2].update msg = "Cannot update a query once a slice has been taken." with self.assertRaisesMessage(TypeError, msg): method(another_value="another thing") def test_update_respects_to_field(self): """ Update of an FK field which specifies a to_field works. """ a_foo = Foo.objects.create(target="aaa") b_foo = Foo.objects.create(target="bbb") bar = Bar.objects.create(foo=a_foo) self.assertEqual(bar.foo_id, a_foo.target) bar_qs = Bar.objects.filter(pk=bar.pk) self.assertEqual(bar_qs[0].foo_id, a_foo.target) bar_qs.update(foo=b_foo) self.assertEqual(bar_qs[0].foo_id, b_foo.target) def test_update_m2m_field(self): msg = ( "Cannot update model field " "<django.db.models.fields.related.ManyToManyField: m2m_foo> " "(only non-relations and foreign keys permitted)." ) with self.assertRaisesMessage(FieldError, msg): Bar.objects.update(m2m_foo="whatever") def test_update_transformed_field(self): A.objects.create(x=5) A.objects.create(x=-6) with register_lookup(IntegerField, Abs): A.objects.update(x=F("x__abs")) self.assertCountEqual(A.objects.values_list("x", flat=True), [5, 6]) def test_update_annotated_queryset(self): """ Update of a queryset that's been annotated. """ # Trivial annotated update qs = DataPoint.objects.annotate(alias=F("value")) self.assertEqual(qs.update(another_value="foo"), 3) # Update where annotation is used for filtering qs = DataPoint.objects.annotate(alias=F("value")).filter(alias="apple") self.assertEqual(qs.update(another_value="foo"), 1) # Update where annotation is used in update parameters qs = DataPoint.objects.annotate(alias=F("value")) self.assertEqual(qs.update(another_value=F("alias")), 3) # Update where aggregation annotation is used in update parameters qs = DataPoint.objects.annotate(max=Max("value")) msg = ( "Aggregate functions are not allowed in this query " "(another_value=Max(Col(update_datapoint, update.DataPoint.value)))." ) with self.assertRaisesMessage(FieldError, msg): qs.update(another_value=F("max")) def test_update_annotated_multi_table_queryset(self): """ Update of a queryset that's been annotated and involves multiple tables. """ # Trivial annotated update qs = DataPoint.objects.annotate(related_count=Count("relatedpoint")) self.assertEqual(qs.update(value="Foo"), 3) # Update where annotation is used for filtering qs = DataPoint.objects.annotate(related_count=Count("relatedpoint")) self.assertEqual(qs.filter(related_count=1).update(value="Foo"), 1) # Update where aggregation annotation is used in update parameters qs = RelatedPoint.objects.annotate(max=Max("data__value")) msg = "Joined field references are not permitted in this query" with self.assertRaisesMessage(FieldError, msg): qs.update(name=F("max")) def test_update_with_joined_field_annotation(self): msg = "Joined field references are not permitted in this query" with register_lookup(CharField, Lower): for annotation in ( F("data__name"), F("data__name__lower"), Lower("data__name"), Concat("data__name", "data__value"), ): with self.subTest(annotation=annotation): with self.assertRaisesMessage(FieldError, msg): RelatedPoint.objects.annotate( new_name=annotation, ).update(name=F("new_name")) def test_update_ordered_by_m2m_aggregation_annotation(self): msg = ( "Cannot update when ordering by an aggregate: " "Count(Col(update_bar_m2m_foo, update.Bar_m2m_foo.foo))" ) with self.assertRaisesMessage(FieldError, msg): Bar.objects.annotate(m2m_count=Count("m2m_foo")).order_by( "m2m_count" ).update(x=2) def test_update_ordered_by_inline_m2m_annotation(self): foo = Foo.objects.create(target="test") Bar.objects.create(foo=foo) Bar.objects.order_by(Abs("m2m_foo")).update(x=2) self.assertEqual(Bar.objects.get().x, 2) def test_update_ordered_by_m2m_annotation(self): foo = Foo.objects.create(target="test") Bar.objects.create(foo=foo) Bar.objects.annotate(abs_id=Abs("m2m_foo")).order_by("abs_id").update(x=3) self.assertEqual(Bar.objects.get().x, 3) def test_update_ordered_by_m2m_annotation_desc(self): foo = Foo.objects.create(target="test") Bar.objects.create(foo=foo) Bar.objects.annotate(abs_id=Abs("m2m_foo")).order_by("-abs_id").update(x=4) self.assertEqual(Bar.objects.get().x, 4) def test_update_negated_f(self): DataPoint.objects.update(is_active=~F("is_active")) self.assertCountEqual( DataPoint.objects.values_list("name", "is_active"), [("d0", False), ("d2", False), ("d3", True)], ) DataPoint.objects.update(is_active=~F("is_active")) self.assertCountEqual( DataPoint.objects.values_list("name", "is_active"), [("d0", True), ("d2", True), ("d3", False)], ) def test_update_negated_f_conditional_annotation(self): DataPoint.objects.annotate( is_d2=Case(When(name="d2", then=True), default=False) ).update(is_active=~F("is_d2")) self.assertCountEqual( DataPoint.objects.values_list("name", "is_active"), [("d0", True), ("d2", False), ("d3", True)], ) def test_updating_non_conditional_field(self): msg = "Cannot negate non-conditional expressions." with self.assertRaisesMessage(TypeError, msg): DataPoint.objects.update(is_active=~F("name")) @unittest.skipUnless( connection.vendor == "mysql", "UPDATE...ORDER BY syntax is supported on MySQL/MariaDB", ) class MySQLUpdateOrderByTest(TestCase): """Update field with a unique constraint using an ordered queryset.""" @classmethod def setUpTestData(cls): UniqueNumber.objects.create(number=1) UniqueNumber.objects.create(number=2) def test_order_by_update_on_unique_constraint(self): tests = [ ("-number", "id"), (F("number").desc(), "id"), (F("number") * -1, "id"), ] for ordering in tests: with self.subTest(ordering=ordering), transaction.atomic(): updated = UniqueNumber.objects.order_by(*ordering).update( number=F("number") + 1, ) self.assertEqual(updated, 2) def test_order_by_update_on_unique_constraint_annotation(self): updated = ( UniqueNumber.objects.annotate(number_inverse=F("number").desc()) .order_by("number_inverse") .update(number=F("number") + 1) ) self.assertEqual(updated, 2) def test_order_by_update_on_unique_constraint_annotation_desc(self): updated = ( UniqueNumber.objects.annotate(number_annotation=F("number")) .order_by("-number_annotation") .update(number=F("number") + 1) ) self.assertEqual(updated, 2) def test_order_by_update_on_parent_unique_constraint(self): # Ordering by inherited fields is omitted because joined fields cannot # be used in the ORDER BY clause. UniqueNumberChild.objects.create(number=3) UniqueNumberChild.objects.create(number=4) with self.assertRaises(IntegrityError): UniqueNumberChild.objects.order_by("number").update( number=F("number") + 1, ) def test_order_by_update_on_related_field(self): # Ordering by related fields is omitted because joined fields cannot be # used in the ORDER BY clause. data = DataPoint.objects.create(name="d0", value="apple") related = RelatedPoint.objects.create(name="r0", data=data) with self.assertNumQueries(1) as ctx: updated = RelatedPoint.objects.order_by("data__name").update(name="new") sql = ctx.captured_queries[0]["sql"] self.assertNotIn("ORDER BY", sql) self.assertEqual(updated, 1) related.refresh_from_db() self.assertEqual(related.name, "new")
601e625fe34a990448d892f2a96f9a0bb475b1ecf5382d5669d7595d986b45a6
import datetime import decimal import logging import sys from pathlib import Path from django.core.exceptions import BadRequest, PermissionDenied, SuspiciousOperation from django.http import Http404, HttpResponse, JsonResponse from django.shortcuts import render from django.template import Context, Template, TemplateDoesNotExist from django.urls import get_resolver from django.views import View from django.views.debug import ( ExceptionReporter, SafeExceptionReporterFilter, technical_500_response, ) from django.views.decorators.debug import sensitive_post_parameters, sensitive_variables TEMPLATES_PATH = Path(__file__).resolve().parent / "templates" def index_page(request): """Dummy index page""" return HttpResponse("<html><body>Dummy page</body></html>") def with_parameter(request, parameter): return HttpResponse("ok") def raises(request): # Make sure that a callable that raises an exception in the stack frame's # local vars won't hijack the technical 500 response (#15025). def callable(): raise Exception try: raise Exception except Exception: return technical_500_response(request, *sys.exc_info()) def raises500(request): # We need to inspect the HTML generated by the fancy 500 debug view but # the test client ignores it, so we send it explicitly. try: raise Exception except Exception: return technical_500_response(request, *sys.exc_info()) class Raises500View(View): def get(self, request): try: raise Exception except Exception: return technical_500_response(request, *sys.exc_info()) def raises400(request): raise SuspiciousOperation def raises400_bad_request(request): raise BadRequest("Malformed request syntax") def raises403(request): raise PermissionDenied("Insufficient Permissions") def raises404(request): resolver = get_resolver(None) resolver.resolve("/not-in-urls") def technical404(request): raise Http404("Testing technical 404.") class Http404View(View): def get(self, request): raise Http404("Testing class-based technical 404.") def template_exception(request): return render(request, "debug/template_exception.html") def safestring_in_template_exception(request): """ Trigger an exception in the template machinery which causes a SafeString to be inserted as args[0] of the Exception. """ template = Template('{% extends "<script>alert(1);</script>" %}') try: template.render(Context()) except Exception: return technical_500_response(request, *sys.exc_info()) def jsi18n(request): return render(request, "jsi18n.html") def jsi18n_multi_catalogs(request): return render(request, "jsi18n-multi-catalogs.html") def raises_template_does_not_exist(request, path="i_dont_exist.html"): # We need to inspect the HTML generated by the fancy 500 debug view but # the test client ignores it, so we send it explicitly. try: return render(request, path) except TemplateDoesNotExist: return technical_500_response(request, *sys.exc_info()) def render_no_template(request): # If we do not specify a template, we need to make sure the debug # view doesn't blow up. return render(request, [], {}) def send_log(request, exc_info): logger = logging.getLogger("django") # The default logging config has a logging filter to ensure admin emails are # only sent with DEBUG=False, but since someone might choose to remove that # filter, we still want to be able to test the behavior of error emails # with DEBUG=True. So we need to remove the filter temporarily. admin_email_handler = [ h for h in logger.handlers if h.__class__.__name__ == "AdminEmailHandler" ][0] orig_filters = admin_email_handler.filters admin_email_handler.filters = [] admin_email_handler.include_html = True logger.error( "Internal Server Error: %s", request.path, exc_info=exc_info, extra={"status_code": 500, "request": request}, ) admin_email_handler.filters = orig_filters def non_sensitive_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") @sensitive_post_parameters("bacon-key", "sausage-key") def sensitive_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") @sensitive_post_parameters("bacon-key", "sausage-key") async def async_sensitive_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables() @sensitive_post_parameters() def paranoid_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) def sensitive_args_function_caller(request): try: sensitive_args_function( "".join( ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) ) except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") def sensitive_args_function(sauce): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA raise Exception def sensitive_kwargs_function_caller(request): try: sensitive_kwargs_function( "".join( ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) ) except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) @sensitive_variables("sauce") def sensitive_kwargs_function(sauce=None): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA raise Exception class UnsafeExceptionReporterFilter(SafeExceptionReporterFilter): """ Ignores all the filtering done by its parent class. """ def get_post_parameters(self, request): return request.POST def get_traceback_frame_variables(self, request, tb_frame): return tb_frame.f_locals.items() @sensitive_variables() @sensitive_post_parameters() def custom_exception_reporter_filter_view(request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's source # is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) request.exception_reporter_filter = UnsafeExceptionReporterFilter() try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) class CustomExceptionReporter(ExceptionReporter): custom_traceback_text = "custom traceback text" def get_traceback_html(self): return self.custom_traceback_text class TemplateOverrideExceptionReporter(ExceptionReporter): html_template_path = TEMPLATES_PATH / "my_technical_500.html" text_template_path = TEMPLATES_PATH / "my_technical_500.txt" def custom_reporter_class_view(request): request.exception_reporter_class = CustomExceptionReporter try: raise Exception except Exception: exc_info = sys.exc_info() return technical_500_response(request, *exc_info) class Klass: @sensitive_variables("sauce") def method(self, request): # Do not just use plain strings for the variables' values in the code # so that the tests don't return false positives when the function's # source is displayed in the exception report. cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: raise Exception except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) def sensitive_method_view(request): return Klass().method(request) @sensitive_variables("sauce") @sensitive_post_parameters("bacon-key", "sausage-key") def multivalue_dict_key_error(request): cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA sauce = "".join( # NOQA ["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"] ) try: request.POST["bar"] except Exception: exc_info = sys.exc_info() send_log(request, exc_info) return technical_500_response(request, *exc_info) def json_response_view(request): return JsonResponse( { "a": [1, 2, 3], "foo": {"bar": "baz"}, # Make sure datetime and Decimal objects would be serialized properly "timestamp": datetime.datetime(2013, 5, 19, 20), "value": decimal.Decimal("3.14"), } )
55fabfaf48ca1784fc619cd2d4af5632bc26346119490df8ee366c775a4179f1
from datetime import datetime from decimal import Decimal from django import forms from django.conf import settings from django.contrib import admin from django.contrib.admin import helpers from django.contrib.admin.utils import ( NestedObjects, build_q_object_from_lookup_parameters, display_for_field, display_for_value, flatten, flatten_fieldsets, help_text_for_field, label_for_field, lookup_field, quote, ) from django.db import DEFAULT_DB_ALIAS, models from django.test import SimpleTestCase, TestCase, override_settings from django.utils.formats import localize from django.utils.safestring import mark_safe from .models import Article, Car, Count, Event, EventGuide, Location, Site, Vehicle class NestedObjectsTests(TestCase): """ Tests for ``NestedObject`` utility collection. """ @classmethod def setUpTestData(cls): cls.n = NestedObjects(using=DEFAULT_DB_ALIAS) cls.objs = [Count.objects.create(num=i) for i in range(5)] def _check(self, target): self.assertEqual(self.n.nested(lambda obj: obj.num), target) def _connect(self, i, j): self.objs[i].parent = self.objs[j] self.objs[i].save() def _collect(self, *indices): self.n.collect([self.objs[i] for i in indices]) def test_unrelated_roots(self): self._connect(2, 1) self._collect(0) self._collect(1) self._check([0, 1, [2]]) def test_siblings(self): self._connect(1, 0) self._connect(2, 0) self._collect(0) self._check([0, [1, 2]]) def test_non_added_parent(self): self._connect(0, 1) self._collect(0) self._check([0]) def test_cyclic(self): self._connect(0, 2) self._connect(1, 0) self._connect(2, 1) self._collect(0) self._check([0, [1, [2]]]) def test_queries(self): self._connect(1, 0) self._connect(2, 0) # 1 query to fetch all children of 0 (1 and 2) # 1 query to fetch all children of 1 and 2 (none) # Should not require additional queries to populate the nested graph. self.assertNumQueries(2, self._collect, 0) def test_on_delete_do_nothing(self): """ The nested collector doesn't query for DO_NOTHING objects. """ n = NestedObjects(using=DEFAULT_DB_ALIAS) objs = [Event.objects.create()] EventGuide.objects.create(event=objs[0]) with self.assertNumQueries(2): # One for Location, one for Guest, and no query for EventGuide n.collect(objs) def test_relation_on_abstract(self): """ NestedObjects.collect() doesn't trip (AttributeError) on the special notation for relations on abstract models (related_name that contains %(app_label)s and/or %(class)s) (#21846). """ n = NestedObjects(using=DEFAULT_DB_ALIAS) Car.objects.create() n.collect([Vehicle.objects.first()]) class UtilsTests(SimpleTestCase): empty_value = "-empty-" def test_values_from_lookup_field(self): """ Regression test for #12654: lookup_field """ SITE_NAME = "example.com" TITLE_TEXT = "Some title" CREATED_DATE = datetime.min ADMIN_METHOD = "admin method" SIMPLE_FUNCTION = "function" INSTANCE_ATTRIBUTE = "attr" class MockModelAdmin: def get_admin_value(self, obj): return ADMIN_METHOD def simple_function(obj): return SIMPLE_FUNCTION site_obj = Site(domain=SITE_NAME) article = Article( site=site_obj, title=TITLE_TEXT, created=CREATED_DATE, ) article.non_field = INSTANCE_ATTRIBUTE verifications = ( ("site", SITE_NAME), ("created", localize(CREATED_DATE)), ("title", TITLE_TEXT), ("get_admin_value", ADMIN_METHOD), (simple_function, SIMPLE_FUNCTION), ("test_from_model", article.test_from_model()), ("non_field", INSTANCE_ATTRIBUTE), ) mock_admin = MockModelAdmin() for name, value in verifications: field, attr, resolved_value = lookup_field(name, article, mock_admin) if field is not None: resolved_value = display_for_field( resolved_value, field, self.empty_value ) self.assertEqual(value, resolved_value) def test_null_display_for_field(self): """ Regression test for #12550: display_for_field should handle None value. """ display_value = display_for_field(None, models.CharField(), self.empty_value) self.assertEqual(display_value, self.empty_value) display_value = display_for_field( None, models.CharField(choices=((None, "test_none"),)), self.empty_value ) self.assertEqual(display_value, "test_none") display_value = display_for_field(None, models.DateField(), self.empty_value) self.assertEqual(display_value, self.empty_value) display_value = display_for_field(None, models.TimeField(), self.empty_value) self.assertEqual(display_value, self.empty_value) display_value = display_for_field( None, models.BooleanField(null=True), self.empty_value ) expected = ( '<img src="%sadmin/img/icon-unknown.svg" alt="None" />' % settings.STATIC_URL ) self.assertHTMLEqual(display_value, expected) display_value = display_for_field(None, models.DecimalField(), self.empty_value) self.assertEqual(display_value, self.empty_value) 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": "你好 世界"}, '{"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") display_value = display_for_field( Decimal("12345.6789"), models.DecimalField(), self.empty_value ) self.assertEqual(display_value, "12345.6789") display_value = display_for_field( 12345, models.IntegerField(), self.empty_value ) self.assertEqual(display_value, "12345") @override_settings(USE_THOUSAND_SEPARATOR=True) def test_number_formats_with_thousand_separator_display_for_field(self): display_value = display_for_field( 12345.6789, models.FloatField(), self.empty_value ) self.assertEqual(display_value, "12,345.6789") display_value = display_for_field( Decimal("12345.6789"), models.DecimalField(), self.empty_value ) self.assertEqual(display_value, "12,345.6789") display_value = display_for_field( 12345, models.IntegerField(), self.empty_value ) self.assertEqual(display_value, "12,345") def test_list_display_for_value(self): display_value = display_for_value([1, 2, 3], self.empty_value) self.assertEqual(display_value, "1, 2, 3") display_value = display_for_value( [1, 2, "buckle", "my", "shoe"], self.empty_value ) self.assertEqual(display_value, "1, 2, buckle, my, shoe") @override_settings(USE_THOUSAND_SEPARATOR=True) def test_list_display_for_value_boolean(self): self.assertEqual( display_for_value(True, "", boolean=True), '<img src="/static/admin/img/icon-yes.svg" alt="True">', ) self.assertEqual( display_for_value(False, "", boolean=True), '<img src="/static/admin/img/icon-no.svg" alt="False">', ) self.assertEqual(display_for_value(True, ""), "True") self.assertEqual(display_for_value(False, ""), "False") def test_label_for_field(self): """ Tests for label_for_field """ self.assertEqual(label_for_field("title", Article), "title") self.assertEqual(label_for_field("hist", Article), "History") self.assertEqual( label_for_field("hist", Article, return_attr=True), ("History", None) ) self.assertEqual(label_for_field("__str__", Article), "article") with self.assertRaisesMessage( AttributeError, "Unable to lookup 'unknown' on Article" ): label_for_field("unknown", Article) def test_callable(obj): return "nothing" self.assertEqual(label_for_field(test_callable, Article), "Test callable") self.assertEqual( label_for_field(test_callable, Article, return_attr=True), ("Test callable", test_callable), ) self.assertEqual(label_for_field("test_from_model", Article), "Test from model") self.assertEqual( label_for_field("test_from_model", Article, return_attr=True), ("Test from model", Article.test_from_model), ) self.assertEqual( label_for_field("test_from_model_with_override", Article), "not What you Expect", ) self.assertEqual(label_for_field(lambda x: "nothing", Article), "--") self.assertEqual(label_for_field("site_id", Article), "Site id") class MockModelAdmin: @admin.display(description="not Really the Model") def test_from_model(self, obj): return "nothing" self.assertEqual( label_for_field("test_from_model", Article, model_admin=MockModelAdmin), "not Really the Model", ) self.assertEqual( label_for_field( "test_from_model", Article, model_admin=MockModelAdmin, return_attr=True ), ("not Really the Model", MockModelAdmin.test_from_model), ) def test_label_for_field_form_argument(self): class ArticleForm(forms.ModelForm): extra_form_field = forms.BooleanField() class Meta: fields = "__all__" model = Article self.assertEqual( label_for_field("extra_form_field", Article, form=ArticleForm()), "Extra form field", ) msg = "Unable to lookup 'nonexistent' on Article or ArticleForm" with self.assertRaisesMessage(AttributeError, msg): label_for_field("nonexistent", Article, form=ArticleForm()), def test_label_for_property(self): class MockModelAdmin: @property @admin.display(description="property short description") def test_from_property(self): return "this if from property" self.assertEqual( label_for_field("test_from_property", Article, model_admin=MockModelAdmin), "property short description", ) def test_help_text_for_field(self): tests = [ ("article", ""), ("unknown", ""), ("hist", "History help text"), ] for name, help_text in tests: with self.subTest(name=name): self.assertEqual(help_text_for_field(name, Article), help_text) def test_related_name(self): """ Regression test for #13963 """ self.assertEqual( label_for_field("location", Event, return_attr=True), ("location", None), ) self.assertEqual( label_for_field("event", Location, return_attr=True), ("awesome event", None), ) self.assertEqual( label_for_field("guest", Event, return_attr=True), ("awesome guest", None), ) def test_safestring_in_field_label(self): # safestring should not be escaped class MyForm(forms.Form): text = forms.CharField(label=mark_safe("<i>text</i>")) cb = forms.BooleanField(label=mark_safe("<i>cb</i>")) form = MyForm() self.assertHTMLEqual( helpers.AdminField(form, "text", is_first=False).label_tag(), '<label for="id_text" class="required inline"><i>text</i>:</label>', ) self.assertHTMLEqual( helpers.AdminField(form, "cb", is_first=False).label_tag(), '<label for="id_cb" class="vCheckboxLabel required inline">' "<i>cb</i></label>", ) # normal strings needs to be escaped class MyForm(forms.Form): text = forms.CharField(label="&text") cb = forms.BooleanField(label="&cb") form = MyForm() self.assertHTMLEqual( helpers.AdminField(form, "text", is_first=False).label_tag(), '<label for="id_text" class="required inline">&amp;text:</label>', ) self.assertHTMLEqual( helpers.AdminField(form, "cb", is_first=False).label_tag(), '<label for="id_cb" class="vCheckboxLabel required inline">&amp;cb</label>', ) def test_flatten(self): flat_all = ["url", "title", "content", "sites"] inputs = ( ((), []), (("url", "title", ("content", "sites")), flat_all), (("url", "title", "content", "sites"), flat_all), ((("url", "title"), ("content", "sites")), flat_all), ) for orig, expected in inputs: self.assertEqual(flatten(orig), expected) def test_flatten_fieldsets(self): """ Regression test for #18051 """ fieldsets = ((None, {"fields": ("url", "title", ("content", "sites"))}),) self.assertEqual( flatten_fieldsets(fieldsets), ["url", "title", "content", "sites"] ) fieldsets = ((None, {"fields": ("url", "title", ["content", "sites"])}),) self.assertEqual( flatten_fieldsets(fieldsets), ["url", "title", "content", "sites"] ) def test_quote(self): self.assertEqual(quote("something\nor\nother"), "something_0Aor_0Aother") def test_build_q_object_from_lookup_parameters(self): parameters = { "title__in": [["Article 1", "Article 2"]], "hist__iexact": ["history"], "site__pk": [1, 2], } q_obj = build_q_object_from_lookup_parameters(parameters) self.assertEqual( q_obj, models.Q(title__in=["Article 1", "Article 2"]) & models.Q(hist__iexact="history") & (models.Q(site__pk=1) | models.Q(site__pk=2)), )
ba9323c463d5444c079c41a4f46a2efc5102e16fc7ce5b617c34f5b138daecc2
import operator from django.db import DatabaseError, NotSupportedError, connection from django.db.models import Exists, F, IntegerField, OuterRef, Subquery, Value from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from .models import Author, Celebrity, ExtraInfo, Number, ReservedName @skipUnlessDBFeature("supports_select_union") class QuerySetSetOperationTests(TestCase): @classmethod def setUpTestData(cls): Number.objects.bulk_create(Number(num=i, other_num=10 - i) for i in range(10)) def assertNumbersEqual(self, queryset, expected_numbers, ordered=True): self.assertQuerySetEqual( queryset, expected_numbers, operator.attrgetter("num"), ordered ) def test_simple_union(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=8) qs3 = Number.objects.filter(num=5) self.assertNumbersEqual(qs1.union(qs2, qs3), [0, 1, 5, 8, 9], ordered=False) @skipUnlessDBFeature("supports_select_intersection") def test_simple_intersection(self): qs1 = Number.objects.filter(num__lte=5) qs2 = Number.objects.filter(num__gte=5) qs3 = Number.objects.filter(num__gte=4, num__lte=6) self.assertNumbersEqual(qs1.intersection(qs2, qs3), [5], ordered=False) @skipUnlessDBFeature("supports_select_intersection") def test_intersection_with_values(self): ReservedName.objects.create(name="a", order=2) qs1 = ReservedName.objects.all() reserved_name = qs1.intersection(qs1).values("name", "order", "id").get() self.assertEqual(reserved_name["name"], "a") self.assertEqual(reserved_name["order"], 2) reserved_name = qs1.intersection(qs1).values_list("name", "order", "id").get() self.assertEqual(reserved_name[:2], ("a", 2)) @skipUnlessDBFeature("supports_select_difference") def test_simple_difference(self): qs1 = Number.objects.filter(num__lte=5) qs2 = Number.objects.filter(num__lte=4) self.assertNumbersEqual(qs1.difference(qs2), [5], ordered=False) def test_union_distinct(self): qs1 = Number.objects.all() qs2 = Number.objects.all() self.assertEqual(len(list(qs1.union(qs2, all=True))), 20) self.assertEqual(len(list(qs1.union(qs2))), 10) def test_union_none(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=8) qs3 = qs1.union(qs2) self.assertSequenceEqual(qs3.none(), []) self.assertNumbersEqual(qs3, [0, 1, 8, 9], ordered=False) def test_union_none_slice(self): qs1 = Number.objects.filter(num__lte=0) qs2 = Number.objects.none() qs3 = qs1.union(qs2) self.assertNumbersEqual(qs3[:1], [0]) def test_union_empty_filter_slice(self): qs1 = Number.objects.filter(num__lte=0) qs2 = Number.objects.filter(pk__in=[]) qs3 = qs1.union(qs2) self.assertNumbersEqual(qs3[:1], [0]) @skipUnlessDBFeature("supports_slicing_ordering_in_compound") def test_union_slice_compound_empty(self): qs1 = Number.objects.filter(num__lte=0)[:1] qs2 = Number.objects.none() qs3 = qs1.union(qs2) self.assertNumbersEqual(qs3[:1], [0]) @skipUnlessDBFeature("supports_slicing_ordering_in_compound") def test_union_combined_slice_compound_empty(self): qs1 = Number.objects.filter(num__lte=2)[:3] qs2 = Number.objects.none() qs3 = qs1.union(qs2) self.assertNumbersEqual(qs3.order_by("num")[2:3], [2]) def test_union_slice_index(self): Celebrity.objects.create(name="Famous") c1 = Celebrity.objects.create(name="Very famous") qs1 = Celebrity.objects.filter(name="nonexistent") qs2 = Celebrity.objects.all() combined_qs = qs1.union(qs2).order_by("name") self.assertEqual(combined_qs[1], c1) def test_union_order_with_null_first_last(self): Number.objects.filter(other_num=5).update(other_num=None) qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=2) qs3 = qs1.union(qs2) self.assertSequenceEqual( qs3.order_by( F("other_num").asc(nulls_first=True), ).values_list("other_num", flat=True), [None, 1, 2, 3, 4, 6, 7, 8, 9, 10], ) self.assertSequenceEqual( qs3.order_by( F("other_num").asc(nulls_last=True), ).values_list("other_num", flat=True), [1, 2, 3, 4, 6, 7, 8, 9, 10, None], ) def test_union_nested(self): qs1 = Number.objects.all() qs2 = qs1.union(qs1) self.assertNumbersEqual( qs1.union(qs2), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], ordered=False, ) @skipUnlessDBFeature("supports_select_intersection") def test_intersection_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.intersection(qs2)), 0) self.assertEqual(len(qs1.intersection(qs3)), 0) self.assertEqual(len(qs2.intersection(qs1)), 0) self.assertEqual(len(qs3.intersection(qs1)), 0) self.assertEqual(len(qs2.intersection(qs2)), 0) self.assertEqual(len(qs3.intersection(qs3)), 0) @skipUnlessDBFeature("supports_select_difference") def test_difference_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.difference(qs2)), 10) self.assertEqual(len(qs1.difference(qs3)), 10) self.assertEqual(len(qs2.difference(qs1)), 0) self.assertEqual(len(qs3.difference(qs1)), 0) self.assertEqual(len(qs2.difference(qs2)), 0) self.assertEqual(len(qs3.difference(qs3)), 0) @skipUnlessDBFeature("supports_select_difference") def test_difference_with_values(self): ReservedName.objects.create(name="a", order=2) qs1 = ReservedName.objects.all() qs2 = ReservedName.objects.none() reserved_name = qs1.difference(qs2).values("name", "order", "id").get() self.assertEqual(reserved_name["name"], "a") self.assertEqual(reserved_name["order"], 2) reserved_name = qs1.difference(qs2).values_list("name", "order", "id").get() self.assertEqual(reserved_name[:2], ("a", 2)) def test_union_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.union(qs2)), 10) self.assertEqual(len(qs2.union(qs1)), 10) self.assertEqual(len(qs1.union(qs3)), 10) self.assertEqual(len(qs3.union(qs1)), 10) self.assertEqual(len(qs2.union(qs1, qs1, qs1)), 10) self.assertEqual(len(qs2.union(qs1, qs1, all=True)), 20) self.assertEqual(len(qs2.union(qs2)), 0) self.assertEqual(len(qs3.union(qs3)), 0) def test_empty_qs_union_with_ordered_qs(self): qs1 = Number.objects.order_by("num") qs2 = Number.objects.none().union(qs1).order_by("num") self.assertEqual(list(qs1), list(qs2)) def test_limits(self): qs1 = Number.objects.all() qs2 = Number.objects.all() self.assertEqual(len(list(qs1.union(qs2)[:2])), 2) def test_ordering(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=2, num__lte=3) self.assertNumbersEqual(qs1.union(qs2).order_by("-num"), [3, 2, 1, 0]) def test_ordering_by_alias(self): qs1 = Number.objects.filter(num__lte=1).values(alias=F("num")) qs2 = Number.objects.filter(num__gte=2, num__lte=3).values(alias=F("num")) self.assertQuerySetEqual( qs1.union(qs2).order_by("-alias"), [3, 2, 1, 0], operator.itemgetter("alias"), ) def test_ordering_by_f_expression(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=2, num__lte=3) self.assertNumbersEqual(qs1.union(qs2).order_by(F("num").desc()), [3, 2, 1, 0]) def test_ordering_by_f_expression_and_alias(self): qs1 = Number.objects.filter(num__lte=1).values(alias=F("other_num")) qs2 = Number.objects.filter(num__gte=2, num__lte=3).values(alias=F("other_num")) self.assertQuerySetEqual( qs1.union(qs2).order_by(F("alias").desc()), [10, 9, 8, 7], operator.itemgetter("alias"), ) Number.objects.create(num=-1) self.assertQuerySetEqual( qs1.union(qs2).order_by(F("alias").desc(nulls_last=True)), [10, 9, 8, 7, None], operator.itemgetter("alias"), ) def test_union_with_values(self): ReservedName.objects.create(name="a", order=2) qs1 = ReservedName.objects.all() reserved_name = qs1.union(qs1).values("name", "order", "id").get() self.assertEqual(reserved_name["name"], "a") self.assertEqual(reserved_name["order"], 2) reserved_name = qs1.union(qs1).values_list("name", "order", "id").get() self.assertEqual(reserved_name[:2], ("a", 2)) # List of columns can be changed. reserved_name = qs1.union(qs1).values_list("order").get() self.assertEqual(reserved_name, (2,)) def test_union_with_two_annotated_values_list(self): qs1 = ( Number.objects.filter(num=1) .annotate( count=Value(0, IntegerField()), ) .values_list("num", "count") ) qs2 = ( Number.objects.filter(num=2) .values("pk") .annotate( count=F("num"), ) .annotate( num=Value(1, IntegerField()), ) .values_list("num", "count") ) self.assertCountEqual(qs1.union(qs2), [(1, 0), (1, 2)]) def test_union_with_extra_and_values_list(self): qs1 = ( Number.objects.filter(num=1) .extra( select={"count": 0}, ) .values_list("num", "count") ) qs2 = Number.objects.filter(num=2).extra(select={"count": 1}) self.assertCountEqual(qs1.union(qs2), [(1, 0), (2, 1)]) def test_union_with_values_list_on_annotated_and_unannotated(self): ReservedName.objects.create(name="rn1", order=1) qs1 = Number.objects.annotate( has_reserved_name=Exists(ReservedName.objects.filter(order=OuterRef("num"))) ).filter(has_reserved_name=True) qs2 = Number.objects.filter(num=9) self.assertCountEqual(qs1.union(qs2).values_list("num", flat=True), [1, 9]) def test_union_with_values_list_and_order(self): ReservedName.objects.bulk_create( [ ReservedName(name="rn1", order=7), ReservedName(name="rn2", order=5), ReservedName(name="rn0", order=6), ReservedName(name="rn9", order=-1), ] ) qs1 = ReservedName.objects.filter(order__gte=6) qs2 = ReservedName.objects.filter(order__lte=5) union_qs = qs1.union(qs2) for qs, expected_result in ( # Order by a single column. (union_qs.order_by("-pk").values_list("order", flat=True), [-1, 6, 5, 7]), (union_qs.order_by("pk").values_list("order", flat=True), [7, 5, 6, -1]), (union_qs.values_list("order", flat=True).order_by("-pk"), [-1, 6, 5, 7]), (union_qs.values_list("order", flat=True).order_by("pk"), [7, 5, 6, -1]), # Order by multiple columns. ( union_qs.order_by("-name", "pk").values_list("order", flat=True), [-1, 5, 7, 6], ), ( union_qs.values_list("order", flat=True).order_by("-name", "pk"), [-1, 5, 7, 6], ), ): with self.subTest(qs=qs): self.assertEqual(list(qs), expected_result) def test_union_with_values_list_and_order_on_annotation(self): qs1 = Number.objects.annotate( annotation=Value(-1), multiplier=F("annotation"), ).filter(num__gte=6) qs2 = Number.objects.annotate( annotation=Value(2), multiplier=F("annotation"), ).filter(num__lte=5) self.assertSequenceEqual( qs1.union(qs2).order_by("annotation", "num").values_list("num", flat=True), [6, 7, 8, 9, 0, 1, 2, 3, 4, 5], ) self.assertQuerySetEqual( qs1.union(qs2) .order_by( F("annotation") * F("multiplier"), "num", ) .values("num"), [6, 7, 8, 9, 0, 1, 2, 3, 4, 5], operator.itemgetter("num"), ) def test_union_with_select_related_and_order(self): e1 = ExtraInfo.objects.create(value=7, info="e1") a1 = Author.objects.create(name="a1", num=1, extra=e1) a2 = Author.objects.create(name="a2", num=3, extra=e1) Author.objects.create(name="a3", num=2, extra=e1) base_qs = Author.objects.select_related("extra").order_by() qs1 = base_qs.filter(name="a1") qs2 = base_qs.filter(name="a2") self.assertSequenceEqual(qs1.union(qs2).order_by("pk"), [a1, a2]) @skipUnlessDBFeature("supports_slicing_ordering_in_compound") def test_union_with_select_related_and_first(self): e1 = ExtraInfo.objects.create(value=7, info="e1") a1 = Author.objects.create(name="a1", num=1, extra=e1) Author.objects.create(name="a2", num=3, extra=e1) base_qs = Author.objects.select_related("extra").order_by() qs1 = base_qs.filter(name="a1") qs2 = base_qs.filter(name="a2") self.assertEqual(qs1.union(qs2).order_by("name").first(), a1) def test_union_with_first(self): e1 = ExtraInfo.objects.create(value=7, info="e1") a1 = Author.objects.create(name="a1", num=1, extra=e1) base_qs = Author.objects.order_by() qs1 = base_qs.filter(name="a1") qs2 = base_qs.filter(name="a2") self.assertEqual(qs1.union(qs2).first(), a1) def test_union_multiple_models_with_values_list_and_order(self): reserved_name = ReservedName.objects.create(name="rn1", order=0) qs1 = Celebrity.objects.all() qs2 = ReservedName.objects.all() self.assertSequenceEqual( qs1.union(qs2).order_by("name").values_list("pk", flat=True), [reserved_name.pk], ) def test_union_multiple_models_with_values_list_and_order_by_extra_select(self): reserved_name = ReservedName.objects.create(name="rn1", order=0) qs1 = Celebrity.objects.extra(select={"extra_name": "name"}) qs2 = ReservedName.objects.extra(select={"extra_name": "name"}) self.assertSequenceEqual( qs1.union(qs2).order_by("extra_name").values_list("pk", flat=True), [reserved_name.pk], ) def test_union_multiple_models_with_values_list_and_annotations(self): ReservedName.objects.create(name="rn1", order=10) Celebrity.objects.create(name="c1") qs1 = ReservedName.objects.annotate(row_type=Value("rn")).values_list( "name", "order", "row_type" ) qs2 = Celebrity.objects.annotate( row_type=Value("cb"), order=Value(-10) ).values_list("name", "order", "row_type") self.assertSequenceEqual( qs1.union(qs2).order_by("order"), [("c1", -10, "cb"), ("rn1", 10, "rn")], ) def test_union_in_subquery(self): ReservedName.objects.bulk_create( [ ReservedName(name="rn1", order=8), ReservedName(name="rn2", order=1), ReservedName(name="rn3", order=5), ] ) qs1 = Number.objects.filter(num__gt=7, num=OuterRef("order")) qs2 = Number.objects.filter(num__lt=2, num=OuterRef("order")) self.assertCountEqual( ReservedName.objects.annotate( number=Subquery(qs1.union(qs2).values("num")), ) .filter(number__isnull=False) .values_list("order", flat=True), [8, 1], ) def test_union_in_subquery_related_outerref(self): e1 = ExtraInfo.objects.create(value=7, info="e3") e2 = ExtraInfo.objects.create(value=5, info="e2") e3 = ExtraInfo.objects.create(value=1, info="e1") Author.objects.bulk_create( [ Author(name="a1", num=1, extra=e1), Author(name="a2", num=3, extra=e2), Author(name="a3", num=2, extra=e3), ] ) qs1 = ExtraInfo.objects.order_by().filter(value=OuterRef("num")) qs2 = ExtraInfo.objects.order_by().filter(value__lt=OuterRef("extra__value")) qs = ( Author.objects.annotate( info=Subquery(qs1.union(qs2).values("info")[:1]), ) .filter(info__isnull=False) .values_list("name", flat=True) ) self.assertCountEqual(qs, ["a1", "a2"]) # Combined queries don't mutate. self.assertCountEqual(qs, ["a1", "a2"]) @skipUnlessDBFeature("supports_slicing_ordering_in_compound") def test_union_in_with_ordering(self): qs1 = Number.objects.filter(num__gt=7).order_by("num") qs2 = Number.objects.filter(num__lt=2).order_by("num") self.assertNumbersEqual( Number.objects.exclude(id__in=qs1.union(qs2).values("id")), [2, 3, 4, 5, 6, 7], ordered=False, ) @skipUnlessDBFeature( "supports_slicing_ordering_in_compound", "allow_sliced_subqueries_with_in" ) def test_union_in_with_ordering_and_slice(self): qs1 = Number.objects.filter(num__gt=7).order_by("num")[:1] qs2 = Number.objects.filter(num__lt=2).order_by("-num")[:1] self.assertNumbersEqual( Number.objects.exclude(id__in=qs1.union(qs2).values("id")), [0, 2, 3, 4, 5, 6, 7, 9], ordered=False, ) def test_count_union(self): qs1 = Number.objects.filter(num__lte=1).values("num") qs2 = Number.objects.filter(num__gte=2, num__lte=3).values("num") self.assertEqual(qs1.union(qs2).count(), 4) def test_count_union_empty_result(self): qs = Number.objects.filter(pk__in=[]) self.assertEqual(qs.union(qs).count(), 0) def test_count_union_with_select_related(self): e1 = ExtraInfo.objects.create(value=1, info="e1") Author.objects.create(name="a1", num=1, extra=e1) qs = Author.objects.select_related("extra").order_by() self.assertEqual(qs.union(qs).count(), 1) @skipUnlessDBFeature("supports_select_difference") def test_count_difference(self): qs1 = Number.objects.filter(num__lt=10) qs2 = Number.objects.filter(num__lt=9) self.assertEqual(qs1.difference(qs2).count(), 1) @skipUnlessDBFeature("supports_select_intersection") def test_count_intersection(self): qs1 = Number.objects.filter(num__gte=5) qs2 = Number.objects.filter(num__lte=5) self.assertEqual(qs1.intersection(qs2).count(), 1) def test_exists_union(self): qs1 = Number.objects.filter(num__gte=5) qs2 = Number.objects.filter(num__lte=5) with CaptureQueriesContext(connection) as context: self.assertIs(qs1.union(qs2).exists(), True) captured_queries = context.captured_queries self.assertEqual(len(captured_queries), 1) captured_sql = captured_queries[0]["sql"] self.assertNotIn( connection.ops.quote_name(Number._meta.pk.column), captured_sql, ) self.assertEqual( captured_sql.count(connection.ops.limit_offset_sql(None, 1)), 1 ) def test_exists_union_empty_result(self): qs = Number.objects.filter(pk__in=[]) self.assertIs(qs.union(qs).exists(), False) @skipUnlessDBFeature("supports_select_intersection") def test_exists_intersection(self): qs1 = Number.objects.filter(num__gt=5) qs2 = Number.objects.filter(num__lt=5) self.assertIs(qs1.intersection(qs1).exists(), True) self.assertIs(qs1.intersection(qs2).exists(), False) @skipUnlessDBFeature("supports_select_difference") def test_exists_difference(self): qs1 = Number.objects.filter(num__gte=5) qs2 = Number.objects.filter(num__gte=3) self.assertIs(qs1.difference(qs2).exists(), False) self.assertIs(qs2.difference(qs1).exists(), True) def test_get_union(self): qs = Number.objects.filter(num=2) self.assertEqual(qs.union(qs).get().num, 2) @skipUnlessDBFeature("supports_select_difference") def test_get_difference(self): qs1 = Number.objects.all() qs2 = Number.objects.exclude(num=2) self.assertEqual(qs1.difference(qs2).get().num, 2) @skipUnlessDBFeature("supports_select_intersection") def test_get_intersection(self): qs1 = Number.objects.all() qs2 = Number.objects.filter(num=2) self.assertEqual(qs1.intersection(qs2).get().num, 2) @skipUnlessDBFeature("supports_slicing_ordering_in_compound") def test_ordering_subqueries(self): qs1 = Number.objects.order_by("num")[:2] qs2 = Number.objects.order_by("-num")[:2] self.assertNumbersEqual(qs1.union(qs2).order_by("-num")[:4], [9, 8, 1, 0]) @skipIfDBFeature("supports_slicing_ordering_in_compound") def test_unsupported_ordering_slicing_raises_db_error(self): qs1 = Number.objects.all() qs2 = Number.objects.all() qs3 = Number.objects.all() msg = "LIMIT/OFFSET not allowed in subqueries of compound statements" with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2[:10])) msg = "ORDER BY not allowed in subqueries of compound statements" with self.assertRaisesMessage(DatabaseError, msg): list(qs1.order_by("id").union(qs2)) with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by("id").union(qs3)) @skipIfDBFeature("supports_select_intersection") def test_unsupported_intersection_raises_db_error(self): qs1 = Number.objects.all() qs2 = Number.objects.all() msg = "intersection is not supported on this database backend" with self.assertRaisesMessage(NotSupportedError, msg): list(qs1.intersection(qs2)) def test_combining_multiple_models(self): ReservedName.objects.create(name="99 little bugs", order=99) qs1 = Number.objects.filter(num=1).values_list("num", flat=True) qs2 = ReservedName.objects.values_list("order") self.assertEqual(list(qs1.union(qs2).order_by("num")), [1, 99]) def test_order_raises_on_non_selected_column(self): qs1 = ( Number.objects.filter() .annotate( annotation=Value(1, IntegerField()), ) .values("annotation", num2=F("num")) ) qs2 = Number.objects.filter().values("id", "num") # Should not raise list(qs1.union(qs2).order_by("annotation")) list(qs1.union(qs2).order_by("num2")) msg = "ORDER BY term does not match any column in the result set" # 'id' is not part of the select with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by("id")) # 'num' got realiased to num2 with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by("num")) with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by(F("num"))) with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by(F("num").desc())) # switched order, now 'exists' again: list(qs2.union(qs1).order_by("num")) @skipUnlessDBFeature("supports_select_difference", "supports_select_intersection") def test_qs_with_subcompound_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.intersection(Number.objects.filter(num__gt=1)) self.assertEqual(qs1.difference(qs2).count(), 2) def test_order_by_same_type(self): qs = Number.objects.all() union = qs.union(qs) numbers = list(range(10)) self.assertNumbersEqual(union.order_by("num"), numbers) self.assertNumbersEqual(union.order_by("other_num"), reversed(numbers)) def test_unsupported_operations_on_combined_qs(self): qs = Number.objects.all() msg = "Calling QuerySet.%s() after %s() is not supported." combinators = ["union"] if connection.features.supports_select_difference: combinators.append("difference") if connection.features.supports_select_intersection: combinators.append("intersection") for combinator in combinators: for operation in ( "alias", "annotate", "defer", "delete", "distinct", "exclude", "extra", "filter", "only", "prefetch_related", "select_related", "update", ): with self.subTest(combinator=combinator, operation=operation): with self.assertRaisesMessage( NotSupportedError, msg % (operation, combinator), ): getattr(getattr(qs, combinator)(qs), operation)() with self.assertRaisesMessage( NotSupportedError, msg % ("contains", combinator), ): obj = Number.objects.first() getattr(qs, combinator)(qs).contains(obj) def test_get_with_filters_unsupported_on_combined_qs(self): qs = Number.objects.all() msg = "Calling QuerySet.get(...) with filters after %s() is not supported." combinators = ["union"] if connection.features.supports_select_difference: combinators.append("difference") if connection.features.supports_select_intersection: combinators.append("intersection") for combinator in combinators: with self.subTest(combinator=combinator): with self.assertRaisesMessage(NotSupportedError, msg % combinator): getattr(qs, combinator)(qs).get(num=2) def test_operator_on_combined_qs_error(self): qs = Number.objects.all() msg = "Cannot use %s operator with combined queryset." combinators = ["union"] if connection.features.supports_select_difference: combinators.append("difference") if connection.features.supports_select_intersection: combinators.append("intersection") operators = [ ("|", operator.or_), ("&", operator.and_), ("^", operator.xor), ] for combinator in combinators: combined_qs = getattr(qs, combinator)(qs) for operator_, operator_func in operators: with self.subTest(combinator=combinator): with self.assertRaisesMessage(TypeError, msg % operator_): operator_func(qs, combined_qs) with self.assertRaisesMessage(TypeError, msg % operator_): operator_func(combined_qs, qs)
05d2beb6c8c8e1e094e0ae0f4768ebf34cbc950ca0f20dc36cb1a96db894b037
import sys from django.template import Context, Engine, TemplateDoesNotExist, TemplateSyntaxError from django.template.base import UNKNOWN_SOURCE from django.test import SimpleTestCase, override_settings from django.urls import NoReverseMatch from django.utils import translation from django.utils.html import escape class TemplateTestMixin: def _engine(self, **kwargs): return Engine(debug=self.debug_engine, **kwargs) def test_string_origin(self): template = self._engine().from_string("string template") self.assertEqual(template.origin.name, UNKNOWN_SOURCE) self.assertIsNone(template.origin.loader_name) self.assertEqual(template.source, "string template") @override_settings(SETTINGS_MODULE=None) def test_url_reverse_no_settings_module(self): """ #9005 -- url tag shouldn't require settings.SETTINGS_MODULE to be set. """ t = self._engine().from_string("{% url will_not_match %}") c = Context() with self.assertRaises(NoReverseMatch): t.render(c) def test_url_reverse_view_name(self): """ #19827 -- url tag should keep original stack trace when reraising exception. """ t = self._engine().from_string("{% url will_not_match %}") c = Context() try: t.render(c) except NoReverseMatch: tb = sys.exc_info()[2] depth = 0 while tb.tb_next is not None: tb = tb.tb_next depth += 1 self.assertGreater( depth, 5, "The traceback context was lost when reraising the traceback." ) def test_no_wrapped_exception(self): """ # 16770 -- The template system doesn't wrap exceptions, but annotates them. """ engine = self._engine() c = Context({"coconuts": lambda: 42 / 0}) t = engine.from_string("{{ coconuts }}") with self.assertRaises(ZeroDivisionError) as e: t.render(c) if self.debug_engine: debug = e.exception.template_debug self.assertEqual(debug["start"], 0) self.assertEqual(debug["end"], 14) def test_invalid_block_suggestion(self): """ Error messages should include the unexpected block name and be in all English. """ engine = self._engine() msg = ( "Invalid block tag on line 1: 'endblock', expected 'elif', 'else' " "or 'endif'. Did you forget to register or load this tag?" ) with self.settings(USE_I18N=True), translation.override("de"): with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.from_string("{% if 1 %}lala{% endblock %}{% endif %}") def test_unknown_block_tag(self): engine = self._engine() msg = ( "Invalid block tag on line 1: 'foobar'. Did you forget to " "register or load this tag?" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.from_string("lala{% foobar %}") def test_compile_filter_expression_error(self): """ 19819 -- Make sure the correct token is highlighted for FilterExpression errors. """ engine = self._engine() msg = "Could not parse the remainder: '@bar' from 'foo@bar'" with self.assertRaisesMessage(TemplateSyntaxError, msg) as e: engine.from_string("{% if 1 %}{{ foo@bar }}{% endif %}") if self.debug_engine: debug = e.exception.template_debug self.assertEqual((debug["start"], debug["end"]), (10, 23)) self.assertEqual((debug["during"]), "{{ foo@bar }}") def test_compile_tag_error(self): """ Errors raised while compiling nodes should include the token information. """ engine = self._engine( libraries={"bad_tag": "template_tests.templatetags.bad_tag"}, ) with self.assertRaises(RuntimeError) as e: engine.from_string("{% load bad_tag %}{% badtag %}") if self.debug_engine: self.assertEqual(e.exception.template_debug["during"], "{% badtag %}") def test_compile_tag_error_27584(self): engine = self._engine( app_dirs=True, libraries={"tag_27584": "template_tests.templatetags.tag_27584"}, ) t = engine.get_template("27584_parent.html") with self.assertRaises(TemplateSyntaxError) as e: t.render(Context()) if self.debug_engine: self.assertEqual(e.exception.template_debug["during"], "{% badtag %}") def test_compile_tag_error_27956(self): """Errors in a child of {% extends %} are displayed correctly.""" engine = self._engine( app_dirs=True, libraries={"tag_27584": "template_tests.templatetags.tag_27584"}, ) t = engine.get_template("27956_child.html") with self.assertRaises(TemplateSyntaxError) as e: t.render(Context()) if self.debug_engine: self.assertEqual(e.exception.template_debug["during"], "{% badtag %}") def test_render_tag_error_in_extended_block(self): """Errors in extended block are displayed correctly.""" e = self._engine(app_dirs=True) template = e.get_template("test_extends_block_error.html") context = Context() with self.assertRaises(TemplateDoesNotExist) as cm: template.render(context) if self.debug_engine: self.assertEqual( cm.exception.template_debug["during"], escape('{% include "missing.html" %}'), ) def test_super_errors(self): """ #18169 -- NoReverseMatch should not be silence in block.super. """ engine = self._engine(app_dirs=True) t = engine.get_template("included_content.html") with self.assertRaises(NoReverseMatch): t.render(Context()) def test_extends_generic_template(self): """ #24338 -- Allow extending django.template.backends.django.Template objects. """ engine = self._engine() parent = engine.from_string("{% block content %}parent{% endblock %}") child = engine.from_string( "{% extends parent %}{% block content %}child{% endblock %}" ) self.assertEqual(child.render(Context({"parent": parent})), "child") def test_node_origin(self): """ #25848 -- Set origin on Node so debugging tools can determine which template the node came from even if extending or including templates. """ template = self._engine().from_string("content") for node in template.nodelist: self.assertEqual(node.origin, template.origin) def test_render_built_in_type_method(self): """ Templates should not crash when rendering methods for built-in types without required arguments. """ template = self._engine().from_string("{{ description.count }}") self.assertEqual(template.render(Context({"description": "test"})), "") class TemplateTests(TemplateTestMixin, SimpleTestCase): debug_engine = False class DebugTemplateTests(TemplateTestMixin, SimpleTestCase): debug_engine = True
4d5a5362ba1ad040393dcddaff5cdb83b1a23937658ab4036d06e866680ec7dc
from django.contrib.admin import ModelAdmin, TabularInline from django.contrib.admin.helpers import InlineAdminForm from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.test import RequestFactory, TestCase, override_settings from django.urls import reverse from .admin import InnerInline from .admin import site as admin_site from .models import ( Author, BinaryTree, Book, BothVerboseNameProfile, Chapter, Child, ChildModel1, ChildModel2, Fashionista, FootNote, Holder, Holder2, Holder3, Holder4, Inner, Inner2, Inner3, Inner4Stacked, Inner4Tabular, Novel, OutfitItem, Parent, ParentModelWithCustomPk, Person, Poll, Profile, ProfileCollection, Question, ShowInlineParent, Sighting, SomeChildModel, SomeParentModel, Teacher, VerboseNamePluralProfile, VerboseNameProfile, ) INLINE_CHANGELINK_HTML = 'class="inlinechangelink">Change</a>' class TestDataMixin: @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", email="[email protected]", password="secret" ) @override_settings(ROOT_URLCONF="admin_inlines.urls") class TestInline(TestDataMixin, TestCase): factory = RequestFactory() @classmethod def setUpTestData(cls): super().setUpTestData() cls.holder = Holder.objects.create(dummy=13) Inner.objects.create(dummy=42, holder=cls.holder) cls.parent = SomeParentModel.objects.create(name="a") SomeChildModel.objects.create(name="b", position="0", parent=cls.parent) SomeChildModel.objects.create(name="c", position="1", parent=cls.parent) cls.view_only_user = User.objects.create_user( username="user", password="pwd", is_staff=True, ) parent_ct = ContentType.objects.get_for_model(SomeParentModel) child_ct = ContentType.objects.get_for_model(SomeChildModel) permission = Permission.objects.get( codename="view_someparentmodel", content_type=parent_ct, ) cls.view_only_user.user_permissions.add(permission) permission = Permission.objects.get( codename="view_somechildmodel", content_type=child_ct, ) cls.view_only_user.user_permissions.add(permission) def setUp(self): self.client.force_login(self.superuser) def test_can_delete(self): """ can_delete should be passed to inlineformset factory. """ response = self.client.get( reverse("admin:admin_inlines_holder_change", args=(self.holder.id,)) ) inner_formset = response.context["inline_admin_formsets"][0].formset expected = InnerInline.can_delete actual = inner_formset.can_delete self.assertEqual(expected, actual, "can_delete must be equal") def test_readonly_stacked_inline_label(self): """Bug #13174.""" holder = Holder.objects.create(dummy=42) Inner.objects.create(holder=holder, dummy=42, readonly="") response = self.client.get( reverse("admin:admin_inlines_holder_change", args=(holder.id,)) ) self.assertContains(response, "<label>Inner readonly label:</label>") def test_many_to_many_inlines(self): "Autogenerated many-to-many inlines are displayed correctly (#13407)" response = self.client.get(reverse("admin:admin_inlines_author_add")) # The heading for the m2m inline block uses the right text self.assertContains(response, "<h2>Author-book relationships</h2>") # The "add another" label is correct self.assertContains(response, "Add another Author-book relationship") # The '+' is dropped from the autogenerated form prefix (Author_books+) self.assertContains(response, 'id="id_Author_books-TOTAL_FORMS"') def test_inline_primary(self): person = Person.objects.create(firstname="Imelda") item = OutfitItem.objects.create(name="Shoes") # Imelda likes shoes, but can't carry her own bags. data = { "shoppingweakness_set-TOTAL_FORMS": 1, "shoppingweakness_set-INITIAL_FORMS": 0, "shoppingweakness_set-MAX_NUM_FORMS": 0, "_save": "Save", "person": person.id, "max_weight": 0, "shoppingweakness_set-0-item": item.id, } response = self.client.post( reverse("admin:admin_inlines_fashionista_add"), data ) self.assertEqual(response.status_code, 302) self.assertEqual(len(Fashionista.objects.filter(person__firstname="Imelda")), 1) def test_tabular_inline_column_css_class(self): """ Field names are included in the context to output a field-specific CSS class name in the column headers. """ response = self.client.get(reverse("admin:admin_inlines_poll_add")) text_field, call_me_field = list( response.context["inline_admin_formset"].fields() ) # Editable field. self.assertEqual(text_field["name"], "text") self.assertContains(response, '<th class="column-text required">') # Read-only field. self.assertEqual(call_me_field["name"], "call_me") self.assertContains(response, '<th class="column-call_me">') def test_custom_form_tabular_inline_label(self): """ A model form with a form field specified (TitleForm.title1) should have its label rendered in the tabular inline. """ response = self.client.get(reverse("admin:admin_inlines_titlecollection_add")) self.assertContains( response, '<th class="column-title1 required">Title1</th>', html=True ) def test_custom_form_tabular_inline_extra_field_label(self): response = self.client.get(reverse("admin:admin_inlines_outfititem_add")) _, extra_field = list(response.context["inline_admin_formset"].fields()) self.assertEqual(extra_field["label"], "Extra field") def test_non_editable_custom_form_tabular_inline_extra_field_label(self): response = self.client.get(reverse("admin:admin_inlines_chapter_add")) _, extra_field = list(response.context["inline_admin_formset"].fields()) self.assertEqual(extra_field["label"], "Extra field") def test_custom_form_tabular_inline_overridden_label(self): """ SomeChildModelForm.__init__() overrides the label of a form field. That label is displayed in the TabularInline. """ response = self.client.get(reverse("admin:admin_inlines_someparentmodel_add")) field = list(response.context["inline_admin_formset"].fields())[0] self.assertEqual(field["label"], "new label") self.assertContains( response, '<th class="column-name required">New label</th>', html=True ) def test_tabular_non_field_errors(self): """ non_field_errors are displayed correctly, including the correct value for colspan. """ data = { "title_set-TOTAL_FORMS": 1, "title_set-INITIAL_FORMS": 0, "title_set-MAX_NUM_FORMS": 0, "_save": "Save", "title_set-0-title1": "a title", "title_set-0-title2": "a different title", } response = self.client.post( reverse("admin:admin_inlines_titlecollection_add"), data ) # Here colspan is "4": two fields (title1 and title2), one hidden field # and the delete checkbox. self.assertContains( response, '<tr class="row-form-errors"><td colspan="4">' '<ul class="errorlist nonfield">' "<li>The two titles must be the same</li></ul></td></tr>", ) def test_no_parent_callable_lookup(self): """Admin inline `readonly_field` shouldn't invoke parent ModelAdmin callable""" # Identically named callable isn't present in the parent ModelAdmin, # rendering of the add view shouldn't explode response = self.client.get(reverse("admin:admin_inlines_novel_add")) # View should have the child inlines section self.assertContains( response, '<div class="js-inline-admin-formset inline-group" id="chapter_set-group"', ) def test_callable_lookup(self): """ Admin inline should invoke local callable when its name is listed in readonly_fields. """ response = self.client.get(reverse("admin:admin_inlines_poll_add")) # Add parent object view should have the child inlines section self.assertContains( response, '<div class="js-inline-admin-formset inline-group" id="question_set-group"', ) # The right callable should be used for the inline readonly_fields # column cells self.assertContains(response, "<p>Callable in QuestionInline</p>") def test_model_error_inline_with_readonly_field(self): poll = Poll.objects.create(name="Test poll") data = { "question_set-TOTAL_FORMS": 1, "question_set-INITIAL_FORMS": 0, "question_set-MAX_NUM_FORMS": 0, "_save": "Save", "question_set-0-text": "Question", "question_set-0-poll": poll.pk, } response = self.client.post( reverse("admin:admin_inlines_poll_change", args=(poll.pk,)), data, ) self.assertContains(response, "Always invalid model.") def test_help_text(self): """ The inlines' model field help texts are displayed when using both the stacked and tabular layouts. """ response = self.client.get(reverse("admin:admin_inlines_holder4_add")) self.assertContains(response, "Awesome stacked help text is awesome.", 4) self.assertContains( response, '<img src="/static/admin/img/icon-unknown.svg" ' 'class="help help-tooltip" width="10" height="10" ' 'alt="(Awesome tabular help text is awesome.)" ' 'title="Awesome tabular help text is awesome.">', 1, ) # ReadOnly fields response = self.client.get(reverse("admin:admin_inlines_capofamiglia_add")) self.assertContains( response, '<img src="/static/admin/img/icon-unknown.svg" ' 'class="help help-tooltip" width="10" height="10" ' 'alt="(Help text for ReadOnlyInline)" ' 'title="Help text for ReadOnlyInline">', 1, ) def test_tabular_model_form_meta_readonly_field(self): """ Tabular inlines use ModelForm.Meta.help_texts and labels for read-only fields. """ response = self.client.get(reverse("admin:admin_inlines_someparentmodel_add")) self.assertContains( response, '<img src="/static/admin/img/icon-unknown.svg" ' 'class="help help-tooltip" width="10" height="10" ' 'alt="(Help text from ModelForm.Meta)" ' 'title="Help text from ModelForm.Meta">', ) self.assertContains(response, "Label from ModelForm.Meta") def test_inline_hidden_field_no_column(self): """#18263 -- Make sure hidden fields don't get a column in tabular inlines""" parent = SomeParentModel.objects.create(name="a") SomeChildModel.objects.create(name="b", position="0", parent=parent) SomeChildModel.objects.create(name="c", position="1", parent=parent) response = self.client.get( reverse("admin:admin_inlines_someparentmodel_change", args=(parent.pk,)) ) self.assertNotContains(response, '<td class="field-position">') self.assertInHTML( '<input id="id_somechildmodel_set-1-position" ' 'name="somechildmodel_set-1-position" type="hidden" value="1">', response.rendered_content, ) def test_tabular_inline_hidden_field_with_view_only_permissions(self): """ Content of hidden field is not visible in tabular inline when user has view-only permission. """ self.client.force_login(self.view_only_user) url = reverse( "tabular_inline_hidden_field_admin:admin_inlines_someparentmodel_change", args=(self.parent.pk,), ) response = self.client.get(url) self.assertInHTML( '<th class="column-position hidden">Position</th>', response.rendered_content, ) self.assertInHTML( '<td class="field-position hidden"><p>0</p></td>', response.rendered_content ) self.assertInHTML( '<td class="field-position hidden"><p>1</p></td>', response.rendered_content ) def test_stacked_inline_hidden_field_with_view_only_permissions(self): """ Content of hidden field is not visible in stacked inline when user has view-only permission. """ self.client.force_login(self.view_only_user) url = reverse( "stacked_inline_hidden_field_in_group_admin:" "admin_inlines_someparentmodel_change", args=(self.parent.pk,), ) response = self.client.get(url) # The whole line containing name + position fields is not hidden. self.assertContains( response, '<div class="form-row field-name field-position">' ) # The div containing the position field is hidden. self.assertInHTML( '<div class="flex-container fieldBox field-position hidden">' '<label class="inline">Position:</label>' '<div class="readonly">0</div></div>', response.rendered_content, ) self.assertInHTML( '<div class="flex-container fieldBox field-position hidden">' '<label class="inline">Position:</label>' '<div class="readonly">1</div></div>', response.rendered_content, ) def test_stacked_inline_single_hidden_field_in_line_with_view_only_permissions( self, ): """ Content of hidden field is not visible in stacked inline when user has view-only permission and the field is grouped on a separate line. """ self.client.force_login(self.view_only_user) url = reverse( "stacked_inline_hidden_field_on_single_line_admin:" "admin_inlines_someparentmodel_change", args=(self.parent.pk,), ) response = self.client.get(url) # The whole line containing position field is hidden. self.assertInHTML( '<div class="form-row hidden field-position">' '<div><div class="flex-container"><label>Position:</label>' '<div class="readonly">0</div></div></div></div>', response.rendered_content, ) self.assertInHTML( '<div class="form-row hidden field-position">' '<div><div class="flex-container"><label>Position:</label>' '<div class="readonly">1</div></div></div></div>', response.rendered_content, ) def test_tabular_inline_with_hidden_field_non_field_errors_has_correct_colspan( self, ): """ In tabular inlines, when a form has non-field errors, those errors are rendered in a table line with a single cell spanning the whole table width. Colspan must be equal to the number of visible columns. """ parent = SomeParentModel.objects.create(name="a") child = SomeChildModel.objects.create(name="b", position="0", parent=parent) url = reverse( "tabular_inline_hidden_field_admin:admin_inlines_someparentmodel_change", args=(parent.id,), ) data = { "name": parent.name, "somechildmodel_set-TOTAL_FORMS": 1, "somechildmodel_set-INITIAL_FORMS": 1, "somechildmodel_set-MIN_NUM_FORMS": 0, "somechildmodel_set-MAX_NUM_FORMS": 1000, "_save": "Save", "somechildmodel_set-0-id": child.id, "somechildmodel_set-0-parent": parent.id, "somechildmodel_set-0-name": child.name, "somechildmodel_set-0-position": 1, } response = self.client.post(url, data) # Form has 3 visible columns and 1 hidden column. self.assertInHTML( '<thead><tr><th class="original"></th>' '<th class="column-name required">Name</th>' '<th class="column-position required hidden">Position</th>' "<th>Delete?</th></tr></thead>", response.rendered_content, ) # The non-field error must be spanned on 3 (visible) columns. self.assertInHTML( '<tr class="row-form-errors"><td colspan="3">' '<ul class="errorlist nonfield"><li>A non-field error</li></ul></td></tr>', response.rendered_content, ) def test_non_related_name_inline(self): """ Multiple inlines with related_name='+' have correct form prefixes. """ response = self.client.get(reverse("admin:admin_inlines_capofamiglia_add")) self.assertContains( response, '<input type="hidden" name="-1-0-id" id="id_-1-0-id">', html=True ) self.assertContains( response, '<input type="hidden" name="-1-0-capo_famiglia" ' 'id="id_-1-0-capo_famiglia">', html=True, ) self.assertContains( response, '<input id="id_-1-0-name" type="text" class="vTextField" name="-1-0-name" ' 'maxlength="100">', html=True, ) self.assertContains( response, '<input type="hidden" name="-2-0-id" id="id_-2-0-id">', html=True ) self.assertContains( response, '<input type="hidden" name="-2-0-capo_famiglia" ' 'id="id_-2-0-capo_famiglia">', html=True, ) self.assertContains( response, '<input id="id_-2-0-name" type="text" class="vTextField" name="-2-0-name" ' 'maxlength="100">', html=True, ) @override_settings(USE_THOUSAND_SEPARATOR=True) def test_localize_pk_shortcut(self): """ The "View on Site" link is correct for locales that use thousand separators. """ holder = Holder.objects.create(pk=123456789, dummy=42) inner = Inner.objects.create(pk=987654321, holder=holder, dummy=42, readonly="") response = self.client.get( reverse("admin:admin_inlines_holder_change", args=(holder.id,)) ) inner_shortcut = "r/%s/%s/" % ( ContentType.objects.get_for_model(inner).pk, inner.pk, ) self.assertContains(response, inner_shortcut) def test_custom_pk_shortcut(self): """ The "View on Site" link is correct for models with a custom primary key field. """ parent = ParentModelWithCustomPk.objects.create(my_own_pk="foo", name="Foo") child1 = ChildModel1.objects.create(my_own_pk="bar", name="Bar", parent=parent) child2 = ChildModel2.objects.create(my_own_pk="baz", name="Baz", parent=parent) response = self.client.get( reverse("admin:admin_inlines_parentmodelwithcustompk_change", args=("foo",)) ) child1_shortcut = "r/%s/%s/" % ( ContentType.objects.get_for_model(child1).pk, child1.pk, ) child2_shortcut = "r/%s/%s/" % ( ContentType.objects.get_for_model(child2).pk, child2.pk, ) self.assertContains(response, child1_shortcut) self.assertContains(response, child2_shortcut) def test_create_inlines_on_inherited_model(self): """ An object can be created with inlines when it inherits another class. """ data = { "name": "Martian", "sighting_set-TOTAL_FORMS": 1, "sighting_set-INITIAL_FORMS": 0, "sighting_set-MAX_NUM_FORMS": 0, "sighting_set-0-place": "Zone 51", "_save": "Save", } response = self.client.post( reverse("admin:admin_inlines_extraterrestrial_add"), data ) self.assertEqual(response.status_code, 302) self.assertEqual(Sighting.objects.filter(et__name="Martian").count(), 1) def test_custom_get_extra_form(self): bt_head = BinaryTree.objects.create(name="Tree Head") BinaryTree.objects.create(name="First Child", parent=bt_head) # The maximum number of forms should respect 'get_max_num' on the # ModelAdmin max_forms_input = ( '<input id="id_binarytree_set-MAX_NUM_FORMS" ' 'name="binarytree_set-MAX_NUM_FORMS" type="hidden" value="%d">' ) # The total number of forms will remain the same in either case total_forms_hidden = ( '<input id="id_binarytree_set-TOTAL_FORMS" ' 'name="binarytree_set-TOTAL_FORMS" type="hidden" value="2">' ) response = self.client.get(reverse("admin:admin_inlines_binarytree_add")) self.assertInHTML(max_forms_input % 3, response.rendered_content) self.assertInHTML(total_forms_hidden, response.rendered_content) response = self.client.get( reverse("admin:admin_inlines_binarytree_change", args=(bt_head.id,)) ) self.assertInHTML(max_forms_input % 2, response.rendered_content) self.assertInHTML(total_forms_hidden, response.rendered_content) def test_min_num(self): """ min_num and extra determine number of forms. """ class MinNumInline(TabularInline): model = BinaryTree min_num = 2 extra = 3 modeladmin = ModelAdmin(BinaryTree, admin_site) modeladmin.inlines = [MinNumInline] min_forms = ( '<input id="id_binarytree_set-MIN_NUM_FORMS" ' 'name="binarytree_set-MIN_NUM_FORMS" type="hidden" value="2">' ) total_forms = ( '<input id="id_binarytree_set-TOTAL_FORMS" ' 'name="binarytree_set-TOTAL_FORMS" type="hidden" value="5">' ) request = self.factory.get(reverse("admin:admin_inlines_binarytree_add")) request.user = User(username="super", is_superuser=True) response = modeladmin.changeform_view(request) self.assertInHTML(min_forms, response.rendered_content) self.assertInHTML(total_forms, response.rendered_content) def test_custom_min_num(self): bt_head = BinaryTree.objects.create(name="Tree Head") BinaryTree.objects.create(name="First Child", parent=bt_head) class MinNumInline(TabularInline): model = BinaryTree extra = 3 def get_min_num(self, request, obj=None, **kwargs): if obj: return 5 return 2 modeladmin = ModelAdmin(BinaryTree, admin_site) modeladmin.inlines = [MinNumInline] min_forms = ( '<input id="id_binarytree_set-MIN_NUM_FORMS" ' 'name="binarytree_set-MIN_NUM_FORMS" type="hidden" value="%d">' ) total_forms = ( '<input id="id_binarytree_set-TOTAL_FORMS" ' 'name="binarytree_set-TOTAL_FORMS" type="hidden" value="%d">' ) request = self.factory.get(reverse("admin:admin_inlines_binarytree_add")) request.user = User(username="super", is_superuser=True) response = modeladmin.changeform_view(request) self.assertInHTML(min_forms % 2, response.rendered_content) self.assertInHTML(total_forms % 5, response.rendered_content) request = self.factory.get( reverse("admin:admin_inlines_binarytree_change", args=(bt_head.id,)) ) request.user = User(username="super", is_superuser=True) response = modeladmin.changeform_view(request, object_id=str(bt_head.id)) self.assertInHTML(min_forms % 5, response.rendered_content) self.assertInHTML(total_forms % 8, response.rendered_content) def test_inline_nonauto_noneditable_pk(self): response = self.client.get(reverse("admin:admin_inlines_author_add")) self.assertContains( response, '<input id="id_nonautopkbook_set-0-rand_pk" ' 'name="nonautopkbook_set-0-rand_pk" type="hidden">', html=True, ) self.assertContains( response, '<input id="id_nonautopkbook_set-2-0-rand_pk" ' 'name="nonautopkbook_set-2-0-rand_pk" type="hidden">', html=True, ) def test_inline_nonauto_noneditable_inherited_pk(self): response = self.client.get(reverse("admin:admin_inlines_author_add")) self.assertContains( response, '<input id="id_nonautopkbookchild_set-0-nonautopkbook_ptr" ' 'name="nonautopkbookchild_set-0-nonautopkbook_ptr" type="hidden">', html=True, ) self.assertContains( response, '<input id="id_nonautopkbookchild_set-2-nonautopkbook_ptr" ' 'name="nonautopkbookchild_set-2-nonautopkbook_ptr" type="hidden">', html=True, ) def test_inline_editable_pk(self): response = self.client.get(reverse("admin:admin_inlines_author_add")) self.assertContains( response, '<input class="vIntegerField" id="id_editablepkbook_set-0-manual_pk" ' 'name="editablepkbook_set-0-manual_pk" type="number">', html=True, count=1, ) self.assertContains( response, '<input class="vIntegerField" id="id_editablepkbook_set-2-0-manual_pk" ' 'name="editablepkbook_set-2-0-manual_pk" type="number">', html=True, count=1, ) def test_stacked_inline_edit_form_contains_has_original_class(self): holder = Holder.objects.create(dummy=1) holder.inner_set.create(dummy=1) response = self.client.get( reverse("admin:admin_inlines_holder_change", args=(holder.pk,)) ) self.assertContains( response, '<div class="inline-related has_original" id="inner_set-0">', count=1, ) self.assertContains( response, '<div class="inline-related" id="inner_set-1">', count=1 ) def test_inlines_show_change_link_registered(self): "Inlines `show_change_link` for registered models when enabled." holder = Holder4.objects.create(dummy=1) item1 = Inner4Stacked.objects.create(dummy=1, holder=holder) item2 = Inner4Tabular.objects.create(dummy=1, holder=holder) items = ( ("inner4stacked", item1.pk), ("inner4tabular", item2.pk), ) response = self.client.get( reverse("admin:admin_inlines_holder4_change", args=(holder.pk,)) ) self.assertTrue( response.context["inline_admin_formset"].opts.has_registered_model ) for model, pk in items: url = reverse("admin:admin_inlines_%s_change" % model, args=(pk,)) self.assertContains( response, '<a href="%s" %s' % (url, INLINE_CHANGELINK_HTML) ) def test_inlines_show_change_link_unregistered(self): "Inlines `show_change_link` disabled for unregistered models." parent = ParentModelWithCustomPk.objects.create(my_own_pk="foo", name="Foo") ChildModel1.objects.create(my_own_pk="bar", name="Bar", parent=parent) ChildModel2.objects.create(my_own_pk="baz", name="Baz", parent=parent) response = self.client.get( reverse("admin:admin_inlines_parentmodelwithcustompk_change", args=("foo",)) ) self.assertFalse( response.context["inline_admin_formset"].opts.has_registered_model ) self.assertNotContains(response, INLINE_CHANGELINK_HTML) def test_tabular_inline_show_change_link_false_registered(self): "Inlines `show_change_link` disabled by default." poll = Poll.objects.create(name="New poll") Question.objects.create(poll=poll) response = self.client.get( reverse("admin:admin_inlines_poll_change", args=(poll.pk,)) ) self.assertTrue( response.context["inline_admin_formset"].opts.has_registered_model ) self.assertNotContains(response, INLINE_CHANGELINK_HTML) def test_noneditable_inline_has_field_inputs(self): """Inlines without change permission shows field inputs on add form.""" response = self.client.get( reverse("admin:admin_inlines_novelreadonlychapter_add") ) self.assertContains( response, '<input type="text" name="chapter_set-0-name" ' 'class="vTextField" maxlength="40" id="id_chapter_set-0-name">', html=True, ) def test_inlines_plural_heading_foreign_key(self): response = self.client.get(reverse("admin:admin_inlines_holder4_add")) self.assertContains(response, "<h2>Inner4 stackeds</h2>", html=True) self.assertContains(response, "<h2>Inner4 tabulars</h2>", html=True) def test_inlines_singular_heading_one_to_one(self): response = self.client.get(reverse("admin:admin_inlines_person_add")) self.assertContains(response, "<h2>Author</h2>", html=True) # Tabular. self.assertContains(response, "<h2>Fashionista</h2>", html=True) # Stacked. def test_inlines_based_on_model_state(self): parent = ShowInlineParent.objects.create(show_inlines=False) data = { "show_inlines": "on", "_save": "Save", } change_url = reverse( "admin:admin_inlines_showinlineparent_change", args=(parent.id,), ) response = self.client.post(change_url, data) self.assertEqual(response.status_code, 302) parent.refresh_from_db() self.assertIs(parent.show_inlines, True) @override_settings(ROOT_URLCONF="admin_inlines.urls") class TestInlineMedia(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_inline_media_only_base(self): holder = Holder(dummy=13) holder.save() Inner(dummy=42, holder=holder).save() change_url = reverse("admin:admin_inlines_holder_change", args=(holder.id,)) response = self.client.get(change_url) self.assertContains(response, "my_awesome_admin_scripts.js") def test_inline_media_only_inline(self): holder = Holder3(dummy=13) holder.save() Inner3(dummy=42, holder=holder).save() change_url = reverse("admin:admin_inlines_holder3_change", args=(holder.id,)) response = self.client.get(change_url) self.assertEqual( response.context["inline_admin_formsets"][0].media._js, [ "admin/js/vendor/jquery/jquery.min.js", "my_awesome_inline_scripts.js", "custom_number.js", "admin/js/jquery.init.js", "admin/js/inlines.js", ], ) self.assertContains(response, "my_awesome_inline_scripts.js") def test_all_inline_media(self): holder = Holder2(dummy=13) holder.save() Inner2(dummy=42, holder=holder).save() change_url = reverse("admin:admin_inlines_holder2_change", args=(holder.id,)) response = self.client.get(change_url) self.assertContains(response, "my_awesome_admin_scripts.js") self.assertContains(response, "my_awesome_inline_scripts.js") @override_settings(ROOT_URLCONF="admin_inlines.urls") class TestInlineAdminForm(TestCase): def test_immutable_content_type(self): """Regression for #9362 The problem depends only on InlineAdminForm and its "original" argument, so we can safely set the other arguments to None/{}. We just need to check that the content_type argument of Child isn't altered by the internals of the inline form.""" sally = Teacher.objects.create(name="Sally") john = Parent.objects.create(name="John") joe = Child.objects.create(name="Joe", teacher=sally, parent=john) iaf = InlineAdminForm(None, None, {}, {}, joe) parent_ct = ContentType.objects.get_for_model(Parent) self.assertEqual(iaf.original.content_type, parent_ct) @override_settings(ROOT_URLCONF="admin_inlines.urls") class TestInlineProtectedOnDelete(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_deleting_inline_with_protected_delete_does_not_validate(self): lotr = Novel.objects.create(name="Lord of the rings") chapter = Chapter.objects.create(novel=lotr, name="Many Meetings") foot_note = FootNote.objects.create(chapter=chapter, note="yadda yadda") change_url = reverse("admin:admin_inlines_novel_change", args=(lotr.id,)) response = self.client.get(change_url) data = { "name": lotr.name, "chapter_set-TOTAL_FORMS": 1, "chapter_set-INITIAL_FORMS": 1, "chapter_set-MAX_NUM_FORMS": 1000, "_save": "Save", "chapter_set-0-id": chapter.id, "chapter_set-0-name": chapter.name, "chapter_set-0-novel": lotr.id, "chapter_set-0-DELETE": "on", } response = self.client.post(change_url, data) self.assertContains( response, "Deleting chapter %s would require deleting " "the following protected related objects: foot note %s" % (chapter, foot_note), ) @override_settings(ROOT_URLCONF="admin_inlines.urls") class TestInlinePermissions(TestCase): """ Make sure the admin respects permissions for objects that are edited inline. Refs #8060. """ @classmethod def setUpTestData(cls): cls.user = User(username="admin", is_staff=True, is_active=True) cls.user.set_password("secret") cls.user.save() cls.author_ct = ContentType.objects.get_for_model(Author) cls.holder_ct = ContentType.objects.get_for_model(Holder2) cls.book_ct = ContentType.objects.get_for_model(Book) cls.inner_ct = ContentType.objects.get_for_model(Inner2) # User always has permissions to add and change Authors, and Holders, # the main (parent) models of the inlines. Permissions on the inlines # vary per test. permission = Permission.objects.get( codename="add_author", content_type=cls.author_ct ) cls.user.user_permissions.add(permission) permission = Permission.objects.get( codename="change_author", content_type=cls.author_ct ) cls.user.user_permissions.add(permission) permission = Permission.objects.get( codename="add_holder2", content_type=cls.holder_ct ) cls.user.user_permissions.add(permission) permission = Permission.objects.get( codename="change_holder2", content_type=cls.holder_ct ) cls.user.user_permissions.add(permission) author = Author.objects.create(pk=1, name="The Author") cls.book = author.books.create(name="The inline Book") cls.author_change_url = reverse( "admin:admin_inlines_author_change", args=(author.id,) ) # Get the ID of the automatically created intermediate model for the # Author-Book m2m. author_book_auto_m2m_intermediate = Author.books.through.objects.get( author=author, book=cls.book ) cls.author_book_auto_m2m_intermediate_id = author_book_auto_m2m_intermediate.pk cls.holder = Holder2.objects.create(dummy=13) cls.inner2 = Inner2.objects.create(dummy=42, holder=cls.holder) def setUp(self): self.holder_change_url = reverse( "admin:admin_inlines_holder2_change", args=(self.holder.id,) ) self.client.force_login(self.user) def test_inline_add_m2m_noperm(self): response = self.client.get(reverse("admin:admin_inlines_author_add")) # No change permission on books, so no inline self.assertNotContains(response, "<h2>Author-book relationships</h2>") self.assertNotContains(response, "Add another Author-Book Relationship") self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"') def test_inline_add_fk_noperm(self): response = self.client.get(reverse("admin:admin_inlines_holder2_add")) # No permissions on Inner2s, so no inline self.assertNotContains(response, "<h2>Inner2s</h2>") self.assertNotContains(response, "Add another Inner2") self.assertNotContains(response, 'id="id_inner2_set-TOTAL_FORMS"') def test_inline_change_m2m_noperm(self): response = self.client.get(self.author_change_url) # No change permission on books, so no inline self.assertNotContains(response, "<h2>Author-book relationships</h2>") self.assertNotContains(response, "Add another Author-Book Relationship") self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"') def test_inline_change_fk_noperm(self): response = self.client.get(self.holder_change_url) # No permissions on Inner2s, so no inline self.assertNotContains(response, "<h2>Inner2s</h2>") self.assertNotContains(response, "Add another Inner2") self.assertNotContains(response, 'id="id_inner2_set-TOTAL_FORMS"') def test_inline_add_m2m_view_only_perm(self): permission = Permission.objects.get( codename="view_book", content_type=self.book_ct ) self.user.user_permissions.add(permission) response = self.client.get(reverse("admin:admin_inlines_author_add")) # View-only inlines. (It could be nicer to hide the empty, non-editable # inlines on the add page.) self.assertIs( response.context["inline_admin_formset"].has_view_permission, True ) self.assertIs( response.context["inline_admin_formset"].has_add_permission, False ) self.assertIs( response.context["inline_admin_formset"].has_change_permission, False ) self.assertIs( response.context["inline_admin_formset"].has_delete_permission, False ) self.assertContains(response, "<h2>Author-book relationships</h2>") self.assertContains( response, '<input type="hidden" name="Author_books-TOTAL_FORMS" value="0" ' 'id="id_Author_books-TOTAL_FORMS">', html=True, ) self.assertNotContains(response, "Add another Author-Book Relationship") def test_inline_add_m2m_add_perm(self): permission = Permission.objects.get( codename="add_book", content_type=self.book_ct ) self.user.user_permissions.add(permission) response = self.client.get(reverse("admin:admin_inlines_author_add")) # No change permission on Books, so no inline self.assertNotContains(response, "<h2>Author-book relationships</h2>") self.assertNotContains(response, "Add another Author-Book Relationship") self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"') def test_inline_add_fk_add_perm(self): permission = Permission.objects.get( codename="add_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) response = self.client.get(reverse("admin:admin_inlines_holder2_add")) # Add permission on inner2s, so we get the inline self.assertContains(response, "<h2>Inner2s</h2>") self.assertContains(response, "Add another Inner2") self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' 'value="3" name="inner2_set-TOTAL_FORMS">', html=True, ) def test_inline_change_m2m_add_perm(self): permission = Permission.objects.get( codename="add_book", content_type=self.book_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.author_change_url) # No change permission on books, so no inline self.assertNotContains(response, "<h2>Author-book relationships</h2>") self.assertNotContains(response, "Add another Author-Book Relationship") self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"') self.assertNotContains(response, 'id="id_Author_books-0-DELETE"') def test_inline_change_m2m_view_only_perm(self): permission = Permission.objects.get( codename="view_book", content_type=self.book_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.author_change_url) # View-only inlines. self.assertIs( response.context["inline_admin_formset"].has_view_permission, True ) self.assertIs( response.context["inline_admin_formset"].has_add_permission, False ) self.assertIs( response.context["inline_admin_formset"].has_change_permission, False ) self.assertIs( response.context["inline_admin_formset"].has_delete_permission, False ) self.assertContains(response, "<h2>Author-book relationships</h2>") self.assertContains( response, '<input type="hidden" name="Author_books-TOTAL_FORMS" value="1" ' 'id="id_Author_books-TOTAL_FORMS">', html=True, ) # The field in the inline is read-only. self.assertContains(response, "<p>%s</p>" % self.book) self.assertNotContains( response, '<input type="checkbox" name="Author_books-0-DELETE" ' 'id="id_Author_books-0-DELETE">', html=True, ) def test_inline_change_m2m_change_perm(self): permission = Permission.objects.get( codename="change_book", content_type=self.book_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.author_change_url) # We have change perm on books, so we can add/change/delete inlines self.assertIs( response.context["inline_admin_formset"].has_view_permission, True ) self.assertIs(response.context["inline_admin_formset"].has_add_permission, True) self.assertIs( response.context["inline_admin_formset"].has_change_permission, True ) self.assertIs( response.context["inline_admin_formset"].has_delete_permission, True ) self.assertContains(response, "<h2>Author-book relationships</h2>") self.assertContains(response, "Add another Author-book relationship") self.assertContains( response, '<input type="hidden" id="id_Author_books-TOTAL_FORMS" ' 'value="4" name="Author_books-TOTAL_FORMS">', html=True, ) self.assertContains( response, '<input type="hidden" id="id_Author_books-0-id" value="%i" ' 'name="Author_books-0-id">' % self.author_book_auto_m2m_intermediate_id, html=True, ) self.assertContains(response, 'id="id_Author_books-0-DELETE"') def test_inline_change_fk_add_perm(self): permission = Permission.objects.get( codename="add_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.holder_change_url) # Add permission on inner2s, so we can add but not modify existing self.assertContains(response, "<h2>Inner2s</h2>") self.assertContains(response, "Add another Inner2") # 3 extra forms only, not the existing instance form self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="3" ' 'name="inner2_set-TOTAL_FORMS">', html=True, ) self.assertNotContains( response, '<input type="hidden" id="id_inner2_set-0-id" value="%i" ' 'name="inner2_set-0-id">' % self.inner2.id, html=True, ) def test_inline_change_fk_change_perm(self): permission = Permission.objects.get( codename="change_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.holder_change_url) # Change permission on inner2s, so we can change existing but not add new self.assertContains(response, "<h2>Inner2s</h2>", count=2) # Just the one form for existing instances self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" ' 'name="inner2_set-TOTAL_FORMS">', html=True, ) self.assertContains( response, '<input type="hidden" id="id_inner2_set-0-id" value="%i" ' 'name="inner2_set-0-id">' % self.inner2.id, html=True, ) # max-num 0 means we can't add new ones self.assertContains( response, '<input type="hidden" id="id_inner2_set-MAX_NUM_FORMS" value="0" ' 'name="inner2_set-MAX_NUM_FORMS">', html=True, ) # TabularInline self.assertContains( response, '<th class="column-dummy required">Dummy</th>', html=True ) self.assertContains( response, '<input type="number" name="inner2_set-2-0-dummy" value="%s" ' 'class="vIntegerField" id="id_inner2_set-2-0-dummy">' % self.inner2.dummy, html=True, ) def test_inline_change_fk_add_change_perm(self): permission = Permission.objects.get( codename="add_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) permission = Permission.objects.get( codename="change_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.holder_change_url) # Add/change perm, so we can add new and change existing self.assertContains(response, "<h2>Inner2s</h2>") # One form for existing instance and three extra for new self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" ' 'name="inner2_set-TOTAL_FORMS">', html=True, ) self.assertContains( response, '<input type="hidden" id="id_inner2_set-0-id" value="%i" ' 'name="inner2_set-0-id">' % self.inner2.id, html=True, ) def test_inline_change_fk_change_del_perm(self): permission = Permission.objects.get( codename="change_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) permission = Permission.objects.get( codename="delete_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.holder_change_url) # Change/delete perm on inner2s, so we can change/delete existing self.assertContains(response, "<h2>Inner2s</h2>") # One form for existing instance only, no new self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" ' 'name="inner2_set-TOTAL_FORMS">', html=True, ) self.assertContains( response, '<input type="hidden" id="id_inner2_set-0-id" value="%i" ' 'name="inner2_set-0-id">' % self.inner2.id, html=True, ) self.assertContains(response, 'id="id_inner2_set-0-DELETE"') def test_inline_change_fk_all_perms(self): permission = Permission.objects.get( codename="add_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) permission = Permission.objects.get( codename="change_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) permission = Permission.objects.get( codename="delete_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.holder_change_url) # All perms on inner2s, so we can add/change/delete self.assertContains(response, "<h2>Inner2s</h2>", count=2) # One form for existing instance only, three for new self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" ' 'name="inner2_set-TOTAL_FORMS">', html=True, ) self.assertContains( response, '<input type="hidden" id="id_inner2_set-0-id" value="%i" ' 'name="inner2_set-0-id">' % self.inner2.id, html=True, ) self.assertContains(response, 'id="id_inner2_set-0-DELETE"') # TabularInline self.assertContains( response, '<th class="column-dummy required">Dummy</th>', html=True ) self.assertContains( response, '<input type="number" name="inner2_set-2-0-dummy" value="%s" ' 'class="vIntegerField" id="id_inner2_set-2-0-dummy">' % self.inner2.dummy, html=True, ) @override_settings(ROOT_URLCONF="admin_inlines.urls") class TestReadOnlyChangeViewInlinePermissions(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user( "testing", password="password", is_staff=True ) cls.user.user_permissions.add( Permission.objects.get( codename="view_poll", content_type=ContentType.objects.get_for_model(Poll), ) ) cls.user.user_permissions.add( *Permission.objects.filter( codename__endswith="question", content_type=ContentType.objects.get_for_model(Question), ).values_list("pk", flat=True) ) cls.poll = Poll.objects.create(name="Survey") cls.add_url = reverse("admin:admin_inlines_poll_add") cls.change_url = reverse("admin:admin_inlines_poll_change", args=(cls.poll.id,)) def setUp(self): self.client.force_login(self.user) def test_add_url_not_allowed(self): response = self.client.get(self.add_url) self.assertEqual(response.status_code, 403) response = self.client.post(self.add_url, {}) self.assertEqual(response.status_code, 403) def test_post_to_change_url_not_allowed(self): response = self.client.post(self.change_url, {}) self.assertEqual(response.status_code, 403) def test_get_to_change_url_is_allowed(self): response = self.client.get(self.change_url) self.assertEqual(response.status_code, 200) def test_main_model_is_rendered_as_read_only(self): response = self.client.get(self.change_url) self.assertContains( response, '<div class="readonly">%s</div>' % self.poll.name, html=True ) input = ( '<input type="text" name="name" value="%s" class="vTextField" ' 'maxlength="40" required id="id_name">' ) self.assertNotContains(response, input % self.poll.name, html=True) def test_inlines_are_rendered_as_read_only(self): question = Question.objects.create( text="How will this be rendered?", poll=self.poll ) response = self.client.get(self.change_url) self.assertContains( response, '<td class="field-text"><p>%s</p></td>' % question.text, html=True ) self.assertNotContains(response, 'id="id_question_set-0-text"') self.assertNotContains(response, 'id="id_related_objs-0-DELETE"') def test_submit_line_shows_only_close_button(self): response = self.client.get(self.change_url) self.assertContains( response, '<a href="/admin/admin_inlines/poll/" class="closelink">Close</a>', html=True, ) delete_link = ( '<a href="/admin/admin_inlines/poll/%s/delete/" class="deletelink">Delete' "</a>" ) self.assertNotContains(response, delete_link % self.poll.id, html=True) self.assertNotContains( response, '<input type="submit" value="Save and add another" name="_addanother">', ) self.assertNotContains( response, '<input type="submit" value="Save and continue editing" name="_continue">', ) def test_inline_delete_buttons_are_not_shown(self): Question.objects.create(text="How will this be rendered?", poll=self.poll) response = self.client.get(self.change_url) self.assertNotContains( response, '<input type="checkbox" name="question_set-0-DELETE" ' 'id="id_question_set-0-DELETE">', html=True, ) def test_extra_inlines_are_not_shown(self): response = self.client.get(self.change_url) self.assertNotContains(response, 'id="id_question_set-0-text"') @override_settings(ROOT_URLCONF="admin_inlines.urls") class TestVerboseNameInlineForms(TestDataMixin, TestCase): factory = RequestFactory() def test_verbose_name_inline(self): class NonVerboseProfileInline(TabularInline): model = Profile verbose_name = "Non-verbose childs" class VerboseNameProfileInline(TabularInline): model = VerboseNameProfile verbose_name = "Childs with verbose name" class VerboseNamePluralProfileInline(TabularInline): model = VerboseNamePluralProfile verbose_name = "Childs with verbose name plural" class BothVerboseNameProfileInline(TabularInline): model = BothVerboseNameProfile verbose_name = "Childs with both verbose names" modeladmin = ModelAdmin(ProfileCollection, admin_site) modeladmin.inlines = [ NonVerboseProfileInline, VerboseNameProfileInline, VerboseNamePluralProfileInline, BothVerboseNameProfileInline, ] obj = ProfileCollection.objects.create() url = reverse("admin:admin_inlines_profilecollection_change", args=(obj.pk,)) request = self.factory.get(url) request.user = self.superuser response = modeladmin.changeform_view(request) self.assertNotContains(response, "Add another Profile") # Non-verbose model. self.assertContains(response, "<h2>Non-verbose childss</h2>") self.assertContains(response, "Add another Non-verbose child") self.assertNotContains(response, "<h2>Profiles</h2>") # Model with verbose name. self.assertContains(response, "<h2>Childs with verbose names</h2>") self.assertContains(response, "Add another Childs with verbose name") self.assertNotContains(response, "<h2>Model with verbose name onlys</h2>") self.assertNotContains(response, "Add another Model with verbose name only") # Model with verbose name plural. self.assertContains(response, "<h2>Childs with verbose name plurals</h2>") self.assertContains(response, "Add another Childs with verbose name plural") self.assertNotContains(response, "<h2>Model with verbose name plural only</h2>") # Model with both verbose names. self.assertContains(response, "<h2>Childs with both verbose namess</h2>") self.assertContains(response, "Add another Childs with both verbose names") self.assertNotContains(response, "<h2>Model with both - plural name</h2>") self.assertNotContains(response, "Add another Model with both - name") def test_verbose_name_plural_inline(self): class NonVerboseProfileInline(TabularInline): model = Profile verbose_name_plural = "Non-verbose childs" class VerboseNameProfileInline(TabularInline): model = VerboseNameProfile verbose_name_plural = "Childs with verbose name" class VerboseNamePluralProfileInline(TabularInline): model = VerboseNamePluralProfile verbose_name_plural = "Childs with verbose name plural" class BothVerboseNameProfileInline(TabularInline): model = BothVerboseNameProfile verbose_name_plural = "Childs with both verbose names" modeladmin = ModelAdmin(ProfileCollection, admin_site) modeladmin.inlines = [ NonVerboseProfileInline, VerboseNameProfileInline, VerboseNamePluralProfileInline, BothVerboseNameProfileInline, ] obj = ProfileCollection.objects.create() url = reverse("admin:admin_inlines_profilecollection_change", args=(obj.pk,)) request = self.factory.get(url) request.user = self.superuser response = modeladmin.changeform_view(request) # Non-verbose model. self.assertContains(response, "<h2>Non-verbose childs</h2>") self.assertContains(response, "Add another Profile") self.assertNotContains(response, "<h2>Profiles</h2>") # Model with verbose name. self.assertContains(response, "<h2>Childs with verbose name</h2>") self.assertContains(response, "Add another Model with verbose name only") self.assertNotContains(response, "<h2>Model with verbose name onlys</h2>") # Model with verbose name plural. self.assertContains(response, "<h2>Childs with verbose name plural</h2>") self.assertContains(response, "Add another Profile") self.assertNotContains(response, "<h2>Model with verbose name plural only</h2>") # Model with both verbose names. self.assertContains(response, "<h2>Childs with both verbose names</h2>") self.assertContains(response, "Add another Model with both - name") self.assertNotContains(response, "<h2>Model with both - plural name</h2>") def test_both_verbose_names_inline(self): class NonVerboseProfileInline(TabularInline): model = Profile verbose_name = "Non-verbose childs - name" verbose_name_plural = "Non-verbose childs - plural name" class VerboseNameProfileInline(TabularInline): model = VerboseNameProfile verbose_name = "Childs with verbose name - name" verbose_name_plural = "Childs with verbose name - plural name" class VerboseNamePluralProfileInline(TabularInline): model = VerboseNamePluralProfile verbose_name = "Childs with verbose name plural - name" verbose_name_plural = "Childs with verbose name plural - plural name" class BothVerboseNameProfileInline(TabularInline): model = BothVerboseNameProfile verbose_name = "Childs with both - name" verbose_name_plural = "Childs with both - plural name" modeladmin = ModelAdmin(ProfileCollection, admin_site) modeladmin.inlines = [ NonVerboseProfileInline, VerboseNameProfileInline, VerboseNamePluralProfileInline, BothVerboseNameProfileInline, ] obj = ProfileCollection.objects.create() url = reverse("admin:admin_inlines_profilecollection_change", args=(obj.pk,)) request = self.factory.get(url) request.user = self.superuser response = modeladmin.changeform_view(request) self.assertNotContains(response, "Add another Profile") # Non-verbose model. self.assertContains(response, "<h2>Non-verbose childs - plural name</h2>") self.assertContains(response, "Add another Non-verbose childs - name") self.assertNotContains(response, "<h2>Profiles</h2>") # Model with verbose name. self.assertContains(response, "<h2>Childs with verbose name - plural name</h2>") self.assertContains(response, "Add another Childs with verbose name - name") self.assertNotContains(response, "<h2>Model with verbose name onlys</h2>") # Model with verbose name plural. self.assertContains( response, "<h2>Childs with verbose name plural - plural name</h2>", ) self.assertContains( response, "Add another Childs with verbose name plural - name", ) self.assertNotContains(response, "<h2>Model with verbose name plural only</h2>") # Model with both verbose names. self.assertContains(response, "<h2>Childs with both - plural name</h2>") self.assertContains(response, "Add another Childs with both - name") self.assertNotContains(response, "<h2>Model with both - plural name</h2>") self.assertNotContains(response, "Add another Model with both - name") @override_settings(ROOT_URLCONF="admin_inlines.urls") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_inlines"] + AdminSeleniumTestCase.available_apps def setUp(self): User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def test_add_stackeds(self): """ The "Add another XXX" link correctly adds items to the stacked formset. """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_holder4_add") ) inline_id = "#inner4stacked_set-group" rows_selector = "%s .dynamic-inner4stacked_set" % inline_id self.assertCountSeleniumElements(rows_selector, 3) add_button = self.selenium.find_element( By.LINK_TEXT, "Add another Inner4 stacked" ) add_button.click() self.assertCountSeleniumElements(rows_selector, 4) def test_delete_stackeds(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_holder4_add") ) inline_id = "#inner4stacked_set-group" rows_selector = "%s .dynamic-inner4stacked_set" % inline_id self.assertCountSeleniumElements(rows_selector, 3) add_button = self.selenium.find_element( By.LINK_TEXT, "Add another Inner4 stacked" ) add_button.click() add_button.click() self.assertCountSeleniumElements(rows_selector, 5) for delete_link in self.selenium.find_elements( By.CSS_SELECTOR, "%s .inline-deletelink" % inline_id ): delete_link.click() with self.disable_implicit_wait(): self.assertCountSeleniumElements(rows_selector, 0) def test_delete_invalid_stacked_inlines(self): from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_holder4_add") ) inline_id = "#inner4stacked_set-group" rows_selector = "%s .dynamic-inner4stacked_set" % inline_id self.assertCountSeleniumElements(rows_selector, 3) add_button = self.selenium.find_element( By.LINK_TEXT, "Add another Inner4 stacked", ) add_button.click() add_button.click() self.assertCountSeleniumElements("#id_inner4stacked_set-4-dummy", 1) # Enter some data and click 'Save'. self.selenium.find_element(By.NAME, "dummy").send_keys("1") self.selenium.find_element(By.NAME, "inner4stacked_set-0-dummy").send_keys( "100" ) self.selenium.find_element(By.NAME, "inner4stacked_set-1-dummy").send_keys( "101" ) self.selenium.find_element(By.NAME, "inner4stacked_set-2-dummy").send_keys( "222" ) self.selenium.find_element(By.NAME, "inner4stacked_set-3-dummy").send_keys( "103" ) self.selenium.find_element(By.NAME, "inner4stacked_set-4-dummy").send_keys( "222" ) with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() # Sanity check. self.assertCountSeleniumElements(rows_selector, 5) errorlist = self.selenium.find_element( By.CSS_SELECTOR, "%s .dynamic-inner4stacked_set .errorlist li" % inline_id, ) self.assertEqual("Please correct the duplicate values below.", errorlist.text) delete_link = self.selenium.find_element( By.CSS_SELECTOR, "#inner4stacked_set-4 .inline-deletelink" ) delete_link.click() self.assertCountSeleniumElements(rows_selector, 4) with self.disable_implicit_wait(), self.assertRaises(NoSuchElementException): self.selenium.find_element( By.CSS_SELECTOR, "%s .dynamic-inner4stacked_set .errorlist li" % inline_id, ) with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() # The objects have been created in the database. self.assertEqual(Inner4Stacked.objects.count(), 4) def test_delete_invalid_tabular_inlines(self): from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_holder4_add") ) inline_id = "#inner4tabular_set-group" rows_selector = "%s .dynamic-inner4tabular_set" % inline_id self.assertCountSeleniumElements(rows_selector, 3) add_button = self.selenium.find_element( By.LINK_TEXT, "Add another Inner4 tabular" ) add_button.click() add_button.click() self.assertCountSeleniumElements("#id_inner4tabular_set-4-dummy", 1) # Enter some data and click 'Save'. self.selenium.find_element(By.NAME, "dummy").send_keys("1") self.selenium.find_element(By.NAME, "inner4tabular_set-0-dummy").send_keys( "100" ) self.selenium.find_element(By.NAME, "inner4tabular_set-1-dummy").send_keys( "101" ) self.selenium.find_element(By.NAME, "inner4tabular_set-2-dummy").send_keys( "222" ) self.selenium.find_element(By.NAME, "inner4tabular_set-3-dummy").send_keys( "103" ) self.selenium.find_element(By.NAME, "inner4tabular_set-4-dummy").send_keys( "222" ) with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() # Sanity Check. self.assertCountSeleniumElements(rows_selector, 5) # Non-field errorlist is in its own <tr> just before # tr#inner4tabular_set-3: errorlist = self.selenium.find_element( By.CSS_SELECTOR, "%s #inner4tabular_set-3 + .row-form-errors .errorlist li" % inline_id, ) self.assertEqual("Please correct the duplicate values below.", errorlist.text) delete_link = self.selenium.find_element( By.CSS_SELECTOR, "#inner4tabular_set-4 .inline-deletelink" ) delete_link.click() self.assertCountSeleniumElements(rows_selector, 4) with self.disable_implicit_wait(), self.assertRaises(NoSuchElementException): self.selenium.find_element( By.CSS_SELECTOR, "%s .dynamic-inner4tabular_set .errorlist li" % inline_id, ) with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() # The objects have been created in the database. self.assertEqual(Inner4Tabular.objects.count(), 4) def test_add_inlines(self): """ The "Add another XXX" link correctly adds items to the inline form. """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_profilecollection_add") ) # There's only one inline to start with and it has the correct ID. self.assertCountSeleniumElements(".dynamic-profile_set", 1) self.assertEqual( self.selenium.find_elements(By.CSS_SELECTOR, ".dynamic-profile_set")[ 0 ].get_attribute("id"), "profile_set-0", ) self.assertCountSeleniumElements( ".dynamic-profile_set#profile_set-0 input[name=profile_set-0-first_name]", 1 ) self.assertCountSeleniumElements( ".dynamic-profile_set#profile_set-0 input[name=profile_set-0-last_name]", 1 ) # Add an inline self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click() # The inline has been added, it has the right id, and it contains the # correct fields. self.assertCountSeleniumElements(".dynamic-profile_set", 2) self.assertEqual( self.selenium.find_elements(By.CSS_SELECTOR, ".dynamic-profile_set")[ 1 ].get_attribute("id"), "profile_set-1", ) self.assertCountSeleniumElements( ".dynamic-profile_set#profile_set-1 input[name=profile_set-1-first_name]", 1 ) self.assertCountSeleniumElements( ".dynamic-profile_set#profile_set-1 input[name=profile_set-1-last_name]", 1 ) # Let's add another one to be sure self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click() self.assertCountSeleniumElements(".dynamic-profile_set", 3) self.assertEqual( self.selenium.find_elements(By.CSS_SELECTOR, ".dynamic-profile_set")[ 2 ].get_attribute("id"), "profile_set-2", ) self.assertCountSeleniumElements( ".dynamic-profile_set#profile_set-2 input[name=profile_set-2-first_name]", 1 ) self.assertCountSeleniumElements( ".dynamic-profile_set#profile_set-2 input[name=profile_set-2-last_name]", 1 ) # Enter some data and click 'Save' self.selenium.find_element(By.NAME, "profile_set-0-first_name").send_keys( "0 first name 1" ) self.selenium.find_element(By.NAME, "profile_set-0-last_name").send_keys( "0 last name 2" ) self.selenium.find_element(By.NAME, "profile_set-1-first_name").send_keys( "1 first name 1" ) self.selenium.find_element(By.NAME, "profile_set-1-last_name").send_keys( "1 last name 2" ) self.selenium.find_element(By.NAME, "profile_set-2-first_name").send_keys( "2 first name 1" ) self.selenium.find_element(By.NAME, "profile_set-2-last_name").send_keys( "2 last name 2" ) with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() # The objects have been created in the database self.assertEqual(ProfileCollection.objects.count(), 1) self.assertEqual(Profile.objects.count(), 3) def test_add_inline_link_absent_for_view_only_parent_model(self): from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By user = User.objects.create_user("testing", password="password", is_staff=True) user.user_permissions.add( Permission.objects.get( codename="view_poll", content_type=ContentType.objects.get_for_model(Poll), ) ) user.user_permissions.add( *Permission.objects.filter( codename__endswith="question", content_type=ContentType.objects.get_for_model(Question), ).values_list("pk", flat=True) ) self.admin_login(username="testing", password="password") poll = Poll.objects.create(name="Survey") change_url = reverse("admin:admin_inlines_poll_change", args=(poll.id,)) self.selenium.get(self.live_server_url + change_url) with self.disable_implicit_wait(): with self.assertRaises(NoSuchElementException): self.selenium.find_element(By.LINK_TEXT, "Add another Question") def test_delete_inlines(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_profilecollection_add") ) # Add a few inlines self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click() self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click() self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click() self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click() self.assertCountSeleniumElements( "#profile_set-group table tr.dynamic-profile_set", 5 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-0", 1 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-1", 1 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-2", 1 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-3", 1 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-4", 1 ) # Click on a few delete buttons self.selenium.find_element( By.CSS_SELECTOR, "form#profilecollection_form tr.dynamic-profile_set#profile_set-1 " "td.delete a", ).click() self.selenium.find_element( By.CSS_SELECTOR, "form#profilecollection_form tr.dynamic-profile_set#profile_set-2 " "td.delete a", ).click() # The rows are gone and the IDs have been re-sequenced self.assertCountSeleniumElements( "#profile_set-group table tr.dynamic-profile_set", 3 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-0", 1 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-1", 1 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-2", 1 ) def test_collapsed_inlines(self): from selenium.webdriver.common.by import By # Collapsed inlines have SHOW/HIDE links. self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_author_add") ) # One field is in a stacked inline, other in a tabular one. test_fields = [ "#id_nonautopkbook_set-0-title", "#id_nonautopkbook_set-2-0-title", ] show_links = self.selenium.find_elements(By.LINK_TEXT, "SHOW") self.assertEqual(len(show_links), 3) for show_index, field_name in enumerate(test_fields, 0): self.wait_until_invisible(field_name) show_links[show_index].click() self.wait_until_visible(field_name) hide_links = self.selenium.find_elements(By.LINK_TEXT, "HIDE") self.assertEqual(len(hide_links), 2) for hide_index, field_name in enumerate(test_fields, 0): self.wait_until_visible(field_name) hide_links[hide_index].click() self.wait_until_invisible(field_name) def test_added_stacked_inline_with_collapsed_fields(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_teacher_add") ) self.selenium.find_element(By.LINK_TEXT, "Add another Child").click() test_fields = ["#id_child_set-0-name", "#id_child_set-1-name"] show_links = self.selenium.find_elements(By.LINK_TEXT, "SHOW") self.assertEqual(len(show_links), 2) for show_index, field_name in enumerate(test_fields, 0): self.wait_until_invisible(field_name) show_links[show_index].click() self.wait_until_visible(field_name) hide_links = self.selenium.find_elements(By.LINK_TEXT, "HIDE") self.assertEqual(len(hide_links), 2) for hide_index, field_name in enumerate(test_fields, 0): self.wait_until_visible(field_name) hide_links[hide_index].click() self.wait_until_invisible(field_name) def assertBorder(self, element, border): width, style, color = border.split(" ") border_properties = [ "border-bottom-%s", "border-left-%s", "border-right-%s", "border-top-%s", ] for prop in border_properties: self.assertEqual(element.value_of_css_property(prop % "width"), width) for prop in border_properties: self.assertEqual(element.value_of_css_property(prop % "style"), style) # Convert hex color to rgb. self.assertRegex(color, "#[0-9a-f]{6}") r, g, b = int(color[1:3], 16), int(color[3:5], 16), int(color[5:], 16) # The value may be expressed as either rgb() or rgba() depending on the # browser. colors = [ "rgb(%d, %d, %d)" % (r, g, b), "rgba(%d, %d, %d, 1)" % (r, g, b), ] for prop in border_properties: self.assertIn(element.value_of_css_property(prop % "color"), colors) def test_inline_formset_error_input_border(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_holder5_add") ) self.wait_until_visible("#id_dummy") self.selenium.find_element(By.ID, "id_dummy").send_keys(1) fields = ["id_inner5stacked_set-0-dummy", "id_inner5tabular_set-0-dummy"] show_links = self.selenium.find_elements(By.LINK_TEXT, "SHOW") for show_index, field_name in enumerate(fields): show_links[show_index].click() self.wait_until_visible("#" + field_name) self.selenium.find_element(By.ID, field_name).send_keys(1) # Before save all inputs have default border for inline in ("stacked", "tabular"): for field_name in ("name", "select", "text"): element_id = "id_inner5%s_set-0-%s" % (inline, field_name) self.assertBorder( self.selenium.find_element(By.ID, element_id), "1px solid #cccccc", ) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() # Test the red border around inputs by css selectors stacked_selectors = [".errors input", ".errors select", ".errors textarea"] for selector in stacked_selectors: self.assertBorder( self.selenium.find_element(By.CSS_SELECTOR, selector), "1px solid #ba2121", ) tabular_selectors = [ "td ul.errorlist + input", "td ul.errorlist + select", "td ul.errorlist + textarea", ] for selector in tabular_selectors: self.assertBorder( self.selenium.find_element(By.CSS_SELECTOR, selector), "1px solid #ba2121", ) def test_inline_formset_error(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_holder5_add") ) stacked_inline_formset_selector = ( "div#inner5stacked_set-group fieldset.module.collapse" ) tabular_inline_formset_selector = ( "div#inner5tabular_set-group fieldset.module.collapse" ) # Inlines without errors, both inlines collapsed self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.assertCountSeleniumElements( stacked_inline_formset_selector + ".collapsed", 1 ) self.assertCountSeleniumElements( tabular_inline_formset_selector + ".collapsed", 1 ) show_links = self.selenium.find_elements(By.LINK_TEXT, "SHOW") self.assertEqual(len(show_links), 2) # Inlines with errors, both inlines expanded test_fields = ["#id_inner5stacked_set-0-dummy", "#id_inner5tabular_set-0-dummy"] for show_index, field_name in enumerate(test_fields): show_links[show_index].click() self.wait_until_visible(field_name) self.selenium.find_element(By.ID, field_name[1:]).send_keys(1) hide_links = self.selenium.find_elements(By.LINK_TEXT, "HIDE") self.assertEqual(len(hide_links), 2) for hide_index, field_name in enumerate(test_fields): hide_link = hide_links[hide_index] self.selenium.execute_script( "window.scrollTo(0, %s);" % hide_link.location["y"] ) hide_link.click() self.wait_until_invisible(field_name) with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() with self.disable_implicit_wait(): self.assertCountSeleniumElements( stacked_inline_formset_selector + ".collapsed", 0 ) self.assertCountSeleniumElements( tabular_inline_formset_selector + ".collapsed", 0 ) self.assertCountSeleniumElements(stacked_inline_formset_selector, 1) self.assertCountSeleniumElements(tabular_inline_formset_selector, 1) def test_inlines_verbose_name(self): """ The item added by the "Add another XXX" link must use the correct verbose_name in the inline form. """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") # Hide sidebar. self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_course_add") ) toggle_button = self.selenium.find_element( By.CSS_SELECTOR, "#toggle-nav-sidebar" ) toggle_button.click() # Each combination of horizontal/vertical filter with stacked/tabular # inlines. tests = [ "admin:admin_inlines_course_add", "admin:admin_inlines_courseproxy_add", "admin:admin_inlines_courseproxy1_add", "admin:admin_inlines_courseproxy2_add", ] css_selector = ".dynamic-class_set#class_set-%s h2" for url_name in tests: with self.subTest(url=url_name): self.selenium.get(self.live_server_url + reverse(url_name)) # First inline shows the verbose_name. available, chosen = self.selenium.find_elements( By.CSS_SELECTOR, css_selector % 0 ) self.assertEqual(available.text, "AVAILABLE ATTENDANT") self.assertEqual(chosen.text, "CHOSEN ATTENDANT") # Added inline should also have the correct verbose_name. self.selenium.find_element(By.LINK_TEXT, "Add another Class").click() available, chosen = self.selenium.find_elements( By.CSS_SELECTOR, css_selector % 1 ) self.assertEqual(available.text, "AVAILABLE ATTENDANT") self.assertEqual(chosen.text, "CHOSEN ATTENDANT") # Third inline should also have the correct verbose_name. self.selenium.find_element(By.LINK_TEXT, "Add another Class").click() available, chosen = self.selenium.find_elements( By.CSS_SELECTOR, css_selector % 2 ) self.assertEqual(available.text, "AVAILABLE ATTENDANT") self.assertEqual(chosen.text, "CHOSEN ATTENDANT")
a647aeb2160e6c66242ebb00154c781d1671e5ecaf807d6faf4ff3d0166d1be2
from unittest import SkipTest from django.core import validators from django.core.exceptions import ValidationError from django.db import IntegrityError, connection, models from django.test import SimpleTestCase, TestCase from .models import ( BigIntegerModel, IntegerModel, PositiveBigIntegerModel, PositiveIntegerModel, PositiveSmallIntegerModel, SmallIntegerModel, ) class IntegerFieldTests(TestCase): model = IntegerModel documented_range = (-2147483648, 2147483647) rel_db_type_class = models.IntegerField @property def backend_range(self): field = self.model._meta.get_field("value") internal_type = field.get_internal_type() return connection.ops.integer_field_range(internal_type) def test_documented_range(self): """ Values within the documented safe range pass validation, and can be saved and retrieved without corruption. """ min_value, max_value = self.documented_range instance = self.model(value=min_value) instance.full_clean() instance.save() qs = self.model.objects.filter(value__lte=min_value) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, min_value) instance = self.model(value=max_value) instance.full_clean() instance.save() qs = self.model.objects.filter(value__gte=max_value) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, max_value) def test_backend_range_save(self): """ Backend specific ranges can be saved without corruption. """ min_value, max_value = self.backend_range if min_value is not None: instance = self.model(value=min_value) instance.full_clean() instance.save() qs = self.model.objects.filter(value__lte=min_value) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, min_value) if max_value is not None: instance = self.model(value=max_value) instance.full_clean() instance.save() qs = self.model.objects.filter(value__gte=max_value) self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].value, max_value) def test_backend_range_validation(self): """ Backend specific ranges are enforced at the model validation level (#12030). """ min_value, max_value = self.backend_range if min_value is not None: instance = self.model(value=min_value - 1) expected_message = validators.MinValueValidator.message % { "limit_value": min_value, } with self.assertRaisesMessage(ValidationError, expected_message): instance.full_clean() instance.value = min_value instance.full_clean() if max_value is not None: instance = self.model(value=max_value + 1) expected_message = validators.MaxValueValidator.message % { "limit_value": max_value, } with self.assertRaisesMessage(ValidationError, expected_message): instance.full_clean() instance.value = max_value instance.full_clean() def test_backend_range_min_value_lookups(self): min_value = self.backend_range[0] if min_value is None: raise SkipTest("Backend doesn't define an integer min value.") underflow_value = min_value - 1 self.model.objects.create(value=min_value) # A refresh of obj is necessary because last_insert_id() is bugged # on MySQL and returns invalid values. obj = self.model.objects.get(value=min_value) with self.assertNumQueries(0), self.assertRaises(self.model.DoesNotExist): self.model.objects.get(value=underflow_value) with self.assertNumQueries(1): self.assertEqual(self.model.objects.get(value__gt=underflow_value), obj) with self.assertNumQueries(1): self.assertEqual(self.model.objects.get(value__gte=underflow_value), obj) with self.assertNumQueries(0), self.assertRaises(self.model.DoesNotExist): self.model.objects.get(value__lt=underflow_value) with self.assertNumQueries(0), self.assertRaises(self.model.DoesNotExist): self.model.objects.get(value__lte=underflow_value) def test_backend_range_max_value_lookups(self): max_value = self.backend_range[-1] if max_value is None: raise SkipTest("Backend doesn't define an integer max value.") overflow_value = max_value + 1 obj = self.model.objects.create(value=max_value) with self.assertNumQueries(0), self.assertRaises(self.model.DoesNotExist): self.model.objects.get(value=overflow_value) with self.assertNumQueries(0), self.assertRaises(self.model.DoesNotExist): self.model.objects.get(value__gt=overflow_value) with self.assertNumQueries(0), self.assertRaises(self.model.DoesNotExist): self.model.objects.get(value__gte=overflow_value) with self.assertNumQueries(1): self.assertEqual(self.model.objects.get(value__lt=overflow_value), obj) with self.assertNumQueries(1): self.assertEqual(self.model.objects.get(value__lte=overflow_value), obj) def test_redundant_backend_range_validators(self): """ If there are stricter validators than the ones from the database backend then the backend validators aren't added. """ min_backend_value, max_backend_value = self.backend_range for callable_limit in (True, False): with self.subTest(callable_limit=callable_limit): if min_backend_value is not None: min_custom_value = min_backend_value + 1 limit_value = ( (lambda: min_custom_value) if callable_limit else min_custom_value ) ranged_value_field = self.model._meta.get_field("value").__class__( validators=[validators.MinValueValidator(limit_value)] ) field_range_message = validators.MinValueValidator.message % { "limit_value": min_custom_value, } with self.assertRaisesMessage( ValidationError, "[%r]" % field_range_message ): ranged_value_field.run_validators(min_backend_value - 1) if max_backend_value is not None: max_custom_value = max_backend_value - 1 limit_value = ( (lambda: max_custom_value) if callable_limit else max_custom_value ) ranged_value_field = self.model._meta.get_field("value").__class__( validators=[validators.MaxValueValidator(limit_value)] ) field_range_message = validators.MaxValueValidator.message % { "limit_value": max_custom_value, } with self.assertRaisesMessage( ValidationError, "[%r]" % field_range_message ): ranged_value_field.run_validators(max_backend_value + 1) def test_types(self): instance = self.model(value=1) self.assertIsInstance(instance.value, int) instance.save() self.assertIsInstance(instance.value, int) instance = self.model.objects.get() self.assertIsInstance(instance.value, int) def test_coercing(self): self.model.objects.create(value="10") instance = self.model.objects.get(value="10") self.assertEqual(instance.value, 10) def test_invalid_value(self): tests = [ (TypeError, ()), (TypeError, []), (TypeError, {}), (TypeError, set()), (TypeError, object()), (TypeError, complex()), (ValueError, "non-numeric string"), (ValueError, b"non-numeric byte-string"), ] for exception, value in tests: with self.subTest(value): msg = "Field 'value' expected a number but got %r." % (value,) with self.assertRaisesMessage(exception, msg): self.model.objects.create(value=value) def test_rel_db_type(self): field = self.model._meta.get_field("value") rel_db_type = field.rel_db_type(connection) self.assertEqual(rel_db_type, self.rel_db_type_class().db_type(connection)) class SmallIntegerFieldTests(IntegerFieldTests): model = SmallIntegerModel documented_range = (-32768, 32767) rel_db_type_class = models.SmallIntegerField class BigIntegerFieldTests(IntegerFieldTests): model = BigIntegerModel documented_range = (-9223372036854775808, 9223372036854775807) rel_db_type_class = models.BigIntegerField class PositiveSmallIntegerFieldTests(IntegerFieldTests): model = PositiveSmallIntegerModel documented_range = (0, 32767) rel_db_type_class = ( models.PositiveSmallIntegerField if connection.features.related_fields_match_type else models.SmallIntegerField ) class PositiveIntegerFieldTests(IntegerFieldTests): model = PositiveIntegerModel documented_range = (0, 2147483647) rel_db_type_class = ( models.PositiveIntegerField if connection.features.related_fields_match_type else models.IntegerField ) def test_negative_values(self): p = PositiveIntegerModel.objects.create(value=0) p.value = models.F("value") - 1 with self.assertRaises(IntegrityError): p.save() class PositiveBigIntegerFieldTests(IntegerFieldTests): model = PositiveBigIntegerModel documented_range = (0, 9223372036854775807) rel_db_type_class = ( models.PositiveBigIntegerField if connection.features.related_fields_match_type else models.BigIntegerField ) class ValidationTests(SimpleTestCase): class Choices(models.IntegerChoices): A = 1 def test_integerfield_cleans_valid_string(self): f = models.IntegerField() self.assertEqual(f.clean("2", None), 2) def test_integerfield_raises_error_on_invalid_intput(self): f = models.IntegerField() with self.assertRaises(ValidationError): f.clean("a", None) def test_choices_validation_supports_named_groups(self): f = models.IntegerField(choices=(("group", ((10, "A"), (20, "B"))), (30, "C"))) self.assertEqual(10, f.clean(10, None)) def test_nullable_integerfield_raises_error_with_blank_false(self): f = models.IntegerField(null=True, blank=False) with self.assertRaises(ValidationError): f.clean(None, None) def test_nullable_integerfield_cleans_none_on_null_and_blank_true(self): f = models.IntegerField(null=True, blank=True) self.assertIsNone(f.clean(None, None)) def test_integerfield_raises_error_on_empty_input(self): f = models.IntegerField(null=False) with self.assertRaises(ValidationError): f.clean(None, None) with self.assertRaises(ValidationError): f.clean("", None) def test_integerfield_validates_zero_against_choices(self): f = models.IntegerField(choices=((1, 1),)) with self.assertRaises(ValidationError): f.clean("0", None) def test_enum_choices_cleans_valid_string(self): f = models.IntegerField(choices=self.Choices) self.assertEqual(f.clean("1", None), 1) def test_enum_choices_invalid_input(self): f = models.IntegerField(choices=self.Choices) with self.assertRaises(ValidationError): f.clean("A", None) with self.assertRaises(ValidationError): f.clean("3", None)
a573d557c31db1d8f25742a76439b5957985bef5c93c46132e5e571493ac5099
import pickle from django import forms from django.core.exceptions import ValidationError from django.db import models from django.test import SimpleTestCase, TestCase from django.utils.functional import lazy from .models import ( Bar, Choiceful, Foo, RenamedField, VerboseNameField, Whiz, WhizDelayed, WhizIter, WhizIterEmpty, ) class Nested: class Field(models.Field): pass class BasicFieldTests(SimpleTestCase): def test_show_hidden_initial(self): """ Fields with choices respect show_hidden_initial as a kwarg to formfield(). """ choices = [(0, 0), (1, 1)] model_field = models.Field(choices=choices) form_field = model_field.formfield(show_hidden_initial=True) self.assertTrue(form_field.show_hidden_initial) form_field = model_field.formfield(show_hidden_initial=False) self.assertFalse(form_field.show_hidden_initial) def test_field_repr(self): """ __repr__() of a field displays its name. """ f = Foo._meta.get_field("a") self.assertEqual(repr(f), "<django.db.models.fields.CharField: a>") f = models.fields.CharField() self.assertEqual(repr(f), "<django.db.models.fields.CharField>") def test_field_repr_nested(self): """__repr__() uses __qualname__ for nested class support.""" self.assertEqual(repr(Nested.Field()), "<model_fields.tests.Nested.Field>") def test_field_name(self): """ A defined field name (name="fieldname") is used instead of the model model's attribute name (modelname). """ instance = RenamedField() self.assertTrue(hasattr(instance, "get_fieldname_display")) self.assertFalse(hasattr(instance, "get_modelname_display")) def test_field_verbose_name(self): m = VerboseNameField for i in range(1, 22): self.assertEqual( m._meta.get_field("field%d" % i).verbose_name, "verbose field%d" % i ) self.assertEqual(m._meta.get_field("id").verbose_name, "verbose pk") def test_choices_form_class(self): """Can supply a custom choices form class to Field.formfield()""" choices = [("a", "a")] field = models.CharField(choices=choices) klass = forms.TypedMultipleChoiceField self.assertIsInstance(field.formfield(choices_form_class=klass), klass) def test_formfield_disabled(self): """Field.formfield() sets disabled for fields with choices.""" field = models.CharField(choices=[("a", "b")]) form_field = field.formfield(disabled=True) self.assertIs(form_field.disabled, True) def test_field_str(self): f = models.Field() self.assertEqual(str(f), "<django.db.models.fields.Field>") f = Foo._meta.get_field("a") self.assertEqual(str(f), "model_fields.Foo.a") def test_field_ordering(self): """Fields are ordered based on their creation.""" f1 = models.Field() f2 = models.Field(auto_created=True) f3 = models.Field() self.assertLess(f2, f1) self.assertGreater(f3, f1) self.assertIsNotNone(f1) self.assertNotIn(f2, (None, 1, "")) def test_field_instance_is_picklable(self): """Field instances can be pickled.""" field = models.Field(max_length=100, default="a string") # Must be picklable with this cached property populated (#28188). field._get_default pickle.dumps(field) def test_deconstruct_nested_field(self): """deconstruct() uses __qualname__ for nested class support.""" name, path, args, kwargs = Nested.Field().deconstruct() self.assertEqual(path, "model_fields.tests.Nested.Field") def test_abstract_inherited_fields(self): """Field instances from abstract models are not equal.""" class AbstractModel(models.Model): field = models.IntegerField() class Meta: abstract = True class InheritAbstractModel1(AbstractModel): pass class InheritAbstractModel2(AbstractModel): pass abstract_model_field = AbstractModel._meta.get_field("field") inherit1_model_field = InheritAbstractModel1._meta.get_field("field") inherit2_model_field = InheritAbstractModel2._meta.get_field("field") self.assertNotEqual(abstract_model_field, inherit1_model_field) self.assertNotEqual(abstract_model_field, inherit2_model_field) self.assertNotEqual(inherit1_model_field, inherit2_model_field) self.assertLess(abstract_model_field, inherit1_model_field) self.assertLess(abstract_model_field, inherit2_model_field) self.assertLess(inherit1_model_field, inherit2_model_field) def test_hash_immutability(self): field = models.IntegerField() field_hash = hash(field) class MyModel(models.Model): rank = field self.assertEqual(field_hash, hash(field)) class ChoicesTests(SimpleTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.no_choices = Choiceful._meta.get_field("no_choices") cls.empty_choices = Choiceful._meta.get_field("empty_choices") cls.empty_choices_bool = Choiceful._meta.get_field("empty_choices_bool") cls.empty_choices_text = Choiceful._meta.get_field("empty_choices_text") cls.with_choices = Choiceful._meta.get_field("with_choices") cls.choices_from_enum = Choiceful._meta.get_field("choices_from_enum") def test_choices(self): self.assertIsNone(self.no_choices.choices) self.assertEqual(self.empty_choices.choices, ()) self.assertEqual(self.with_choices.choices, [(1, "A")]) def test_flatchoices(self): self.assertEqual(self.no_choices.flatchoices, []) self.assertEqual(self.empty_choices.flatchoices, []) self.assertEqual(self.with_choices.flatchoices, [(1, "A")]) def test_check(self): self.assertEqual(Choiceful.check(), []) def test_invalid_choice(self): model_instance = None # Actual model instance not needed. self.no_choices.validate(0, model_instance) msg = "['Value 99 is not a valid choice.']" with self.assertRaisesMessage(ValidationError, msg): self.empty_choices.validate(99, model_instance) with self.assertRaisesMessage(ValidationError, msg): self.with_choices.validate(99, model_instance) def test_formfield(self): no_choices_formfield = self.no_choices.formfield() self.assertIsInstance(no_choices_formfield, forms.IntegerField) fields = ( self.empty_choices, self.with_choices, self.empty_choices_bool, self.empty_choices_text, ) for field in fields: with self.subTest(field=field): self.assertIsInstance(field.formfield(), forms.ChoiceField) def test_choices_from_enum(self): # Choices class was transparently resolved when given as argument. self.assertEqual(self.choices_from_enum.choices, Choiceful.Suit.choices) class GetFieldDisplayTests(SimpleTestCase): def test_choices_and_field_display(self): """ get_choices() interacts with get_FIELD_display() to return the expected values. """ self.assertEqual(Whiz(c=1).get_c_display(), "First") # A nested value self.assertEqual(Whiz(c=0).get_c_display(), "Other") # A top level value self.assertEqual(Whiz(c=9).get_c_display(), 9) # Invalid value self.assertIsNone(Whiz(c=None).get_c_display()) # Blank value self.assertEqual(Whiz(c="").get_c_display(), "") # Empty value self.assertEqual(WhizDelayed(c=0).get_c_display(), "Other") # Delayed choices def test_get_FIELD_display_translated(self): """A translated display value is coerced to str.""" val = Whiz(c=5).get_c_display() self.assertIsInstance(val, str) self.assertEqual(val, "translated") def test_overriding_FIELD_display(self): class FooBar(models.Model): foo_bar = models.IntegerField(choices=[(1, "foo"), (2, "bar")]) def get_foo_bar_display(self): return "something" f = FooBar(foo_bar=1) self.assertEqual(f.get_foo_bar_display(), "something") def test_overriding_inherited_FIELD_display(self): class Base(models.Model): foo = models.CharField(max_length=254, choices=[("A", "Base A")]) class Meta: abstract = True class Child(Base): foo = models.CharField( max_length=254, choices=[("A", "Child A"), ("B", "Child B")] ) self.assertEqual(Child(foo="A").get_foo_display(), "Child A") self.assertEqual(Child(foo="B").get_foo_display(), "Child B") def test_iterator_choices(self): """ get_choices() works with Iterators. """ self.assertEqual(WhizIter(c=1).c, 1) # A nested value self.assertEqual(WhizIter(c=9).c, 9) # Invalid value self.assertIsNone(WhizIter(c=None).c) # Blank value self.assertEqual(WhizIter(c="").c, "") # Empty value def test_empty_iterator_choices(self): """ get_choices() works with empty iterators. """ self.assertEqual(WhizIterEmpty(c="a").c, "a") # A nested value self.assertEqual(WhizIterEmpty(c="b").c, "b") # Invalid value self.assertIsNone(WhizIterEmpty(c=None).c) # Blank value self.assertEqual(WhizIterEmpty(c="").c, "") # Empty value class GetChoicesTests(SimpleTestCase): def test_empty_choices(self): choices = [] f = models.CharField(choices=choices) self.assertEqual(f.get_choices(include_blank=False), choices) def test_blank_in_choices(self): choices = [("", "<><>"), ("a", "A")] f = models.CharField(choices=choices) self.assertEqual(f.get_choices(include_blank=True), choices) def test_blank_in_grouped_choices(self): choices = [ ("f", "Foo"), ("b", "Bar"), ( "Group", ( ("", "No Preference"), ("fg", "Foo"), ("bg", "Bar"), ), ), ] f = models.CharField(choices=choices) self.assertEqual(f.get_choices(include_blank=True), choices) def test_lazy_strings_not_evaluated(self): lazy_func = lazy(lambda x: 0 / 0, int) # raises ZeroDivisionError if evaluated. f = models.CharField(choices=[(lazy_func("group"), (("a", "A"), ("b", "B")))]) self.assertEqual(f.get_choices(include_blank=True)[0], ("", "---------")) class GetChoicesOrderingTests(TestCase): @classmethod def setUpTestData(cls): cls.foo1 = Foo.objects.create(a="a", d="12.35") cls.foo2 = Foo.objects.create(a="b", d="12.34") cls.bar1 = Bar.objects.create(a=cls.foo1, b="b") cls.bar2 = Bar.objects.create(a=cls.foo2, b="a") cls.field = Bar._meta.get_field("a") def assertChoicesEqual(self, choices, objs): self.assertEqual(choices, [(obj.pk, str(obj)) for obj in objs]) def test_get_choices(self): self.assertChoicesEqual( self.field.get_choices(include_blank=False, ordering=("a",)), [self.foo1, self.foo2], ) self.assertChoicesEqual( self.field.get_choices(include_blank=False, ordering=("-a",)), [self.foo2, self.foo1], ) def test_get_choices_default_ordering(self): self.addCleanup(setattr, Foo._meta, "ordering", Foo._meta.ordering) Foo._meta.ordering = ("d",) self.assertChoicesEqual( self.field.get_choices(include_blank=False), [self.foo2, self.foo1] ) def test_get_choices_reverse_related_field(self): self.assertChoicesEqual( self.field.remote_field.get_choices(include_blank=False, ordering=("a",)), [self.bar1, self.bar2], ) self.assertChoicesEqual( self.field.remote_field.get_choices(include_blank=False, ordering=("-a",)), [self.bar2, self.bar1], ) def test_get_choices_reverse_related_field_default_ordering(self): self.addCleanup(setattr, Bar._meta, "ordering", Bar._meta.ordering) Bar._meta.ordering = ("b",) self.assertChoicesEqual( self.field.remote_field.get_choices(include_blank=False), [self.bar2, self.bar1], ) class GetChoicesLimitChoicesToTests(TestCase): @classmethod def setUpTestData(cls): cls.foo1 = Foo.objects.create(a="a", d="12.34") cls.foo2 = Foo.objects.create(a="b", d="12.34") cls.bar1 = Bar.objects.create(a=cls.foo1, b="b") cls.bar2 = Bar.objects.create(a=cls.foo2, b="a") cls.field = Bar._meta.get_field("a") def assertChoicesEqual(self, choices, objs): self.assertCountEqual(choices, [(obj.pk, str(obj)) for obj in objs]) def test_get_choices(self): self.assertChoicesEqual( self.field.get_choices(include_blank=False, limit_choices_to={"a": "a"}), [self.foo1], ) self.assertChoicesEqual( self.field.get_choices(include_blank=False, limit_choices_to={}), [self.foo1, self.foo2], ) def test_get_choices_reverse_related_field(self): field = self.field.remote_field self.assertChoicesEqual( field.get_choices(include_blank=False, limit_choices_to={"b": "b"}), [self.bar1], ) self.assertChoicesEqual( field.get_choices(include_blank=False, limit_choices_to={}), [self.bar1, self.bar2], )
2f86ac4c0ada3d7af6c9177fad12bd75209a8111b7d779d35fa1a6d7c27e3b42
import json import tempfile import uuid from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.core.files.storage import FileSystemStorage from django.core.serializers.json import DjangoJSONEncoder from django.db import models from django.db.models.fields.files import ImageFieldFile from django.utils.translation import gettext_lazy as _ try: from PIL import Image except ImportError: Image = None class Foo(models.Model): a = models.CharField(max_length=10) d = models.DecimalField(max_digits=5, decimal_places=3) def get_foo(): return Foo.objects.get(id=1).pk class Bar(models.Model): b = models.CharField(max_length=10) a = models.ForeignKey(Foo, models.CASCADE, default=get_foo, related_name="bars") class Whiz(models.Model): CHOICES = ( ( "Group 1", ( (1, "First"), (2, "Second"), ), ), ( "Group 2", ( (3, "Third"), (4, "Fourth"), ), ), (0, "Other"), (5, _("translated")), ) c = models.IntegerField(choices=CHOICES, null=True) class WhizDelayed(models.Model): c = models.IntegerField(choices=(), null=True) # Contrived way of adding choices later. WhizDelayed._meta.get_field("c").choices = Whiz.CHOICES class WhizIter(models.Model): c = models.IntegerField(choices=iter(Whiz.CHOICES), null=True) class WhizIterEmpty(models.Model): c = models.CharField(choices=iter(()), blank=True, max_length=1) class Choiceful(models.Model): class Suit(models.IntegerChoices): DIAMOND = 1, "Diamond" SPADE = 2, "Spade" HEART = 3, "Heart" CLUB = 4, "Club" no_choices = models.IntegerField(null=True) empty_choices = models.IntegerField(choices=(), null=True) with_choices = models.IntegerField(choices=[(1, "A")], null=True) empty_choices_bool = models.BooleanField(choices=()) empty_choices_text = models.TextField(choices=()) choices_from_enum = models.IntegerField(choices=Suit) class BigD(models.Model): d = models.DecimalField(max_digits=32, decimal_places=30) class FloatModel(models.Model): size = models.FloatField() class BigS(models.Model): s = models.SlugField(max_length=255) class UnicodeSlugField(models.Model): s = models.SlugField(max_length=255, allow_unicode=True) class AutoModel(models.Model): value = models.AutoField(primary_key=True) class BigAutoModel(models.Model): value = models.BigAutoField(primary_key=True) class SmallAutoModel(models.Model): value = models.SmallAutoField(primary_key=True) class SmallIntegerModel(models.Model): value = models.SmallIntegerField() class IntegerModel(models.Model): value = models.IntegerField() class BigIntegerModel(models.Model): value = models.BigIntegerField() null_value = models.BigIntegerField(null=True, blank=True) class PositiveBigIntegerModel(models.Model): value = models.PositiveBigIntegerField() class PositiveSmallIntegerModel(models.Model): value = models.PositiveSmallIntegerField() class PositiveIntegerModel(models.Model): value = models.PositiveIntegerField() class Post(models.Model): title = models.CharField(max_length=100) body = models.TextField() class NullBooleanModel(models.Model): nbfield = models.BooleanField(null=True, blank=True) class BooleanModel(models.Model): bfield = models.BooleanField() class DateTimeModel(models.Model): d = models.DateField() dt = models.DateTimeField() t = models.TimeField() class DurationModel(models.Model): field = models.DurationField() class NullDurationModel(models.Model): field = models.DurationField(null=True) class PrimaryKeyCharModel(models.Model): string = models.CharField(max_length=10, primary_key=True) class FksToBooleans(models.Model): """Model with FKs to models with {Null,}BooleanField's, #15040""" bf = models.ForeignKey(BooleanModel, models.CASCADE) nbf = models.ForeignKey(NullBooleanModel, models.CASCADE) class FkToChar(models.Model): """Model with FK to a model with a CharField primary key, #19299""" out = models.ForeignKey(PrimaryKeyCharModel, models.CASCADE) class RenamedField(models.Model): modelname = models.IntegerField(name="fieldname", choices=((1, "One"),)) class VerboseNameField(models.Model): id = models.AutoField("verbose pk", primary_key=True) field1 = models.BigIntegerField("verbose field1") field2 = models.BooleanField("verbose field2", default=False) field3 = models.CharField("verbose field3", max_length=10) field4 = models.DateField("verbose field4") field5 = models.DateTimeField("verbose field5") field6 = models.DecimalField("verbose field6", max_digits=6, decimal_places=1) field7 = models.EmailField("verbose field7") field8 = models.FileField("verbose field8", upload_to="unused") field9 = models.FilePathField("verbose field9") field10 = models.FloatField("verbose field10") # Don't want to depend on Pillow in this test # field_image = models.ImageField("verbose field") field11 = models.IntegerField("verbose field11") field12 = models.GenericIPAddressField("verbose field12", protocol="ipv4") field13 = models.PositiveIntegerField("verbose field13") field14 = models.PositiveSmallIntegerField("verbose field14") field15 = models.SlugField("verbose field15") field16 = models.SmallIntegerField("verbose field16") field17 = models.TextField("verbose field17") field18 = models.TimeField("verbose field18") field19 = models.URLField("verbose field19") field20 = models.UUIDField("verbose field20") field21 = models.DurationField("verbose field21") class GenericIPAddress(models.Model): ip = models.GenericIPAddressField(null=True, protocol="ipv4") ############################################################################### # These models aren't used in any test, just here to ensure they validate # successfully. # See ticket #16570. class DecimalLessThanOne(models.Model): d = models.DecimalField(max_digits=3, decimal_places=3) # See ticket #18389. class FieldClassAttributeModel(models.Model): field_class = models.CharField ############################################################################### class DataModel(models.Model): short_data = models.BinaryField(max_length=10, default=b"\x08") data = models.BinaryField() ############################################################################### # FileField class Document(models.Model): myfile = models.FileField(upload_to="unused", unique=True) ############################################################################### # ImageField # If Pillow available, do these tests. if Image: class TestImageFieldFile(ImageFieldFile): """ Custom Field File class that records whether or not the underlying file was opened. """ def __init__(self, *args, **kwargs): self.was_opened = False super().__init__(*args, **kwargs) def open(self): self.was_opened = True super().open() class TestImageField(models.ImageField): attr_class = TestImageFieldFile # Set up a temp directory for file storage. temp_storage_dir = tempfile.mkdtemp() temp_storage = FileSystemStorage(temp_storage_dir) class Person(models.Model): """ Model that defines an ImageField with no dimension fields. """ name = models.CharField(max_length=50) mugshot = TestImageField(storage=temp_storage, upload_to="tests") class AbstractPersonWithHeight(models.Model): """ Abstract model that defines an ImageField with only one dimension field to make sure the dimension update is correctly run on concrete subclass instance post-initialization. """ mugshot = TestImageField( storage=temp_storage, upload_to="tests", height_field="mugshot_height" ) mugshot_height = models.PositiveSmallIntegerField() class Meta: abstract = True class PersonWithHeight(AbstractPersonWithHeight): """ Concrete model that subclass an abstract one with only on dimension field. """ name = models.CharField(max_length=50) class PersonWithHeightAndWidth(models.Model): """ Model that defines height and width fields after the ImageField. """ name = models.CharField(max_length=50) mugshot = TestImageField( storage=temp_storage, upload_to="tests", height_field="mugshot_height", width_field="mugshot_width", ) mugshot_height = models.PositiveSmallIntegerField() mugshot_width = models.PositiveSmallIntegerField() class PersonDimensionsFirst(models.Model): """ Model that defines height and width fields before the ImageField. """ name = models.CharField(max_length=50) mugshot_height = models.PositiveSmallIntegerField() mugshot_width = models.PositiveSmallIntegerField() mugshot = TestImageField( storage=temp_storage, upload_to="tests", height_field="mugshot_height", width_field="mugshot_width", ) class PersonTwoImages(models.Model): """ Model that: * Defines two ImageFields * Defines the height/width fields before the ImageFields * Has a nullable ImageField """ name = models.CharField(max_length=50) mugshot_height = models.PositiveSmallIntegerField() mugshot_width = models.PositiveSmallIntegerField() mugshot = TestImageField( storage=temp_storage, upload_to="tests", height_field="mugshot_height", width_field="mugshot_width", ) headshot_height = models.PositiveSmallIntegerField(blank=True, null=True) headshot_width = models.PositiveSmallIntegerField(blank=True, null=True) headshot = TestImageField( blank=True, null=True, storage=temp_storage, upload_to="tests", height_field="headshot_height", width_field="headshot_width", ) class CustomJSONDecoder(json.JSONDecoder): def __init__(self, object_hook=None, *args, **kwargs): return super().__init__(object_hook=self.as_uuid, *args, **kwargs) def as_uuid(self, dct): if "uuid" in dct: dct["uuid"] = uuid.UUID(dct["uuid"]) return dct class JSONModel(models.Model): value = models.JSONField() class Meta: required_db_features = {"supports_json_field"} class NullableJSONModel(models.Model): value = models.JSONField(blank=True, null=True) value_custom = models.JSONField( encoder=DjangoJSONEncoder, decoder=CustomJSONDecoder, null=True, ) class Meta: required_db_features = {"supports_json_field"} class RelatedJSONModel(models.Model): value = models.JSONField() json_model = models.ForeignKey(NullableJSONModel, models.CASCADE) class Meta: required_db_features = {"supports_json_field"} class AllFieldsModel(models.Model): big_integer = models.BigIntegerField() binary = models.BinaryField() boolean = models.BooleanField(default=False) char = models.CharField(max_length=10) date = models.DateField() datetime = models.DateTimeField() decimal = models.DecimalField(decimal_places=2, max_digits=2) duration = models.DurationField() email = models.EmailField() file_path = models.FilePathField() floatf = models.FloatField() integer = models.IntegerField() generic_ip = models.GenericIPAddressField() positive_integer = models.PositiveIntegerField() positive_small_integer = models.PositiveSmallIntegerField() slug = models.SlugField() small_integer = models.SmallIntegerField() text = models.TextField() time = models.TimeField() url = models.URLField() uuid = models.UUIDField() fo = models.ForeignObject( "self", on_delete=models.CASCADE, from_fields=["positive_integer"], to_fields=["id"], related_name="reverse", ) fk = models.ForeignKey("self", models.CASCADE, related_name="reverse2") m2m = models.ManyToManyField("self") oto = models.OneToOneField("self", models.CASCADE) object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType, models.CASCADE) gfk = GenericForeignKey() gr = GenericRelation(DataModel) class ManyToMany(models.Model): m2m = models.ManyToManyField("self") ############################################################################### class UUIDModel(models.Model): field = models.UUIDField() class NullableUUIDModel(models.Model): field = models.UUIDField(blank=True, null=True) class PrimaryKeyUUIDModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) class RelatedToUUIDModel(models.Model): uuid_fk = models.ForeignKey("PrimaryKeyUUIDModel", models.CASCADE) class UUIDChild(PrimaryKeyUUIDModel): pass class UUIDGrandchild(UUIDChild): pass
fb4f58232c18a42cfef2d300463154f281302f1080aeb8807be4ebefe052c06f
from django.core.exceptions import ValidationError from django.db import models from django.test import SimpleTestCase, TestCase from .models import Post class TestCharField(TestCase): def test_max_length_passed_to_formfield(self): """ CharField passes its max_length attribute to form fields created using the formfield() method. """ cf1 = models.CharField() cf2 = models.CharField(max_length=1234) self.assertIsNone(cf1.formfield().max_length) self.assertEqual(1234, cf2.formfield().max_length) def test_lookup_integer_in_charfield(self): self.assertEqual(Post.objects.filter(title=9).count(), 0) def test_emoji(self): p = Post.objects.create(title="Smile 😀", body="Whatever.") p.refresh_from_db() self.assertEqual(p.title, "Smile 😀") def test_assignment_from_choice_enum(self): class Event(models.TextChoices): C = "Carnival!" F = "Festival!" p1 = Post.objects.create(title=Event.C, body=Event.F) p1.refresh_from_db() self.assertEqual(p1.title, "Carnival!") self.assertEqual(p1.body, "Festival!") self.assertEqual(p1.title, Event.C) self.assertEqual(p1.body, Event.F) p2 = Post.objects.get(title="Carnival!") self.assertEqual(p1, p2) self.assertEqual(p2.title, Event.C) class TestMethods(SimpleTestCase): def test_deconstruct(self): field = models.CharField() *_, kwargs = field.deconstruct() self.assertEqual(kwargs, {}) field = models.CharField(db_collation="utf8_esperanto_ci") *_, kwargs = field.deconstruct() self.assertEqual(kwargs, {"db_collation": "utf8_esperanto_ci"}) class ValidationTests(SimpleTestCase): class Choices(models.TextChoices): C = "c", "C" def test_charfield_raises_error_on_empty_string(self): f = models.CharField() msg = "This field cannot be blank." with self.assertRaisesMessage(ValidationError, msg): f.clean("", None) def test_charfield_cleans_empty_string_when_blank_true(self): f = models.CharField(blank=True) self.assertEqual("", f.clean("", None)) def test_charfield_with_choices_cleans_valid_choice(self): f = models.CharField(max_length=1, choices=[("a", "A"), ("b", "B")]) self.assertEqual("a", f.clean("a", None)) def test_charfield_with_choices_raises_error_on_invalid_choice(self): f = models.CharField(choices=[("a", "A"), ("b", "B")]) msg = "Value 'not a' is not a valid choice." with self.assertRaisesMessage(ValidationError, msg): f.clean("not a", None) def test_enum_choices_cleans_valid_string(self): f = models.CharField(choices=self.Choices, max_length=1) self.assertEqual(f.clean("c", None), "c") def test_enum_choices_invalid_input(self): f = models.CharField(choices=self.Choices, max_length=1) msg = "Value 'a' is not a valid choice." with self.assertRaisesMessage(ValidationError, msg): f.clean("a", None) def test_charfield_raises_error_on_empty_input(self): f = models.CharField(null=False) msg = "This field cannot be null." with self.assertRaisesMessage(ValidationError, msg): f.clean(None, None)
d71667e00976a64cd91b68e5c0a14f8202a0a4f4e0cd28dcbe9b320bd38d2f7e
from datetime import datetime from django.contrib.admin.options import IncorrectLookupParameters from django.contrib.auth.models import User from django.test import RequestFactory, TestCase from django.utils.timezone import make_aware from .admin import EventAdmin from .admin import site as custom_site from .models import Event class DateHierarchyTests(TestCase): factory = RequestFactory() @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", email="[email protected]", password="xxx" ) def assertDateParams(self, query, expected_from_date, expected_to_date): query = {"date__%s" % field: val for field, val in query.items()} request = self.factory.get("/", query) request.user = self.superuser changelist = EventAdmin(Event, custom_site).get_changelist_instance(request) _, _, lookup_params, *_ = changelist.get_filters(request) self.assertEqual(lookup_params["date__gte"], [expected_from_date]) self.assertEqual(lookup_params["date__lt"], [expected_to_date]) def test_bounded_params(self): tests = ( ({"year": 2017}, datetime(2017, 1, 1), datetime(2018, 1, 1)), ({"year": 2017, "month": 2}, datetime(2017, 2, 1), datetime(2017, 3, 1)), ({"year": 2017, "month": 12}, datetime(2017, 12, 1), datetime(2018, 1, 1)), ( {"year": 2017, "month": 12, "day": 15}, datetime(2017, 12, 15), datetime(2017, 12, 16), ), ( {"year": 2017, "month": 12, "day": 31}, datetime(2017, 12, 31), datetime(2018, 1, 1), ), ( {"year": 2017, "month": 2, "day": 28}, datetime(2017, 2, 28), datetime(2017, 3, 1), ), ) for query, expected_from_date, expected_to_date in tests: with self.subTest(query=query): self.assertDateParams(query, expected_from_date, expected_to_date) def test_bounded_params_with_time_zone(self): with self.settings(USE_TZ=True, TIME_ZONE="Asia/Jerusalem"): self.assertDateParams( {"year": 2017, "month": 2, "day": 28}, make_aware(datetime(2017, 2, 28)), make_aware(datetime(2017, 3, 1)), ) def test_bounded_params_with_dst_time_zone(self): tests = [ # Northern hemisphere. ("Asia/Jerusalem", 3), ("Asia/Jerusalem", 10), # Southern hemisphere. ("Pacific/Chatham", 4), ("Pacific/Chatham", 9), ] for time_zone, month in tests: with self.subTest(time_zone=time_zone, month=month): with self.settings(USE_TZ=True, TIME_ZONE=time_zone): self.assertDateParams( {"year": 2019, "month": month}, make_aware(datetime(2019, month, 1)), make_aware(datetime(2019, month + 1, 1)), ) def test_invalid_params(self): tests = ( {"year": "x"}, {"year": 2017, "month": "x"}, {"year": 2017, "month": 12, "day": "x"}, {"year": 2017, "month": 13}, {"year": 2017, "month": 12, "day": 32}, {"year": 2017, "month": 0}, {"year": 2017, "month": 12, "day": 0}, ) for invalid_query in tests: with self.subTest(query=invalid_query), self.assertRaises( IncorrectLookupParameters ): self.assertDateParams(invalid_query, None, None)
e515ebb054982f05f846b473b8259d6c7f0f8f2d1a2535750844fce0d46a85c3
# Unittests for fixtures. import json import os import re from io import StringIO from pathlib import Path from django.core import management, serializers from django.core.exceptions import ImproperlyConfigured from django.core.serializers.base import DeserializationError from django.db import IntegrityError, transaction from django.db.models import signals from django.test import ( TestCase, TransactionTestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from .models import ( Absolute, Animal, Article, Book, Child, Circle1, Circle2, Circle3, ExternalDependency, M2MCircular1ThroughAB, M2MCircular1ThroughBC, M2MCircular1ThroughCA, M2MCircular2ThroughAB, M2MComplexA, M2MComplexB, M2MComplexCircular1A, M2MComplexCircular1B, M2MComplexCircular1C, M2MComplexCircular2A, M2MComplexCircular2B, M2MSimpleA, M2MSimpleB, M2MSimpleCircularA, M2MSimpleCircularB, M2MThroughAB, NaturalKeyWithFKDependency, NKChild, Parent, Person, RefToNKChild, Store, Stuff, Thingy, Widget, ) _cur_dir = os.path.dirname(os.path.abspath(__file__)) class TestFixtures(TestCase): def animal_pre_save_check(self, signal, sender, instance, **kwargs): self.pre_save_checks.append( ( "Count = %s (%s)" % (instance.count, type(instance.count)), "Weight = %s (%s)" % (instance.weight, type(instance.weight)), ) ) def test_duplicate_pk(self): """ This is a regression test for ticket #3790. """ # Load a fixture that uses PK=1 management.call_command( "loaddata", "sequence", verbosity=0, ) # Create a new animal. Without a sequence reset, this new object # will take a PK of 1 (on Postgres), and the save will fail. animal = Animal( name="Platypus", latin_name="Ornithorhynchus anatinus", count=2, weight=2.2, ) animal.save() self.assertGreater(animal.id, 1) def test_loaddata_not_found_fields_not_ignore(self): """ Test for ticket #9279 -- Error is raised for entries in the serialized data for fields that have been removed from the database when not ignored. """ with self.assertRaises(DeserializationError): management.call_command( "loaddata", "sequence_extra", verbosity=0, ) def test_loaddata_not_found_fields_ignore(self): """ Test for ticket #9279 -- Ignores entries in the serialized data for fields that have been removed from the database. """ management.call_command( "loaddata", "sequence_extra", ignore=True, verbosity=0, ) self.assertEqual(Animal.specimens.all()[0].name, "Lion") def test_loaddata_not_found_fields_ignore_xml(self): """ Test for ticket #19998 -- Ignore entries in the XML serialized data for fields that have been removed from the model definition. """ management.call_command( "loaddata", "sequence_extra_xml", ignore=True, verbosity=0, ) self.assertEqual(Animal.specimens.all()[0].name, "Wolf") @skipIfDBFeature("interprets_empty_strings_as_nulls") def test_pretty_print_xml(self): """ Regression test for ticket #4558 -- pretty printing of XML fixtures doesn't affect parsing of None values. """ # Load a pretty-printed XML fixture with Nulls. management.call_command( "loaddata", "pretty.xml", verbosity=0, ) self.assertIsNone(Stuff.objects.all()[0].name) self.assertIsNone(Stuff.objects.all()[0].owner) @skipUnlessDBFeature("interprets_empty_strings_as_nulls") def test_pretty_print_xml_empty_strings(self): """ Regression test for ticket #4558 -- pretty printing of XML fixtures doesn't affect parsing of None values. """ # Load a pretty-printed XML fixture with Nulls. management.call_command( "loaddata", "pretty.xml", verbosity=0, ) self.assertEqual(Stuff.objects.all()[0].name, "") self.assertIsNone(Stuff.objects.all()[0].owner) def test_absolute_path(self): """ Regression test for ticket #6436 -- os.path.join will throw away the initial parts of a path if it encounters an absolute path. This means that if a fixture is specified as an absolute path, we need to make sure we don't discover the absolute path in every fixture directory. """ load_absolute_path = os.path.join( os.path.dirname(__file__), "fixtures", "absolute.json" ) management.call_command( "loaddata", load_absolute_path, verbosity=0, ) self.assertEqual(Absolute.objects.count(), 1) def test_relative_path(self, path=["fixtures", "absolute.json"]): relative_path = os.path.join(*path) cwd = os.getcwd() try: os.chdir(_cur_dir) management.call_command( "loaddata", relative_path, verbosity=0, ) finally: os.chdir(cwd) self.assertEqual(Absolute.objects.count(), 1) @override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, "fixtures_1")]) def test_relative_path_in_fixture_dirs(self): self.test_relative_path(path=["inner", "absolute.json"]) def test_path_containing_dots(self): management.call_command( "loaddata", "path.containing.dots.json", verbosity=0, ) self.assertEqual(Absolute.objects.count(), 1) def test_unknown_format(self): """ Test for ticket #4371 -- Loading data of an unknown format should fail Validate that error conditions are caught correctly """ msg = ( "Problem installing fixture 'bad_fix.ture1': unkn is not a known " "serialization format." ) with self.assertRaisesMessage(management.CommandError, msg): management.call_command( "loaddata", "bad_fix.ture1.unkn", verbosity=0, ) @override_settings(SERIALIZATION_MODULES={"unkn": "unexistent.path"}) def test_unimportable_serializer(self): """ Failing serializer import raises the proper error """ with self.assertRaisesMessage(ImportError, "No module named 'unexistent'"): management.call_command( "loaddata", "bad_fix.ture1.unkn", verbosity=0, ) def test_invalid_data(self): """ Test for ticket #4371 -- Loading a fixture file with invalid data using explicit filename. Test for ticket #18213 -- warning conditions are caught correctly """ msg = "No fixture data found for 'bad_fixture2'. (File format may be invalid.)" with self.assertWarnsMessage(RuntimeWarning, msg): management.call_command( "loaddata", "bad_fixture2.xml", verbosity=0, ) def test_invalid_data_no_ext(self): """ Test for ticket #4371 -- Loading a fixture file with invalid data without file extension. Test for ticket #18213 -- warning conditions are caught correctly """ msg = "No fixture data found for 'bad_fixture2'. (File format may be invalid.)" with self.assertWarnsMessage(RuntimeWarning, msg): management.call_command( "loaddata", "bad_fixture2", verbosity=0, ) def test_empty(self): """ Test for ticket #18213 -- Loading a fixture file with no data output a warning. Previously empty fixture raises an error exception, see ticket #4371. """ msg = "No fixture data found for 'empty'. (File format may be invalid.)" with self.assertWarnsMessage(RuntimeWarning, msg): management.call_command( "loaddata", "empty", verbosity=0, ) def test_error_message(self): """ Regression for #9011 - error message is correct. Change from error to warning for ticket #18213. """ msg = "No fixture data found for 'bad_fixture2'. (File format may be invalid.)" with self.assertWarnsMessage(RuntimeWarning, msg): management.call_command( "loaddata", "bad_fixture2", "animal", verbosity=0, ) def test_pg_sequence_resetting_checks(self): """ Test for ticket #7565 -- PostgreSQL sequence resetting checks shouldn't ascend to parent models when inheritance is used (since they are treated individually). """ management.call_command( "loaddata", "model-inheritance.json", verbosity=0, ) self.assertEqual(Parent.objects.all()[0].id, 1) self.assertEqual(Child.objects.all()[0].id, 1) def test_close_connection_after_loaddata(self): """ Test for ticket #7572 -- MySQL has a problem if the same connection is used to create tables, load data, and then query over that data. To compensate, we close the connection after running loaddata. This ensures that a new connection is opened when test queries are issued. """ management.call_command( "loaddata", "big-fixture.json", verbosity=0, ) articles = Article.objects.exclude(id=9) self.assertEqual( list(articles.values_list("id", flat=True)), [1, 2, 3, 4, 5, 6, 7, 8] ) # Just for good measure, run the same query again. # Under the influence of ticket #7572, this will # give a different result to the previous call. self.assertEqual( list(articles.values_list("id", flat=True)), [1, 2, 3, 4, 5, 6, 7, 8] ) def test_field_value_coerce(self): """ Test for tickets #8298, #9942 - Field values should be coerced into the correct type by the deserializer, not as part of the database write. """ self.pre_save_checks = [] signals.pre_save.connect(self.animal_pre_save_check) try: management.call_command( "loaddata", "animal.xml", verbosity=0, ) self.assertEqual( self.pre_save_checks, [("Count = 42 (<class 'int'>)", "Weight = 1.2 (<class 'float'>)")], ) finally: signals.pre_save.disconnect(self.animal_pre_save_check) def test_dumpdata_uses_default_manager(self): """ Regression for #11286 Dumpdata honors the default manager. Dump the current contents of the database as a JSON fixture """ management.call_command( "loaddata", "animal.xml", verbosity=0, ) management.call_command( "loaddata", "sequence.json", verbosity=0, ) animal = Animal( name="Platypus", latin_name="Ornithorhynchus anatinus", count=2, weight=2.2, ) animal.save() out = StringIO() management.call_command( "dumpdata", "fixtures_regress.animal", format="json", stdout=out, ) # Output order isn't guaranteed, so check for parts data = out.getvalue() # Get rid of artifacts like '000000002' to eliminate the differences # between different Python versions. data = re.sub("0{6,}[0-9]", "", data) animals_data = sorted( [ { "pk": 1, "model": "fixtures_regress.animal", "fields": { "count": 3, "weight": 1.2, "name": "Lion", "latin_name": "Panthera leo", }, }, { "pk": 10, "model": "fixtures_regress.animal", "fields": { "count": 42, "weight": 1.2, "name": "Emu", "latin_name": "Dromaius novaehollandiae", }, }, { "pk": animal.pk, "model": "fixtures_regress.animal", "fields": { "count": 2, "weight": 2.2, "name": "Platypus", "latin_name": "Ornithorhynchus anatinus", }, }, ], key=lambda x: x["pk"], ) data = sorted(json.loads(data), key=lambda x: x["pk"]) self.maxDiff = 1024 self.assertEqual(data, animals_data) def test_proxy_model_included(self): """ Regression for #11428 - Proxy models aren't included when you dumpdata """ out = StringIO() # Create an instance of the concrete class widget = Widget.objects.create(name="grommet") management.call_command( "dumpdata", "fixtures_regress.widget", "fixtures_regress.widgetproxy", format="json", stdout=out, ) self.assertJSONEqual( out.getvalue(), '[{"pk": %d, "model": "fixtures_regress.widget", ' '"fields": {"name": "grommet"}}]' % widget.pk, ) @skipUnlessDBFeature("supports_forward_references") def test_loaddata_works_when_fixture_has_forward_refs(self): """ Forward references cause fixtures not to load in MySQL (InnoDB). """ management.call_command( "loaddata", "forward_ref.json", verbosity=0, ) self.assertEqual(Book.objects.all()[0].id, 1) self.assertEqual(Person.objects.all()[0].id, 4) def test_loaddata_raises_error_when_fixture_has_invalid_foreign_key(self): """ Data with nonexistent child key references raises error. """ with self.assertRaisesMessage(IntegrityError, "Problem installing fixture"): management.call_command( "loaddata", "forward_ref_bad_data.json", verbosity=0, ) @skipUnlessDBFeature("supports_forward_references") @override_settings( FIXTURE_DIRS=[ os.path.join(_cur_dir, "fixtures_1"), os.path.join(_cur_dir, "fixtures_2"), ] ) def test_loaddata_forward_refs_split_fixtures(self): """ Regression for #17530 - should be able to cope with forward references when the fixtures are not in the same files or directories. """ management.call_command( "loaddata", "forward_ref_1.json", "forward_ref_2.json", verbosity=0, ) self.assertEqual(Book.objects.all()[0].id, 1) self.assertEqual(Person.objects.all()[0].id, 4) def test_loaddata_no_fixture_specified(self): """ Error is quickly reported when no fixtures is provided in the command line. """ msg = ( "No database fixture specified. Please provide the path of at least one " "fixture in the command line." ) with self.assertRaisesMessage(management.CommandError, msg): management.call_command( "loaddata", verbosity=0, ) def test_ticket_20820(self): """ Regression for ticket #20820 -- loaddata on a model that inherits from a model with a M2M shouldn't blow up. """ management.call_command( "loaddata", "special-article.json", verbosity=0, ) def test_ticket_22421(self): """ Regression for ticket #22421 -- loaddata on a model that inherits from a grand-parent model with a M2M but via an abstract parent shouldn't blow up. """ management.call_command( "loaddata", "feature.json", verbosity=0, ) def test_loaddata_with_m2m_to_self(self): """ Regression test for ticket #17946. """ management.call_command( "loaddata", "m2mtoself.json", verbosity=0, ) @override_settings( FIXTURE_DIRS=[ os.path.join(_cur_dir, "fixtures_1"), os.path.join(_cur_dir, "fixtures_1"), ] ) def test_fixture_dirs_with_duplicates(self): """ settings.FIXTURE_DIRS cannot contain duplicates in order to avoid repeated fixture loading. """ with self.assertRaisesMessage( ImproperlyConfigured, "settings.FIXTURE_DIRS contains duplicates." ): management.call_command("loaddata", "absolute.json", verbosity=0) @override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, "fixtures")]) def test_fixture_dirs_with_default_fixture_path(self): """ settings.FIXTURE_DIRS cannot contain a default fixtures directory for application (app/fixtures) in order to avoid repeated fixture loading. """ msg = ( "'%s' is a default fixture directory for the '%s' app " "and cannot be listed in settings.FIXTURE_DIRS." % (os.path.join(_cur_dir, "fixtures"), "fixtures_regress") ) with self.assertRaisesMessage(ImproperlyConfigured, msg): management.call_command("loaddata", "absolute.json", verbosity=0) @override_settings(FIXTURE_DIRS=[Path(_cur_dir) / "fixtures"]) def test_fixture_dirs_with_default_fixture_path_as_pathlib(self): """ settings.FIXTURE_DIRS cannot contain a default fixtures directory for application (app/fixtures) in order to avoid repeated fixture loading. """ msg = ( "'%s' is a default fixture directory for the '%s' app " "and cannot be listed in settings.FIXTURE_DIRS." % (os.path.join(_cur_dir, "fixtures"), "fixtures_regress") ) with self.assertRaisesMessage(ImproperlyConfigured, msg): management.call_command("loaddata", "absolute.json", verbosity=0) @override_settings( FIXTURE_DIRS=[ os.path.join(_cur_dir, "fixtures_1"), os.path.join(_cur_dir, "fixtures_2"), ] ) def test_loaddata_with_valid_fixture_dirs(self): management.call_command( "loaddata", "absolute.json", verbosity=0, ) @override_settings(FIXTURE_DIRS=[Path(_cur_dir) / "fixtures_1"]) def test_fixtures_dir_pathlib(self): management.call_command("loaddata", "inner/absolute.json", verbosity=0) self.assertQuerySetEqual(Absolute.objects.all(), [1], transform=lambda o: o.pk) class NaturalKeyFixtureTests(TestCase): def test_nk_deserialize(self): """ Test for ticket #13030 - Python based parser version natural keys deserialize with fk to inheriting model """ management.call_command( "loaddata", "model-inheritance.json", verbosity=0, ) management.call_command( "loaddata", "nk-inheritance.json", verbosity=0, ) self.assertEqual(NKChild.objects.get(pk=1).data, "apple") self.assertEqual(RefToNKChild.objects.get(pk=1).nk_fk.data, "apple") def test_nk_deserialize_xml(self): """ Test for ticket #13030 - XML version natural keys deserialize with fk to inheriting model """ management.call_command( "loaddata", "model-inheritance.json", verbosity=0, ) management.call_command( "loaddata", "nk-inheritance.json", verbosity=0, ) management.call_command( "loaddata", "nk-inheritance2.xml", verbosity=0, ) self.assertEqual(NKChild.objects.get(pk=2).data, "banana") self.assertEqual(RefToNKChild.objects.get(pk=2).nk_fk.data, "apple") def test_nk_on_serialize(self): """ Natural key requirements are taken into account when serializing models. """ management.call_command( "loaddata", "forward_ref_lookup.json", verbosity=0, ) out = StringIO() management.call_command( "dumpdata", "fixtures_regress.book", "fixtures_regress.person", "fixtures_regress.store", verbosity=0, format="json", use_natural_foreign_keys=True, use_natural_primary_keys=True, stdout=out, ) self.assertJSONEqual( out.getvalue(), """ [{"fields": {"main": null, "name": "Amazon"}, "model": "fixtures_regress.store"}, {"fields": {"main": null, "name": "Borders"}, "model": "fixtures_regress.store"}, {"fields": {"name": "Neal Stephenson"}, "model": "fixtures_regress.person"}, {"pk": 1, "model": "fixtures_regress.book", "fields": {"stores": [["Amazon"], ["Borders"]], "name": "Cryptonomicon", "author": ["Neal Stephenson"]}}] """, ) def test_dependency_sorting(self): """ It doesn't matter what order you mention the models, Store *must* be serialized before then Person, and both must be serialized before Book. """ sorted_deps = serializers.sort_dependencies( [("fixtures_regress", [Book, Person, Store])] ) self.assertEqual(sorted_deps, [Store, Person, Book]) def test_dependency_sorting_2(self): sorted_deps = serializers.sort_dependencies( [("fixtures_regress", [Book, Store, Person])] ) self.assertEqual(sorted_deps, [Store, Person, Book]) def test_dependency_sorting_3(self): sorted_deps = serializers.sort_dependencies( [("fixtures_regress", [Store, Book, Person])] ) self.assertEqual(sorted_deps, [Store, Person, Book]) def test_dependency_sorting_4(self): sorted_deps = serializers.sort_dependencies( [("fixtures_regress", [Store, Person, Book])] ) self.assertEqual(sorted_deps, [Store, Person, Book]) def test_dependency_sorting_5(self): sorted_deps = serializers.sort_dependencies( [("fixtures_regress", [Person, Book, Store])] ) self.assertEqual(sorted_deps, [Store, Person, Book]) def test_dependency_sorting_6(self): sorted_deps = serializers.sort_dependencies( [("fixtures_regress", [Person, Store, Book])] ) self.assertEqual(sorted_deps, [Store, Person, Book]) def test_dependency_sorting_dangling(self): sorted_deps = serializers.sort_dependencies( [("fixtures_regress", [Person, Circle1, Store, Book])] ) self.assertEqual(sorted_deps, [Circle1, Store, Person, Book]) def test_dependency_sorting_tight_circular(self): with self.assertRaisesMessage( RuntimeError, "Can't resolve dependencies for fixtures_regress.Circle1, " "fixtures_regress.Circle2 in serialized app list.", ): serializers.sort_dependencies( [("fixtures_regress", [Person, Circle2, Circle1, Store, Book])] ) def test_dependency_sorting_tight_circular_2(self): with self.assertRaisesMessage( RuntimeError, "Can't resolve dependencies for fixtures_regress.Circle1, " "fixtures_regress.Circle2 in serialized app list.", ): serializers.sort_dependencies( [("fixtures_regress", [Circle1, Book, Circle2])] ) def test_dependency_self_referential(self): with self.assertRaisesMessage( RuntimeError, "Can't resolve dependencies for fixtures_regress.Circle3 in " "serialized app list.", ): serializers.sort_dependencies([("fixtures_regress", [Book, Circle3])]) def test_dependency_sorting_long(self): with self.assertRaisesMessage( RuntimeError, "Can't resolve dependencies for fixtures_regress.Circle1, " "fixtures_regress.Circle2, fixtures_regress.Circle3 in serialized " "app list.", ): serializers.sort_dependencies( [("fixtures_regress", [Person, Circle2, Circle1, Circle3, Store, Book])] ) def test_dependency_sorting_normal(self): sorted_deps = serializers.sort_dependencies( [("fixtures_regress", [Person, ExternalDependency, Book])] ) self.assertEqual(sorted_deps, [Person, Book, ExternalDependency]) def test_normal_pk(self): """ Normal primary keys work on a model with natural key capabilities. """ management.call_command( "loaddata", "non_natural_1.json", verbosity=0, ) management.call_command( "loaddata", "forward_ref_lookup.json", verbosity=0, ) management.call_command( "loaddata", "non_natural_2.xml", verbosity=0, ) books = Book.objects.all() self.assertQuerySetEqual( books, [ "<Book: Cryptonomicon by Neal Stephenson (available at Amazon, " "Borders)>", "<Book: Ender's Game by Orson Scott Card (available at Collins " "Bookstore)>", "<Book: Permutation City by Greg Egan (available at Angus and " "Robertson)>", ], transform=repr, ) class NaturalKeyFixtureOnOtherDatabaseTests(TestCase): databases = {"other"} def test_natural_key_dependencies(self): """ Natural keys with foreign keys in dependencies works in a multiple database setup. """ management.call_command( "loaddata", "nk_with_foreign_key.json", database="other", verbosity=0, ) obj = NaturalKeyWithFKDependency.objects.using("other").get() self.assertEqual(obj.name, "The Lord of the Rings") self.assertEqual(obj.author.name, "J.R.R. Tolkien") class M2MNaturalKeyFixtureTests(TestCase): """Tests for ticket #14426.""" def test_dependency_sorting_m2m_simple(self): """ M2M relations without explicit through models SHOULD count as dependencies Regression test for bugs that could be caused by flawed fixes to #14226, namely if M2M checks are removed from sort_dependencies altogether. """ sorted_deps = serializers.sort_dependencies( [("fixtures_regress", [M2MSimpleA, M2MSimpleB])] ) self.assertEqual(sorted_deps, [M2MSimpleB, M2MSimpleA]) def test_dependency_sorting_m2m_simple_circular(self): """ Resolving circular M2M relations without explicit through models should fail loudly """ with self.assertRaisesMessage( RuntimeError, "Can't resolve dependencies for fixtures_regress.M2MSimpleCircularA, " "fixtures_regress.M2MSimpleCircularB in serialized app list.", ): serializers.sort_dependencies( [("fixtures_regress", [M2MSimpleCircularA, M2MSimpleCircularB])] ) def test_dependency_sorting_m2m_complex(self): """ M2M relations with explicit through models should NOT count as dependencies. The through model itself will have dependencies, though. """ sorted_deps = serializers.sort_dependencies( [("fixtures_regress", [M2MComplexA, M2MComplexB, M2MThroughAB])] ) # Order between M2MComplexA and M2MComplexB doesn't matter. The through # model has dependencies to them though, so it should come last. self.assertEqual(sorted_deps[-1], M2MThroughAB) def test_dependency_sorting_m2m_complex_circular_1(self): """ Circular M2M relations with explicit through models should be serializable """ A, B, C, AtoB, BtoC, CtoA = ( M2MComplexCircular1A, M2MComplexCircular1B, M2MComplexCircular1C, M2MCircular1ThroughAB, M2MCircular1ThroughBC, M2MCircular1ThroughCA, ) sorted_deps = serializers.sort_dependencies( [("fixtures_regress", [A, B, C, AtoB, BtoC, CtoA])] ) # The dependency sorting should not result in an error, and the # through model should have dependencies to the other models and as # such come last in the list. self.assertEqual(sorted_deps[:3], [A, B, C]) self.assertEqual(sorted_deps[3:], [AtoB, BtoC, CtoA]) def test_dependency_sorting_m2m_complex_circular_2(self): """ Circular M2M relations with explicit through models should be serializable This test tests the circularity with explicit natural_key.dependencies """ sorted_deps = serializers.sort_dependencies( [ ( "fixtures_regress", [M2MComplexCircular2A, M2MComplexCircular2B, M2MCircular2ThroughAB], ) ] ) self.assertEqual(sorted_deps[:2], [M2MComplexCircular2A, M2MComplexCircular2B]) self.assertEqual(sorted_deps[2:], [M2MCircular2ThroughAB]) def test_dump_and_load_m2m_simple(self): """ Test serializing and deserializing back models with simple M2M relations """ a = M2MSimpleA.objects.create(data="a") b1 = M2MSimpleB.objects.create(data="b1") b2 = M2MSimpleB.objects.create(data="b2") a.b_set.add(b1) a.b_set.add(b2) out = StringIO() management.call_command( "dumpdata", "fixtures_regress.M2MSimpleA", "fixtures_regress.M2MSimpleB", use_natural_foreign_keys=True, stdout=out, ) for model in [M2MSimpleA, M2MSimpleB]: model.objects.all().delete() objects = serializers.deserialize("json", out.getvalue()) for obj in objects: obj.save() new_a = M2MSimpleA.objects.get_by_natural_key("a") self.assertCountEqual(new_a.b_set.all(), [b1, b2]) class TestTicket11101(TransactionTestCase): available_apps = ["fixtures_regress"] @skipUnlessDBFeature("supports_transactions") def test_ticket_11101(self): """Fixtures can be rolled back (ticket #11101).""" with transaction.atomic(): management.call_command( "loaddata", "thingy.json", verbosity=0, ) self.assertEqual(Thingy.objects.count(), 1) transaction.set_rollback(True) self.assertEqual(Thingy.objects.count(), 0) class TestLoadFixtureFromOtherAppDirectory(TestCase): """ #23612 -- fixtures path should be normalized to allow referencing relative paths on Windows. """ current_dir = os.path.abspath(os.path.dirname(__file__)) # relative_prefix is something like tests/fixtures_regress or # fixtures_regress depending on how runtests.py is invoked. # All path separators must be / in order to be a proper regression test on # Windows, so replace as appropriate. relative_prefix = os.path.relpath(current_dir, os.getcwd()).replace("\\", "/") fixtures = [relative_prefix + "/fixtures/absolute.json"] def test_fixtures_loaded(self): count = Absolute.objects.count() self.assertGreater(count, 0, "Fixtures not loaded properly.")
3aa02625061d45280ab83fce66bf77674ea83016aeb9ae7155a13eb4bc5e394c
import sys from datetime import date from django.forms import DateField, Form, SelectDateWidget from django.test import override_settings from django.utils import translation from django.utils.dates import MONTHS_AP from .base import WidgetTest class SelectDateWidgetTest(WidgetTest): maxDiff = None widget = SelectDateWidget( years=( "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", ), ) def test_render_empty(self): self.check_html( self.widget, "mydate", "", html=( """ <select name="mydate_month" id="id_mydate_month"> <option selected value="">---</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option selected value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option selected value="">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010">2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """ ), ) def test_render_none(self): """ Rendering the None or '' values should yield the same output. """ self.assertHTMLEqual( self.widget.render("mydate", None), self.widget.render("mydate", ""), ) def test_render_string(self): self.check_html( self.widget, "mydate", "2010-04-15", html=( """ <select name="mydate_month" id="id_mydate_month"> <option value="">---</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4" selected>April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15" selected>15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected>2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """ ), ) def test_render_datetime(self): self.assertHTMLEqual( self.widget.render("mydate", date(2010, 4, 15)), self.widget.render("mydate", "2010-04-15"), ) def test_render_invalid_date(self): """ Invalid dates should still render the failed date. """ self.check_html( self.widget, "mydate", "2010-02-31", html=( """ <select name="mydate_month" id="id_mydate_month"> <option value="">---</option> <option value="1">January</option> <option value="2" selected>February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31" selected>31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option value="">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected>2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """ ), ) def test_custom_months(self): widget = SelectDateWidget(months=MONTHS_AP, years=("2013",)) self.check_html( widget, "mydate", "", html=( """ <select name="mydate_month" id="id_mydate_month"> <option selected value="">---</option> <option value="1">Jan.</option> <option value="2">Feb.</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">Aug.</option> <option value="9">Sept.</option> <option value="10">Oct.</option> <option value="11">Nov.</option> <option value="12">Dec.</option> </select> <select name="mydate_day" id="id_mydate_day"> <option selected value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option selected value="">---</option> <option value="2013">2013</option> </select> """ ), ) def test_selectdate_required(self): class GetNotRequiredDate(Form): mydate = DateField(widget=SelectDateWidget, required=False) class GetRequiredDate(Form): mydate = DateField(widget=SelectDateWidget, required=True) self.assertFalse(GetNotRequiredDate().fields["mydate"].widget.is_required) self.assertTrue(GetRequiredDate().fields["mydate"].widget.is_required) def test_selectdate_empty_label(self): w = SelectDateWidget(years=("2014",), empty_label="empty_label") # Rendering the default state with empty_label set as string. self.assertInHTML( '<option selected value="">empty_label</option>', w.render("mydate", ""), count=3, ) w = SelectDateWidget( years=("2014",), empty_label=("empty_year", "empty_month", "empty_day") ) # Rendering the default state with empty_label tuple. self.assertHTMLEqual( w.render("mydate", ""), """ <select name="mydate_month" id="id_mydate_month"> <option selected value="">empty_month</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option selected value="">empty_day</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option selected value="">empty_year</option> <option value="2014">2014</option> </select> """, ) with self.assertRaisesMessage( ValueError, "empty_label list/tuple must have 3 elements." ): SelectDateWidget(years=("2014",), empty_label=("not enough", "values")) @translation.override("nl") def test_l10n(self): w = SelectDateWidget( years=( "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", ) ) self.assertEqual( w.value_from_datadict( {"date_year": "2010", "date_month": "8", "date_day": "13"}, {}, "date" ), "13-08-2010", ) self.assertHTMLEqual( w.render("date", "13-08-2010"), """ <select name="date_day" id="id_date_day"> <option value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13" selected>13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="date_month" id="id_date_month"> <option value="">---</option> <option value="1">januari</option> <option value="2">februari</option> <option value="3">maart</option> <option value="4">april</option> <option value="5">mei</option> <option value="6">juni</option> <option value="7">juli</option> <option value="8" selected>augustus</option> <option value="9">september</option> <option value="10">oktober</option> <option value="11">november</option> <option value="12">december</option> </select> <select name="date_year" id="id_date_year"> <option value="">---</option> <option value="2007">2007</option> <option value="2008">2008</option> <option value="2009">2009</option> <option value="2010" selected>2010</option> <option value="2011">2011</option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> </select> """, ) # Even with an invalid date, the widget should reflect the entered # value. self.assertEqual(w.render("mydate", "2010-02-30").count("selected"), 3) # Years before 1900 should work. w = SelectDateWidget(years=("1899",)) self.assertEqual( w.value_from_datadict( {"date_year": "1899", "date_month": "8", "date_day": "13"}, {}, "date" ), "13-08-1899", ) # And years before 1000 (demonstrating the need for # sanitize_strftime_format). w = SelectDateWidget(years=("0001",)) self.assertEqual( w.value_from_datadict( {"date_year": "0001", "date_month": "8", "date_day": "13"}, {}, "date" ), "13-08-0001", ) @override_settings(DATE_INPUT_FORMATS=["%d.%m.%Y"]) def test_custom_input_format(self): w = SelectDateWidget(years=("0001", "1899", "2009", "2010")) with translation.override(None): for values, expected_value in ( (("0001", "8", "13"), "13.08.0001"), (("1899", "7", "11"), "11.07.1899"), (("2009", "3", "7"), "07.03.2009"), ): with self.subTest(values=values): data = { "field_%s" % field: value for field, value in zip(("year", "month", "day"), values) } self.assertEqual( w.value_from_datadict(data, {}, "field"), expected_value ) expected_dict = { field: int(value) for field, value in zip(("year", "month", "day"), values) } self.assertEqual(w.format_value(expected_value), expected_dict) def test_format_value(self): valid_formats = [ "2000-1-1", "2000-10-15", "2000-01-01", "2000-01-0", "2000-0-01", "2000-0-0", "0-01-01", "0-01-0", "0-0-01", "0-0-0", ] for value in valid_formats: year, month, day = (int(x) or "" for x in value.split("-")) with self.subTest(value=value): self.assertEqual( self.widget.format_value(value), {"day": day, "month": month, "year": year}, ) invalid_formats = [ "2000-01-001", "2000-001-01", "2-01-01", "20-01-01", "200-01-01", "20000-01-01", ] for value in invalid_formats: with self.subTest(value=value): self.assertEqual( self.widget.format_value(value), {"day": None, "month": None, "year": None}, ) def test_value_from_datadict(self): tests = [ (("2000", "12", "1"), "2000-12-01"), (("", "12", "1"), "0-12-1"), (("2000", "", "1"), "2000-0-1"), (("2000", "12", ""), "2000-12-0"), (("", "", "", ""), None), ((None, "12", "1"), None), (("2000", None, "1"), None), (("2000", "12", None), None), ((str(sys.maxsize + 1), "12", "1"), "0-0-0"), ] for values, expected in tests: with self.subTest(values=values): data = {} for field_name, value in zip(("year", "month", "day"), values): if value is not None: data["field_%s" % field_name] = value self.assertEqual( self.widget.value_from_datadict(data, {}, "field"), expected ) def test_value_omitted_from_data(self): self.assertIs(self.widget.value_omitted_from_data({}, {}, "field"), True) self.assertIs( self.widget.value_omitted_from_data({"field_month": "12"}, {}, "field"), False, ) self.assertIs( self.widget.value_omitted_from_data({"field_year": "2000"}, {}, "field"), False, ) self.assertIs( self.widget.value_omitted_from_data({"field_day": "1"}, {}, "field"), False ) data = {"field_day": "1", "field_month": "12", "field_year": "2000"} self.assertIs(self.widget.value_omitted_from_data(data, {}, "field"), False) @override_settings(USE_THOUSAND_SEPARATOR=True) def test_years_rendered_without_separator(self): widget = SelectDateWidget(years=(2007,)) self.check_html( widget, "mydate", "", html=( """ <select name="mydate_month" id="id_mydate_month"> <option selected value="">---</option> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name="mydate_day" id="id_mydate_day"> <option selected value="">---</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mydate_year" id="id_mydate_year"> <option selected value="">---</option> <option value="2007">2007</option> </select> """ ), ) def test_fieldset(self): class TestForm(Form): template_name = "forms_tests/use_fieldset.html" field = DateField(widget=self.widget) form = TestForm() self.assertIs(self.widget.use_fieldset, True) self.assertHTMLEqual( '<div><fieldset><legend for="id_field_month">Field:</legend>' '<select name="field_month" required id="id_field_month">' '<option value="1">January</option><option value="2">February</option>' '<option value="3">March</option><option value="4">April</option>' '<option value="5">May</option><option value="6">June</option>' '<option value="7">July</option><option value="8">August</option>' '<option value="9">September</option><option value="10">October</option>' '<option value="11">November</option><option value="12">December</option>' '</select><select name="field_day" required id="id_field_day">' '<option value="1">1</option><option value="2">2</option>' '<option value="3">3</option><option value="4">4</option>' '<option value="5">5</option><option value="6">6</option>' '<option value="7">7</option><option value="8">8</option>' '<option value="9">9</option><option value="10">10</option>' '<option value="11">11</option><option value="12">12</option>' '<option value="13">13</option><option value="14">14</option>' '<option value="15">15</option><option value="16">16</option>' '<option value="17">17</option><option value="18">18</option>' '<option value="19">19</option><option value="20">20</option>' '<option value="21">21</option><option value="22">22</option>' '<option value="23">23</option><option value="24">24</option>' '<option value="25">25</option><option value="26">26</option>' '<option value="27">27</option><option value="28">28</option>' '<option value="29">29</option><option value="30">30</option>' '<option value="31">31</option></select>' '<select name="field_year" required id="id_field_year">' '<option value="2007">2007</option><option value="2008">2008</option>' '<option value="2009">2009</option><option value="2010">2010</option>' '<option value="2011">2011</option><option value="2012">2012</option>' '<option value="2013">2013</option><option value="2014">2014</option>' '<option value="2015">2015</option><option value="2016">2016</option>' "</select></fieldset></div>", form.render(), )
5f15097d33aee97b75e57704ed28a8d88a0d26a01f2f6cc378e7f7548ec19e51
import sys from datetime import date, datetime from django.core.exceptions import ValidationError from django.forms import DateField, Form, HiddenInput, SelectDateWidget from django.test import SimpleTestCase from django.utils import translation class GetDate(Form): mydate = DateField(widget=SelectDateWidget) class DateFieldTest(SimpleTestCase): def test_form_field(self): a = GetDate({"mydate_month": "4", "mydate_day": "1", "mydate_year": "2008"}) self.assertTrue(a.is_valid()) self.assertEqual(a.cleaned_data["mydate"], date(2008, 4, 1)) # As with any widget that implements get_value_from_datadict(), we must # accept the input from the "as_hidden" rendering as well. self.assertHTMLEqual( a["mydate"].as_hidden(), '<input type="hidden" name="mydate" value="2008-04-01" id="id_mydate">', ) b = GetDate({"mydate": "2008-4-1"}) self.assertTrue(b.is_valid()) self.assertEqual(b.cleaned_data["mydate"], date(2008, 4, 1)) # Invalid dates shouldn't be allowed c = GetDate({"mydate_month": "2", "mydate_day": "31", "mydate_year": "2010"}) self.assertFalse(c.is_valid()) self.assertEqual(c.errors, {"mydate": ["Enter a valid date."]}) # label tag is correctly associated with month dropdown d = GetDate({"mydate_month": "1", "mydate_day": "1", "mydate_year": "2010"}) self.assertIn('<label for="id_mydate_month">', d.as_p()) # Inputs raising an OverflowError. e = GetDate( { "mydate_month": str(sys.maxsize + 1), "mydate_day": "31", "mydate_year": "2010", } ) self.assertIs(e.is_valid(), False) self.assertEqual(e.errors, {"mydate": ["Enter a valid date."]}) @translation.override("nl") def test_l10n_date_changed(self): """ DateField.has_changed() with SelectDateWidget works with a localized date format (#17165). """ # With Field.show_hidden_initial=False b = GetDate( { "mydate_year": "2008", "mydate_month": "4", "mydate_day": "1", }, initial={"mydate": date(2008, 4, 1)}, ) self.assertFalse(b.has_changed()) b = GetDate( { "mydate_year": "2008", "mydate_month": "4", "mydate_day": "2", }, initial={"mydate": date(2008, 4, 1)}, ) self.assertTrue(b.has_changed()) # With Field.show_hidden_initial=True class GetDateShowHiddenInitial(Form): mydate = DateField(widget=SelectDateWidget, show_hidden_initial=True) b = GetDateShowHiddenInitial( { "mydate_year": "2008", "mydate_month": "4", "mydate_day": "1", "initial-mydate": HiddenInput().format_value(date(2008, 4, 1)), }, initial={"mydate": date(2008, 4, 1)}, ) self.assertFalse(b.has_changed()) b = GetDateShowHiddenInitial( { "mydate_year": "2008", "mydate_month": "4", "mydate_day": "22", "initial-mydate": HiddenInput().format_value(date(2008, 4, 1)), }, initial={"mydate": date(2008, 4, 1)}, ) self.assertTrue(b.has_changed()) b = GetDateShowHiddenInitial( { "mydate_year": "2008", "mydate_month": "4", "mydate_day": "22", "initial-mydate": HiddenInput().format_value(date(2008, 4, 1)), }, initial={"mydate": date(2008, 4, 22)}, ) self.assertTrue(b.has_changed()) b = GetDateShowHiddenInitial( { "mydate_year": "2008", "mydate_month": "4", "mydate_day": "22", "initial-mydate": HiddenInput().format_value(date(2008, 4, 22)), }, initial={"mydate": date(2008, 4, 1)}, ) self.assertFalse(b.has_changed()) @translation.override("nl") def test_l10n_invalid_date_in(self): # Invalid dates shouldn't be allowed a = GetDate({"mydate_month": "2", "mydate_day": "31", "mydate_year": "2010"}) self.assertFalse(a.is_valid()) # 'Geef een geldige datum op.' = 'Enter a valid date.' self.assertEqual(a.errors, {"mydate": ["Voer een geldige datum in."]}) @translation.override("nl") def test_form_label_association(self): # label tag is correctly associated with first rendered dropdown a = GetDate({"mydate_month": "1", "mydate_day": "1", "mydate_year": "2010"}) self.assertIn('<label for="id_mydate_day">', a.as_p()) def test_datefield_1(self): f = DateField() self.assertEqual(date(2006, 10, 25), f.clean(date(2006, 10, 25))) self.assertEqual(date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30))) self.assertEqual( date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30, 59)) ) self.assertEqual( date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30, 59, 200)) ) self.assertEqual(date(2006, 10, 25), f.clean("2006-10-25")) self.assertEqual(date(2006, 10, 25), f.clean("10/25/2006")) self.assertEqual(date(2006, 10, 25), f.clean("10/25/06")) self.assertEqual(date(2006, 10, 25), f.clean("Oct 25 2006")) self.assertEqual(date(2006, 10, 25), f.clean("October 25 2006")) self.assertEqual(date(2006, 10, 25), f.clean("October 25, 2006")) self.assertEqual(date(2006, 10, 25), f.clean("25 October 2006")) self.assertEqual(date(2006, 10, 25), f.clean("25 October, 2006")) with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean("2006-4-31") with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean("200a-10-25") with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean("25/10/06") with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean("0-0-0") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) def test_datefield_2(self): f = DateField(required=False) self.assertIsNone(f.clean(None)) self.assertEqual("None", repr(f.clean(None))) self.assertIsNone(f.clean("")) self.assertEqual("None", repr(f.clean(""))) def test_datefield_3(self): f = DateField(input_formats=["%Y %m %d"]) self.assertEqual(date(2006, 10, 25), f.clean(date(2006, 10, 25))) self.assertEqual(date(2006, 10, 25), f.clean(datetime(2006, 10, 25, 14, 30))) self.assertEqual(date(2006, 10, 25), f.clean("2006 10 25")) with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean("2006-10-25") with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean("10/25/2006") with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean("10/25/06") def test_datefield_4(self): # Test whitespace stripping behavior (#5714) f = DateField() self.assertEqual(date(2006, 10, 25), f.clean(" 10/25/2006 ")) self.assertEqual(date(2006, 10, 25), f.clean(" 10/25/06 ")) self.assertEqual(date(2006, 10, 25), f.clean(" Oct 25 2006 ")) self.assertEqual(date(2006, 10, 25), f.clean(" October 25 2006 ")) self.assertEqual(date(2006, 10, 25), f.clean(" October 25, 2006 ")) self.assertEqual(date(2006, 10, 25), f.clean(" 25 October 2006 ")) with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean(" ") def test_datefield_5(self): # Test null bytes (#18982) f = DateField() with self.assertRaisesMessage(ValidationError, "'Enter a valid date.'"): f.clean("a\x00b") def test_datefield_changed(self): format = "%d/%m/%Y" f = DateField(input_formats=[format]) d = date(2007, 9, 17) self.assertFalse(f.has_changed(d, "17/09/2007")) def test_datefield_strptime(self): """field.strptime() doesn't raise a UnicodeEncodeError (#16123)""" f = DateField() try: f.strptime("31 мая 2011", "%d-%b-%y") except Exception as e: # assertIsInstance or assertRaises cannot be used because UnicodeEncodeError # is a subclass of ValueError self.assertEqual(e.__class__, ValueError)
b7ada6e3a8762426a05bd7b416115eeca590f3618cf7c81cc249d19cd1a8d98c
from django.core.exceptions import ValidationError from django.db import models from django.forms import ChoiceField, Form from django.test import SimpleTestCase from . import FormFieldAssertionsMixin class ChoiceFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_choicefield_1(self): f = ChoiceField(choices=[("1", "One"), ("2", "Two")]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertEqual("1", f.clean(1)) self.assertEqual("1", f.clean("1")) msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean("3") def test_choicefield_2(self): f = ChoiceField(choices=[("1", "One"), ("2", "Two")], required=False) self.assertEqual("", f.clean("")) self.assertEqual("", f.clean(None)) self.assertEqual("1", f.clean(1)) self.assertEqual("1", f.clean("1")) msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean("3") def test_choicefield_3(self): f = ChoiceField(choices=[("J", "John"), ("P", "Paul")]) self.assertEqual("J", f.clean("J")) msg = "'Select a valid choice. John is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean("John") def test_choicefield_4(self): f = ChoiceField( choices=[ ("Numbers", (("1", "One"), ("2", "Two"))), ("Letters", (("3", "A"), ("4", "B"))), ("5", "Other"), ] ) self.assertEqual("1", f.clean(1)) self.assertEqual("1", f.clean("1")) self.assertEqual("3", f.clean(3)) self.assertEqual("3", f.clean("3")) self.assertEqual("5", f.clean(5)) self.assertEqual("5", f.clean("5")) msg = "'Select a valid choice. 6 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean("6") def test_choicefield_choices_default(self): f = ChoiceField() self.assertEqual(f.choices, []) def test_choicefield_callable(self): def choices(): return [("J", "John"), ("P", "Paul")] f = ChoiceField(choices=choices) self.assertEqual("J", f.clean("J")) def test_choicefield_callable_may_evaluate_to_different_values(self): choices = [] def choices_as_callable(): return choices class ChoiceFieldForm(Form): choicefield = ChoiceField(choices=choices_as_callable) choices = [("J", "John")] form = ChoiceFieldForm() self.assertEqual([("J", "John")], list(form.fields["choicefield"].choices)) choices = [("P", "Paul")] form = ChoiceFieldForm() self.assertEqual([("P", "Paul")], list(form.fields["choicefield"].choices)) def test_choicefield_disabled(self): f = ChoiceField(choices=[("J", "John"), ("P", "Paul")], disabled=True) self.assertWidgetRendersTo( f, '<select id="id_f" name="f" disabled><option value="J">John</option>' '<option value="P">Paul</option></select>', ) def test_choicefield_enumeration(self): class FirstNames(models.TextChoices): JOHN = "J", "John" PAUL = "P", "Paul" f = ChoiceField(choices=FirstNames) self.assertEqual(f.choices, FirstNames.choices) self.assertEqual(f.clean("J"), "J") msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): f.clean("3")
4aba509a7f6e03dad38754d69bb120964066bac979c86d4aead2bccfae1e67c0
import copy import json from django.core.exceptions import ValidationError from django.forms.utils import ( ErrorDict, ErrorList, RenderableFieldMixin, RenderableMixin, flatatt, pretty_name, ) from django.test import SimpleTestCase from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy class FormsUtilsTestCase(SimpleTestCase): # Tests for forms/utils.py module. def test_flatatt(self): ########### # flatatt # ########### self.assertEqual(flatatt({"id": "header"}), ' id="header"') self.assertEqual( flatatt({"class": "news", "title": "Read this"}), ' class="news" title="Read this"', ) self.assertEqual( flatatt({"class": "news", "title": "Read this", "required": "required"}), ' class="news" required="required" title="Read this"', ) self.assertEqual( flatatt({"class": "news", "title": "Read this", "required": True}), ' class="news" title="Read this" required', ) self.assertEqual( flatatt({"class": "news", "title": "Read this", "required": False}), ' class="news" title="Read this"', ) self.assertEqual(flatatt({"class": None}), "") self.assertEqual(flatatt({}), "") def test_flatatt_no_side_effects(self): """ flatatt() does not modify the dict passed in. """ attrs = {"foo": "bar", "true": True, "false": False} attrs_copy = copy.copy(attrs) self.assertEqual(attrs, attrs_copy) first_run = flatatt(attrs) self.assertEqual(attrs, attrs_copy) self.assertEqual(first_run, ' foo="bar" true') second_run = flatatt(attrs) self.assertEqual(attrs, attrs_copy) self.assertEqual(first_run, second_run) def test_validation_error(self): ################### # ValidationError # ################### # Can take a string. self.assertHTMLEqual( str(ErrorList(ValidationError("There was an error.").messages)), '<ul class="errorlist"><li>There was an error.</li></ul>', ) # Can take a Unicode string. self.assertHTMLEqual( str(ErrorList(ValidationError("Not \u03C0.").messages)), '<ul class="errorlist"><li>Not π.</li></ul>', ) # Can take a lazy string. self.assertHTMLEqual( str(ErrorList(ValidationError(gettext_lazy("Error.")).messages)), '<ul class="errorlist"><li>Error.</li></ul>', ) # Can take a list. self.assertHTMLEqual( str(ErrorList(ValidationError(["Error one.", "Error two."]).messages)), '<ul class="errorlist"><li>Error one.</li><li>Error two.</li></ul>', ) # Can take a dict. self.assertHTMLEqual( str( ErrorList( sorted( ValidationError( {"error_1": "1. Error one.", "error_2": "2. Error two."} ).messages ) ) ), '<ul class="errorlist"><li>1. Error one.</li><li>2. Error two.</li></ul>', ) # Can take a mixture in a list. self.assertHTMLEqual( str( ErrorList( sorted( ValidationError( [ "1. First error.", "2. Not \u03C0.", gettext_lazy("3. Error."), { "error_1": "4. First dict error.", "error_2": "5. Second dict error.", }, ] ).messages ) ) ), '<ul class="errorlist">' "<li>1. First error.</li>" "<li>2. Not π.</li>" "<li>3. Error.</li>" "<li>4. First dict error.</li>" "<li>5. Second dict error.</li>" "</ul>", ) class VeryBadError: def __str__(self): return "A very bad error." # Can take a non-string. self.assertHTMLEqual( str(ErrorList(ValidationError(VeryBadError()).messages)), '<ul class="errorlist"><li>A very bad error.</li></ul>', ) # Escapes non-safe input but not input marked safe. example = 'Example of link: <a href="http://www.example.com/">example</a>' self.assertHTMLEqual( str(ErrorList([example])), '<ul class="errorlist"><li>Example of link: ' "&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;" "</li></ul>", ) self.assertHTMLEqual( str(ErrorList([mark_safe(example)])), '<ul class="errorlist"><li>Example of link: ' '<a href="http://www.example.com/">example</a></li></ul>', ) self.assertHTMLEqual( str(ErrorDict({"name": example})), '<ul class="errorlist"><li>nameExample of link: ' "&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;" "</li></ul>", ) self.assertHTMLEqual( str(ErrorDict({"name": mark_safe(example)})), '<ul class="errorlist"><li>nameExample of link: ' '<a href="http://www.example.com/">example</a></li></ul>', ) def test_error_dict_copy(self): e = ErrorDict() e["__all__"] = ErrorList( [ ValidationError( message="message %(i)s", params={"i": 1}, ), ValidationError( message="message %(i)s", params={"i": 2}, ), ] ) e_copy = copy.copy(e) self.assertEqual(e, e_copy) self.assertEqual(e.as_data(), e_copy.as_data()) e_deepcopy = copy.deepcopy(e) self.assertEqual(e, e_deepcopy) def test_error_dict_html_safe(self): e = ErrorDict() e["username"] = "Invalid username." self.assertTrue(hasattr(ErrorDict, "__html__")) self.assertEqual(str(e), e.__html__()) def test_error_list_html_safe(self): e = ErrorList(["Invalid username."]) self.assertTrue(hasattr(ErrorList, "__html__")) self.assertEqual(str(e), e.__html__()) def test_error_dict_is_dict(self): self.assertIsInstance(ErrorDict(), dict) def test_error_dict_is_json_serializable(self): init_errors = ErrorDict( [ ( "__all__", ErrorList( [ValidationError("Sorry this form only works on leap days.")] ), ), ("name", ErrorList([ValidationError("This field is required.")])), ] ) min_value_error_list = ErrorList( [ValidationError("Ensure this value is greater than or equal to 0.")] ) e = ErrorDict( init_errors, date=ErrorList( [ ErrorDict( { "day": min_value_error_list, "month": min_value_error_list, "year": min_value_error_list, } ), ] ), ) e["renderer"] = ErrorList( [ ValidationError( "Select a valid choice. That choice is not one of the " "available choices." ), ] ) self.assertJSONEqual( json.dumps(e), { "__all__": ["Sorry this form only works on leap days."], "name": ["This field is required."], "date": [ { "day": ["Ensure this value is greater than or equal to 0."], "month": ["Ensure this value is greater than or equal to 0."], "year": ["Ensure this value is greater than or equal to 0."], }, ], "renderer": [ "Select a valid choice. That choice is not one of the " "available choices." ], }, ) def test_get_context_must_be_implemented(self): mixin = RenderableMixin() msg = "Subclasses of RenderableMixin must provide a get_context() method." with self.assertRaisesMessage(NotImplementedError, msg): mixin.get_context() def test_field_mixin_as_hidden_must_be_implemented(self): mixin = RenderableFieldMixin() msg = "Subclasses of RenderableFieldMixin must provide an as_hidden() method." with self.assertRaisesMessage(NotImplementedError, msg): mixin.as_hidden() def test_field_mixin_as_widget_must_be_implemented(self): mixin = RenderableFieldMixin() msg = "Subclasses of RenderableFieldMixin must provide an as_widget() method." with self.assertRaisesMessage(NotImplementedError, msg): mixin.as_widget() def test_pretty_name(self): self.assertEqual(pretty_name("john_doe"), "John doe") self.assertEqual(pretty_name(None), "") self.assertEqual(pretty_name(""), "")
2ddad070ec96f0aff6cf373a75413f0694ecf35b6d852b7e166e51324ed94d57
import copy import datetime import json import uuid from django.core.exceptions import NON_FIELD_ERRORS from django.core.files.uploadedfile import SimpleUploadedFile from django.core.validators import MaxValueValidator, RegexValidator from django.forms import ( BooleanField, CharField, CheckboxSelectMultiple, ChoiceField, DateField, DateTimeField, EmailField, FileField, FileInput, FloatField, Form, HiddenInput, ImageField, IntegerField, MultipleChoiceField, MultipleHiddenInput, MultiValueField, MultiWidget, NullBooleanField, PasswordInput, RadioSelect, Select, SplitDateTimeField, SplitHiddenDateTimeWidget, Textarea, TextInput, TimeField, ValidationError, forms, ) from django.forms.renderers import DjangoTemplates, get_default_renderer from django.forms.utils import ErrorList from django.http import QueryDict from django.template import Context, Template from django.test import SimpleTestCase from django.test.utils import override_settings from django.utils.datastructures import MultiValueDict from django.utils.safestring import mark_safe from . import jinja2_tests class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[("P", "Python"), ("J", "Java")], widget=RadioSelect) class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class PersonNew(Form): first_name = CharField(widget=TextInput(attrs={"id": "first_name_id"})) last_name = CharField() birthday = DateField() class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=CheckboxSelectMultiple, ) class MultiValueDictLike(dict): def getlist(self, key): return [self[key]] class FormsTestCase(SimpleTestCase): # A Form is a collection of Fields. It knows how to validate a set of data and it # knows how to render itself in a couple of default ways (e.g., an HTML table). # You can pass it data in __init__(), as a dictionary. def test_form(self): # Pass a dictionary to a Form's __init__(). p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"} ) self.assertTrue(p.is_bound) self.assertEqual(p.errors, {}) self.assertIsInstance(p.errors, dict) self.assertTrue(p.is_valid()) self.assertHTMLEqual(p.errors.as_ul(), "") self.assertEqual(p.errors.as_text(), "") self.assertEqual(p.cleaned_data["first_name"], "John") self.assertEqual(p.cleaned_data["last_name"], "Lennon") self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) self.assertHTMLEqual( str(p["first_name"]), '<input type="text" name="first_name" value="John" id="id_first_name" ' "required>", ) self.assertHTMLEqual( str(p["last_name"]), '<input type="text" name="last_name" value="Lennon" id="id_last_name" ' "required>", ) self.assertHTMLEqual( str(p["birthday"]), '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required>", ) msg = ( "Key 'nonexistentfield' not found in 'Person'. Choices are: birthday, " "first_name, last_name." ) with self.assertRaisesMessage(KeyError, msg): p["nonexistentfield"] form_output = [] for boundfield in p: form_output.append(str(boundfield)) self.assertHTMLEqual( "\n".join(form_output), '<input type="text" name="first_name" value="John" id="id_first_name" ' "required>" '<input type="text" name="last_name" value="Lennon" id="id_last_name" ' "required>" '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required>", ) form_output = [] for boundfield in p: form_output.append([boundfield.label, boundfield.data]) self.assertEqual( form_output, [ ["First name", "John"], ["Last name", "Lennon"], ["Birthday", "1940-10-9"], ], ) self.assertHTMLEqual( str(p), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" value="John" required id="id_first_name"></div><div>' '<label for="id_last_name">Last name:</label><input type="text" ' 'name="last_name" value="Lennon" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label><input type="text" ' 'name="birthday" value="1940-10-9" required id="id_birthday"></div>', ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" value="John" required id="id_first_name"></div><div>' '<label for="id_last_name">Last name:</label><input type="text" ' 'name="last_name" value="Lennon" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label><input type="text" ' 'name="birthday" value="1940-10-9" required id="id_birthday"></div>', ) def test_empty_dict(self): # Empty dictionaries are valid, too. p = Person({}) self.assertTrue(p.is_bound) self.assertEqual(p.errors["first_name"], ["This field is required."]) self.assertEqual(p.errors["last_name"], ["This field is required."]) self.assertEqual(p.errors["birthday"], ["This field is required."]) self.assertFalse(p.is_valid()) self.assertEqual(p.cleaned_data, {}) self.assertHTMLEqual( str(p), '<div><label for="id_first_name">First name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="first_name" required id="id_first_name"></div>' '<div><label for="id_last_name">Last name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="last_name" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="birthday" required id="id_birthday"></div>', ) self.assertHTMLEqual( p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td> <ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="birthday" id="id_birthday" required></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> <label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> <label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> <label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></li>""", ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="first_name" required id="id_first_name"></div>' '<div><label for="id_last_name">Last name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="last_name" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="birthday" required id="id_birthday"></div>', ) def test_empty_querydict_args(self): data = QueryDict() files = QueryDict() p = Person(data, files) self.assertIs(p.data, data) self.assertIs(p.files, files) def test_unbound_form(self): # If you don't pass any values to the Form's __init__(), or if you pass None, # the Form will be considered unbound and won't do any validation. Form.errors # will be an empty dictionary *but* Form.is_valid() will return False. p = Person() self.assertFalse(p.is_bound) self.assertEqual(p.errors, {}) self.assertFalse(p.is_valid()) with self.assertRaises(AttributeError): p.cleaned_data self.assertHTMLEqual( str(p), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" id="id_first_name" required></div><div><label ' 'for="id_last_name">Last name:</label><input type="text" name="last_name" ' 'id="id_last_name" required></div><div><label for="id_birthday">' 'Birthday:</label><input type="text" name="birthday" id="id_birthday" ' "required></div>", ) self.assertHTMLEqual( p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" id="id_birthday" required></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></li>""", ) self.assertHTMLEqual( p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" id="id_first_name" required></div><div><label ' 'for="id_last_name">Last name:</label><input type="text" name="last_name" ' 'id="id_last_name" required></div><div><label for="id_birthday">' 'Birthday:</label><input type="text" name="birthday" id="id_birthday" ' "required></div>", ) def test_unicode_values(self): # Unicode values are handled properly. p = Person( { "first_name": "John", "last_name": "\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111", "birthday": "1940-10-9", } ) self.assertHTMLEqual( p.as_table(), '<tr><th><label for="id_first_name">First name:</label></th><td>' '<input type="text" name="first_name" value="John" id="id_first_name" ' "required></td></tr>\n" '<tr><th><label for="id_last_name">Last name:</label>' '</th><td><input type="text" name="last_name" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111"' 'id="id_last_name" required></td></tr>\n' '<tr><th><label for="id_birthday">Birthday:</label></th><td>' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required></td></tr>", ) self.assertHTMLEqual( p.as_ul(), '<li><label for="id_first_name">First name:</label> ' '<input type="text" name="first_name" value="John" id="id_first_name" ' "required></li>\n" '<li><label for="id_last_name">Last name:</label> ' '<input type="text" name="last_name" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ' 'id="id_last_name" required></li>\n' '<li><label for="id_birthday">Birthday:</label> ' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required></li>", ) self.assertHTMLEqual( p.as_p(), '<p><label for="id_first_name">First name:</label> ' '<input type="text" name="first_name" value="John" id="id_first_name" ' "required></p>\n" '<p><label for="id_last_name">Last name:</label> ' '<input type="text" name="last_name" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ' 'id="id_last_name" required></p>\n' '<p><label for="id_birthday">Birthday:</label> ' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required></p>", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label>' '<input type="text" name="first_name" value="John" id="id_first_name" ' 'required></div><div><label for="id_last_name">Last name:</label>' '<input type="text" name="last_name"' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ' 'id="id_last_name" required></div><div><label for="id_birthday">' 'Birthday:</label><input type="text" name="birthday" value="1940-10-9" ' 'id="id_birthday" required></div>', ) p = Person({"last_name": "Lennon"}) self.assertEqual(p.errors["first_name"], ["This field is required."]) self.assertEqual(p.errors["birthday"], ["This field is required."]) self.assertFalse(p.is_valid()) self.assertEqual( p.errors, { "birthday": ["This field is required."], "first_name": ["This field is required."], }, ) self.assertEqual(p.cleaned_data, {"last_name": "Lennon"}) self.assertEqual(p["first_name"].errors, ["This field is required."]) self.assertHTMLEqual( p["first_name"].errors.as_ul(), '<ul class="errorlist"><li>This field is required.</li></ul>', ) self.assertEqual(p["first_name"].errors.as_text(), "* This field is required.") p = Person() self.assertHTMLEqual( str(p["first_name"]), '<input type="text" name="first_name" id="id_first_name" required>', ) self.assertHTMLEqual( str(p["last_name"]), '<input type="text" name="last_name" id="id_last_name" required>', ) self.assertHTMLEqual( str(p["birthday"]), '<input type="text" name="birthday" id="id_birthday" required>', ) def test_cleaned_data_only_fields(self): # cleaned_data will always *only* contain a key for fields defined in the # Form, even if you pass extra data when you define the Form. In this # example, we pass a bunch of extra fields to the form constructor, # but cleaned_data contains only the form's fields. data = { "first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9", "extra1": "hello", "extra2": "hello", } p = Person(data) self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data["first_name"], "John") self.assertEqual(p.cleaned_data["last_name"], "Lennon") self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) def test_optional_data(self): # cleaned_data will include a key and value for *all* fields defined in # the Form, even if the Form's data didn't include a value for fields # that are not required. In this example, the data dictionary doesn't # include a value for the "nick_name" field, but cleaned_data includes # it. For CharFields, it's set to the empty string. class OptionalPersonForm(Form): first_name = CharField() last_name = CharField() nick_name = CharField(required=False) data = {"first_name": "John", "last_name": "Lennon"} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["nick_name"], "") self.assertEqual(f.cleaned_data["first_name"], "John") self.assertEqual(f.cleaned_data["last_name"], "Lennon") # For DateFields, it's set to None. class OptionalPersonForm(Form): first_name = CharField() last_name = CharField() birth_date = DateField(required=False) data = {"first_name": "John", "last_name": "Lennon"} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) self.assertIsNone(f.cleaned_data["birth_date"]) self.assertEqual(f.cleaned_data["first_name"], "John") self.assertEqual(f.cleaned_data["last_name"], "Lennon") def test_auto_id(self): # "auto_id" tells the Form to add an "id" attribute to each form # element. If it's a string that contains '%s', Django will use that as # a format string into which the field's name will be inserted. It will # also put a <label> around the human-readable labels for a field. p = Person(auto_id="%s_id") self.assertHTMLEqual( p.as_table(), """<tr><th><label for="first_name_id">First name:</label></th><td> <input type="text" name="first_name" id="first_name_id" required></td></tr> <tr><th><label for="last_name_id">Last name:</label></th><td> <input type="text" name="last_name" id="last_name_id" required></td></tr> <tr><th><label for="birthday_id">Birthday:</label></th><td> <input type="text" name="birthday" id="birthday_id" required></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" required></li> <li><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" required></li> <li><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" required></li>""", ) self.assertHTMLEqual( p.as_p(), """<p><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" required></p> <p><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" required></p> <p><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" required></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="first_name_id">First name:</label><input type="text" ' 'name="first_name" id="first_name_id" required></div><div><label ' 'for="last_name_id">Last name:</label><input type="text" ' 'name="last_name" id="last_name_id" required></div><div><label ' 'for="birthday_id">Birthday:</label><input type="text" name="birthday" ' 'id="birthday_id" required></div>', ) def test_auto_id_true(self): # If auto_id is any True value whose str() does not contain '%s', the "id" # attribute will be the name of the field. p = Person(auto_id=True) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name">First name:</label> <input type="text" name="first_name" id="first_name" required></li> <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" required></li> <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" required></li>""", ) def test_auto_id_false(self): # If auto_id is any False value, an "id" attribute won't be output unless it # was manually entered. p = Person(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""", ) def test_id_on_field(self): # In this example, auto_id is False, but the "id" attribute for the "first_name" # field is given. Also note that field gets a <label>, while the others don't. p = PersonNew(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""", ) def test_auto_id_on_form_and_field(self): # If the "id" attribute is specified in the Form and auto_id is True, the "id" # attribute in the Form gets precedence. p = PersonNew(auto_id=True) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" required></li> <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" required></li> <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" required></li>""", ) def test_various_boolean_values(self): class SignupForm(Form): email = EmailField() get_spam = BooleanField() f = SignupForm(auto_id=False) self.assertHTMLEqual( str(f["email"]), '<input type="email" name="email" required>' ) self.assertHTMLEqual( str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>' ) f = SignupForm({"email": "[email protected]", "get_spam": True}, auto_id=False) self.assertHTMLEqual( str(f["email"]), '<input type="email" name="email" value="[email protected]" required>', ) self.assertHTMLEqual( str(f["get_spam"]), '<input checked type="checkbox" name="get_spam" required>', ) # 'True' or 'true' should be rendered without a value attribute f = SignupForm({"email": "[email protected]", "get_spam": "True"}, auto_id=False) self.assertHTMLEqual( str(f["get_spam"]), '<input checked type="checkbox" name="get_spam" required>', ) f = SignupForm({"email": "[email protected]", "get_spam": "true"}, auto_id=False) self.assertHTMLEqual( str(f["get_spam"]), '<input checked type="checkbox" name="get_spam" required>', ) # A value of 'False' or 'false' should be rendered unchecked f = SignupForm( {"email": "[email protected]", "get_spam": "False"}, auto_id=False ) self.assertHTMLEqual( str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>' ) f = SignupForm( {"email": "[email protected]", "get_spam": "false"}, auto_id=False ) self.assertHTMLEqual( str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>' ) # A value of '0' should be interpreted as a True value (#16820) f = SignupForm({"email": "[email protected]", "get_spam": "0"}) self.assertTrue(f.is_valid()) self.assertTrue(f.cleaned_data.get("get_spam")) def test_widget_output(self): # Any Field can have a Widget class passed to its constructor: class ContactForm(Form): subject = CharField() message = CharField(widget=Textarea) f = ContactForm(auto_id=False) self.assertHTMLEqual( str(f["subject"]), '<input type="text" name="subject" required>' ) self.assertHTMLEqual( str(f["message"]), '<textarea name="message" rows="10" cols="40" required></textarea>', ) # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output # widget type: self.assertHTMLEqual( f["subject"].as_textarea(), '<textarea name="subject" rows="10" cols="40" required></textarea>', ) self.assertHTMLEqual( f["message"].as_text(), '<input type="text" name="message" required>' ) self.assertHTMLEqual( f["message"].as_hidden(), '<input type="hidden" name="message">' ) # The 'widget' parameter to a Field can also be an instance: class ContactForm(Form): subject = CharField() message = CharField(widget=Textarea(attrs={"rows": 80, "cols": 20})) f = ContactForm(auto_id=False) self.assertHTMLEqual( str(f["message"]), '<textarea name="message" rows="80" cols="20" required></textarea>', ) # Instance-level attrs are *not* carried over to as_textarea(), as_text() and # as_hidden(): self.assertHTMLEqual( f["message"].as_text(), '<input type="text" name="message" required>' ) f = ContactForm({"subject": "Hello", "message": "I love you."}, auto_id=False) self.assertHTMLEqual( f["subject"].as_textarea(), '<textarea rows="10" cols="40" name="subject" required>Hello</textarea>', ) self.assertHTMLEqual( f["message"].as_text(), '<input type="text" name="message" value="I love you." required>', ) self.assertHTMLEqual( f["message"].as_hidden(), '<input type="hidden" name="message" value="I love you.">', ) def test_forms_with_choices(self): # For a form with a <select>, use ChoiceField: class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[("P", "Python"), ("J", "Java")]) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language"> <option value="P" selected>Python</option> <option value="J">Java</option> </select>""", ) # A subtlety: If one of the choices' value is the empty string and the form is # unbound, then the <option> for the empty-string choice will get selected. class FrameworkForm(Form): name = CharField() language = ChoiceField( choices=[("", "------"), ("P", "Python"), ("J", "Java")] ) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language" required> <option value="" selected>------</option> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) # You can specify widget attributes in the Widget constructor. class FrameworkForm(Form): name = CharField() language = ChoiceField( choices=[("P", "Python"), ("J", "Java")], widget=Select(attrs={"class": "foo"}), ) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P" selected>Python</option> <option value="J">Java</option> </select>""", ) # When passing a custom widget instance to ChoiceField, note that setting # 'choices' on the widget is meaningless. The widget will use the choices # defined on the Field, not the ones defined on the Widget. class FrameworkForm(Form): name = CharField() language = ChoiceField( choices=[("P", "Python"), ("J", "Java")], widget=Select( choices=[("R", "Ruby"), ("P", "Perl")], attrs={"class": "foo"} ), ) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P" selected>Python</option> <option value="J">Java</option> </select>""", ) # You can set a ChoiceField's choices after the fact. class FrameworkForm(Form): name = CharField() language = ChoiceField() f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language"> </select>""", ) f.fields["language"].choices = [("P", "Python"), ("J", "Java")] self.assertHTMLEqual( str(f["language"]), """<select name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) def test_forms_with_radio(self): # Add widget=RadioSelect to use that widget with a ChoiceField. f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<div> <div><label><input type="radio" name="language" value="P" required> Python</label></div> <div><label><input type="radio" name="language" value="J" required> Java</label></div> </div>""", ) self.assertHTMLEqual( f.as_table(), """<tr><th>Name:</th><td><input type="text" name="name" required></td></tr> <tr><th>Language:</th><td><div> <div><label><input type="radio" name="language" value="P" required> Python</label></div> <div><label><input type="radio" name="language" value="J" required> Java</label></div> </div></td></tr>""", ) self.assertHTMLEqual( f.as_ul(), """<li>Name: <input type="text" name="name" required></li> <li>Language: <div> <div><label><input type="radio" name="language" value="P" required> Python</label></div> <div><label><input type="radio" name="language" value="J" required> Java</label></div> </div></li>""", ) # Need an auto_id to generate legend. self.assertHTMLEqual( f.render(f.template_name_div), '<div> Name: <input type="text" name="name" required></div><div><fieldset>' 'Language:<div><div><label><input type="radio" name="language" value="P" ' 'required> Python</label></div><div><label><input type="radio" ' 'name="language" value="J" required> Java</label></div></div></fieldset>' "</div>", ) # Regarding auto_id and <label>, RadioSelect is a special case. Each # radio button gets a distinct ID, formed by appending an underscore # plus the button's zero-based index. f = FrameworkForm(auto_id="id_%s") self.assertHTMLEqual( str(f["language"]), """ <div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div>""", ) # When RadioSelect is used with auto_id, and the whole form is printed # using either as_table() or as_ul(), the label for the RadioSelect # will **not** point to the ID of the *first* radio button to improve # accessibility for screen reader users. self.assertHTMLEqual( f.as_table(), """ <tr><th><label for="id_name">Name:</label></th><td> <input type="text" name="name" id="id_name" required></td></tr> <tr><th><label>Language:</label></th><td><div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div></td></tr>""", ) self.assertHTMLEqual( f.as_ul(), """ <li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li> <li><label>Language:</label> <div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div></li> """, ) self.assertHTMLEqual( f.as_p(), """ <p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></p> <p><label>Language:</label> <div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div></p> """, ) self.assertHTMLEqual( f.render(f.template_name_div), '<div><label for="id_name">Name:</label><input type="text" name="name" ' 'required id="id_name"></div><div><fieldset><legend>Language:</legend>' '<div id="id_language"><div><label for="id_language_0"><input ' 'type="radio" name="language" value="P" required id="id_language_0">' 'Python</label></div><div><label for="id_language_1"><input type="radio" ' 'name="language" value="J" required id="id_language_1">Java</label></div>' "</div></fieldset></div>", ) def test_form_with_iterable_boundfield(self): class BeatleForm(Form): name = ChoiceField( choices=[ ("john", "John"), ("paul", "Paul"), ("george", "George"), ("ringo", "Ringo"), ], widget=RadioSelect, ) f = BeatleForm(auto_id=False) self.assertHTMLEqual( "\n".join(str(bf) for bf in f["name"]), '<label><input type="radio" name="name" value="john" required> John</label>' '<label><input type="radio" name="name" value="paul" required> Paul</label>' '<label><input type="radio" name="name" value="george" required> George' "</label>" '<label><input type="radio" name="name" value="ringo" required> Ringo' "</label>", ) self.assertHTMLEqual( "\n".join("<div>%s</div>" % bf for bf in f["name"]), """ <div><label> <input type="radio" name="name" value="john" required> John</label></div> <div><label> <input type="radio" name="name" value="paul" required> Paul</label></div> <div><label> <input type="radio" name="name" value="george" required> George </label></div> <div><label> <input type="radio" name="name" value="ringo" required> Ringo</label></div> """, ) def test_form_with_iterable_boundfield_id(self): class BeatleForm(Form): name = ChoiceField( choices=[ ("john", "John"), ("paul", "Paul"), ("george", "George"), ("ringo", "Ringo"), ], widget=RadioSelect, ) fields = list(BeatleForm()["name"]) self.assertEqual(len(fields), 4) self.assertEqual(fields[0].id_for_label, "id_name_0") self.assertEqual(fields[0].choice_label, "John") self.assertHTMLEqual( fields[0].tag(), '<input type="radio" name="name" value="john" id="id_name_0" required>', ) self.assertHTMLEqual( str(fields[0]), '<label for="id_name_0"><input type="radio" name="name" ' 'value="john" id="id_name_0" required> John</label>', ) self.assertEqual(fields[1].id_for_label, "id_name_1") self.assertEqual(fields[1].choice_label, "Paul") self.assertHTMLEqual( fields[1].tag(), '<input type="radio" name="name" value="paul" id="id_name_1" required>', ) self.assertHTMLEqual( str(fields[1]), '<label for="id_name_1"><input type="radio" name="name" ' 'value="paul" id="id_name_1" required> Paul</label>', ) def test_iterable_boundfield_select(self): class BeatleForm(Form): name = ChoiceField( choices=[ ("john", "John"), ("paul", "Paul"), ("george", "George"), ("ringo", "Ringo"), ] ) fields = list(BeatleForm(auto_id=False)["name"]) self.assertEqual(len(fields), 4) self.assertIsNone(fields[0].id_for_label) self.assertEqual(fields[0].choice_label, "John") self.assertHTMLEqual(fields[0].tag(), '<option value="john">John</option>') self.assertHTMLEqual(str(fields[0]), '<option value="john">John</option>') def test_form_with_noniterable_boundfield(self): # You can iterate over any BoundField, not just those with widget=RadioSelect. class BeatleForm(Form): name = CharField() f = BeatleForm(auto_id=False) self.assertHTMLEqual( "\n".join(str(bf) for bf in f["name"]), '<input type="text" name="name" required>', ) def test_boundfield_slice(self): class BeatleForm(Form): name = ChoiceField( choices=[ ("john", "John"), ("paul", "Paul"), ("george", "George"), ("ringo", "Ringo"), ], widget=RadioSelect, ) f = BeatleForm() bf = f["name"] self.assertEqual( [str(item) for item in bf[1:]], [str(bf[1]), str(bf[2]), str(bf[3])], ) def test_boundfield_invalid_index(self): class TestForm(Form): name = ChoiceField(choices=[]) field = TestForm()["name"] msg = "BoundField indices must be integers or slices, not str." with self.assertRaisesMessage(TypeError, msg): field["foo"] def test_boundfield_bool(self): """BoundField without any choices (subwidgets) evaluates to True.""" class TestForm(Form): name = ChoiceField(choices=[]) self.assertIs(bool(TestForm()["name"]), True) def test_forms_with_multiple_choice(self): # MultipleChoiceField is a special case, as its data is required to be a list: class SongForm(Form): name = CharField() composers = MultipleChoiceField() f = SongForm(auto_id=False) self.assertHTMLEqual( str(f["composers"]), """<select multiple name="composers" required> </select>""", ) class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")] ) f = SongForm(auto_id=False) self.assertHTMLEqual( str(f["composers"]), """<select multiple name="composers" required> <option value="J">John Lennon</option> <option value="P">Paul McCartney</option> </select>""", ) f = SongForm({"name": "Yesterday", "composers": ["P"]}, auto_id=False) self.assertHTMLEqual( str(f["name"]), '<input type="text" name="name" value="Yesterday" required>' ) self.assertHTMLEqual( str(f["composers"]), """<select multiple name="composers" required> <option value="J">John Lennon</option> <option value="P" selected>Paul McCartney</option> </select>""", ) f = SongForm() self.assertHTMLEqual( f.as_table(), '<tr><th><label for="id_name">Name:</label></th>' '<td><input type="text" name="name" required id="id_name"></td>' '</tr><tr><th><label for="id_composers">Composers:</label></th>' '<td><select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option>' '<option value="P">Paul McCartney</option>' "</select></td></tr>", ) self.assertHTMLEqual( f.as_ul(), '<li><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></li>' '<li><label for="id_composers">Composers:</label>' '<select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option>' '<option value="P">Paul McCartney</option>' "</select></li>", ) self.assertHTMLEqual( f.as_p(), '<p><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></p>' '<p><label for="id_composers">Composers:</label>' '<select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option>' '<option value="P">Paul McCartney</option>' "</select></p>", ) self.assertHTMLEqual( f.render(f.template_name_div), '<div><label for="id_name">Name:</label><input type="text" name="name" ' 'required id="id_name"></div><div><label for="id_composers">Composers:' '</label><select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option><option value="P">Paul McCartney' "</option></select></div>", ) def test_multiple_checkbox_render(self): f = SongForm() self.assertHTMLEqual( f.as_table(), '<tr><th><label for="id_name">Name:</label></th><td>' '<input type="text" name="name" required id="id_name"></td></tr>' '<tr><th><label>Composers:</label></th><td><div id="id_composers">' '<div><label for="id_composers_0">' '<input type="checkbox" name="composers" value="J" ' 'id="id_composers_0">John Lennon</label></div>' '<div><label for="id_composers_1">' '<input type="checkbox" name="composers" value="P" ' 'id="id_composers_1">Paul McCartney</label></div>' "</div></td></tr>", ) self.assertHTMLEqual( f.as_ul(), '<li><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></li>' '<li><label>Composers:</label><div id="id_composers">' '<div><label for="id_composers_0">' '<input type="checkbox" name="composers" value="J" ' 'id="id_composers_0">John Lennon</label></div>' '<div><label for="id_composers_1">' '<input type="checkbox" name="composers" value="P" ' 'id="id_composers_1">Paul McCartney</label></div>' "</div></li>", ) self.assertHTMLEqual( f.as_p(), '<p><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></p>' '<p><label>Composers:</label><div id="id_composers">' '<div><label for="id_composers_0">' '<input type="checkbox" name="composers" value="J" ' 'id="id_composers_0">John Lennon</label></div>' '<div><label for="id_composers_1">' '<input type="checkbox" name="composers" value="P" ' 'id="id_composers_1">Paul McCartney</label></div>' "</div></p>", ) self.assertHTMLEqual( f.render(f.template_name_div), '<div><label for="id_name">Name:</label><input type="text" name="name" ' 'required id="id_name"></div><div><fieldset><legend>Composers:</legend>' '<div id="id_composers"><div><label for="id_composers_0"><input ' 'type="checkbox" name="composers" value="J" id="id_composers_0">' 'John Lennon</label></div><div><label for="id_composers_1"><input ' 'type="checkbox" name="composers" value="P" id="id_composers_1">' "Paul McCartney</label></div></div></fieldset></div>", ) def test_form_with_disabled_fields(self): class PersonForm(Form): name = CharField() birthday = DateField(disabled=True) class PersonFormFieldInitial(Form): name = CharField() birthday = DateField(disabled=True, initial=datetime.date(1974, 8, 16)) # Disabled fields are generally not transmitted by user agents. # The value from the form's initial data is used. f1 = PersonForm( {"name": "John Doe"}, initial={"birthday": datetime.date(1974, 8, 16)} ) f2 = PersonFormFieldInitial({"name": "John Doe"}) for form in (f1, f2): self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data, {"birthday": datetime.date(1974, 8, 16), "name": "John Doe"}, ) # Values provided in the form's data are ignored. data = {"name": "John Doe", "birthday": "1984-11-10"} f1 = PersonForm(data, initial={"birthday": datetime.date(1974, 8, 16)}) f2 = PersonFormFieldInitial(data) for form in (f1, f2): self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data, {"birthday": datetime.date(1974, 8, 16), "name": "John Doe"}, ) # Initial data remains present on invalid forms. data = {} f1 = PersonForm(data, initial={"birthday": datetime.date(1974, 8, 16)}) f2 = PersonFormFieldInitial(data) for form in (f1, f2): self.assertFalse(form.is_valid()) self.assertEqual(form["birthday"].value(), datetime.date(1974, 8, 16)) def test_hidden_data(self): class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")] ) # MultipleChoiceField rendered as_hidden() is a special case. Because it can # have multiple values, its as_hidden() renders multiple <input type="hidden"> # tags. f = SongForm({"name": "Yesterday", "composers": ["P"]}, auto_id=False) self.assertHTMLEqual( f["composers"].as_hidden(), '<input type="hidden" name="composers" value="P">', ) f = SongForm({"name": "From Me To You", "composers": ["P", "J"]}, auto_id=False) self.assertHTMLEqual( f["composers"].as_hidden(), """<input type="hidden" name="composers" value="P"> <input type="hidden" name="composers" value="J">""", ) # DateTimeField rendered as_hidden() is special too class MessageForm(Form): when = SplitDateTimeField() f = MessageForm({"when_0": "1992-01-01", "when_1": "01:01"}) self.assertTrue(f.is_valid()) self.assertHTMLEqual( str(f["when"]), '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" ' "required>" '<input type="text" name="when_1" value="01:01" id="id_when_1" required>', ) self.assertHTMLEqual( f["when"].as_hidden(), '<input type="hidden" name="when_0" value="1992-01-01" id="id_when_0">' '<input type="hidden" name="when_1" value="01:01" id="id_when_1">', ) def test_multiple_choice_checkbox(self): # MultipleChoiceField can also be used with the CheckboxSelectMultiple widget. f = SongForm(auto_id=False) self.assertHTMLEqual( str(f["composers"]), """ <div> <div><label><input type="checkbox" name="composers" value="J"> John Lennon</label></div> <div><label><input type="checkbox" name="composers" value="P"> Paul McCartney</label></div> </div> """, ) f = SongForm({"composers": ["J"]}, auto_id=False) self.assertHTMLEqual( str(f["composers"]), """ <div> <div><label><input checked type="checkbox" name="composers" value="J"> John Lennon</label></div> <div><label><input type="checkbox" name="composers" value="P"> Paul McCartney</label></div> </div> """, ) f = SongForm({"composers": ["J", "P"]}, auto_id=False) self.assertHTMLEqual( str(f["composers"]), """ <div> <div><label><input checked type="checkbox" name="composers" value="J"> John Lennon</label></div> <div><label><input checked type="checkbox" name="composers" value="P"> Paul McCartney</label></div> </div> """, ) def test_checkbox_auto_id(self): # Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox # gets a distinct ID, formed by appending an underscore plus the checkbox's # zero-based index. class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=CheckboxSelectMultiple, ) f = SongForm(auto_id="%s_id") self.assertHTMLEqual( str(f["composers"]), """ <div id="composers_id"> <div><label for="composers_id_0"> <input type="checkbox" name="composers" value="J" id="composers_id_0"> John Lennon</label></div> <div><label for="composers_id_1"> <input type="checkbox" name="composers" value="P" id="composers_id_1"> Paul McCartney</label></div> </div> """, ) def test_multiple_choice_list_data(self): # Data for a MultipleChoiceField should be a list. QueryDict and # MultiValueDict conveniently work with this. class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=CheckboxSelectMultiple, ) data = {"name": "Yesterday", "composers": ["J", "P"]} f = SongForm(data) self.assertEqual(f.errors, {}) data = QueryDict("name=Yesterday&composers=J&composers=P") f = SongForm(data) self.assertEqual(f.errors, {}) data = MultiValueDict({"name": ["Yesterday"], "composers": ["J", "P"]}) f = SongForm(data) self.assertEqual(f.errors, {}) # SelectMultiple uses ducktyping so that MultiValueDictLike.getlist() # is called. f = SongForm(MultiValueDictLike({"name": "Yesterday", "composers": "J"})) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J"]) def test_multiple_hidden(self): class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=CheckboxSelectMultiple, ) # The MultipleHiddenInput widget renders multiple values as hidden fields. class SongFormHidden(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=MultipleHiddenInput, ) f = SongFormHidden( MultiValueDict({"name": ["Yesterday"], "composers": ["J", "P"]}), auto_id=False, ) self.assertHTMLEqual( f.as_ul(), """<li>Name: <input type="text" name="name" value="Yesterday" required> <input type="hidden" name="composers" value="J"> <input type="hidden" name="composers" value="P"></li>""", ) # When using CheckboxSelectMultiple, the framework expects a list of input and # returns a list of input. f = SongForm({"name": "Yesterday"}, auto_id=False) self.assertEqual(f.errors["composers"], ["This field is required."]) f = SongForm({"name": "Yesterday", "composers": ["J"]}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J"]) self.assertEqual(f.cleaned_data["name"], "Yesterday") f = SongForm({"name": "Yesterday", "composers": ["J", "P"]}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J", "P"]) self.assertEqual(f.cleaned_data["name"], "Yesterday") # MultipleHiddenInput uses ducktyping so that # MultiValueDictLike.getlist() is called. f = SongForm(MultiValueDictLike({"name": "Yesterday", "composers": "J"})) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J"]) def test_escaping(self): # Validation errors are HTML-escaped when output as HTML. class EscapingForm(Form): special_name = CharField(label="<em>Special</em> Field") special_safe_name = CharField(label=mark_safe("<em>Special</em> Field")) def clean_special_name(self): raise ValidationError( "Something's wrong with '%s'" % self.cleaned_data["special_name"] ) def clean_special_safe_name(self): raise ValidationError( mark_safe( "'<b>%s</b>' is a safe string" % self.cleaned_data["special_safe_name"] ) ) f = EscapingForm( { "special_name": "Nothing to escape", "special_safe_name": "Nothing to escape", }, auto_id=False, ) self.assertHTMLEqual( f.as_table(), """ <tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td> <ul class="errorlist"> <li>Something&#x27;s wrong with &#x27;Nothing to escape&#x27;</li></ul> <input type="text" name="special_name" value="Nothing to escape" required> </td></tr> <tr><th><em>Special</em> Field:</th><td> <ul class="errorlist"> <li>'<b>Nothing to escape</b>' is a safe string</li></ul> <input type="text" name="special_safe_name" value="Nothing to escape" required></td></tr> """, ) f = EscapingForm( { "special_name": "Should escape < & > and <script>alert('xss')</script>", "special_safe_name": "<i>Do not escape</i>", }, auto_id=False, ) self.assertHTMLEqual( f.as_table(), "<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>" '<ul class="errorlist"><li>' "Something&#x27;s wrong with &#x27;Should escape &lt; &amp; &gt; and " "&lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;&#x27;</li></ul>" '<input type="text" name="special_name" value="Should escape &lt; &amp; ' '&gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;" required>' "</td></tr>" "<tr><th><em>Special</em> Field:</th><td>" '<ul class="errorlist">' "<li>'<b><i>Do not escape</i></b>' is a safe string</li></ul>" '<input type="text" name="special_safe_name" ' 'value="&lt;i&gt;Do not escape&lt;/i&gt;" required></td></tr>', ) def test_validating_multiple_fields(self): # There are a couple of ways to do multiple-field validation. If you # want the validation message to be associated with a particular field, # implement the clean_XXX() method on the Form, where XXX is the field # name. As in Field.clean(), the clean_XXX() method should return the # cleaned value. In the clean_XXX() method, you have access to # self.cleaned_data, which is a dictionary of all the data that has # been cleaned *so far*, in order by the fields, including the current # field (e.g., the field XXX if you're in clean_XXX()). class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean_password2(self): if ( self.cleaned_data.get("password1") and self.cleaned_data.get("password2") and self.cleaned_data["password1"] != self.cleaned_data["password2"] ): raise ValidationError("Please make sure your passwords match.") return self.cleaned_data["password2"] f = UserRegistration(auto_id=False) self.assertEqual(f.errors, {}) f = UserRegistration({}, auto_id=False) self.assertEqual(f.errors["username"], ["This field is required."]) self.assertEqual(f.errors["password1"], ["This field is required."]) self.assertEqual(f.errors["password2"], ["This field is required."]) f = UserRegistration( {"username": "adrian", "password1": "foo", "password2": "bar"}, auto_id=False, ) self.assertEqual( f.errors["password2"], ["Please make sure your passwords match."] ) f = UserRegistration( {"username": "adrian", "password1": "foo", "password2": "foo"}, auto_id=False, ) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["username"], "adrian") self.assertEqual(f.cleaned_data["password1"], "foo") self.assertEqual(f.cleaned_data["password2"], "foo") # Another way of doing multiple-field validation is by implementing the # Form's clean() method. Usually ValidationError raised by that method # will not be associated with a particular field and will have a # special-case association with the field named '__all__'. It's # possible to associate the errors to particular field with the # Form.add_error() method or by passing a dictionary that maps each # field to one or more errors. # # Note that in Form.clean(), you have access to self.cleaned_data, a # dictionary of all the fields/values that have *not* raised a # ValidationError. Also note Form.clean() is required to return a # dictionary of all clean data. class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean(self): # Test raising a ValidationError as NON_FIELD_ERRORS. if ( self.cleaned_data.get("password1") and self.cleaned_data.get("password2") and self.cleaned_data["password1"] != self.cleaned_data["password2"] ): raise ValidationError("Please make sure your passwords match.") # Test raising ValidationError that targets multiple fields. errors = {} if self.cleaned_data.get("password1") == "FORBIDDEN_VALUE": errors["password1"] = "Forbidden value." if self.cleaned_data.get("password2") == "FORBIDDEN_VALUE": errors["password2"] = ["Forbidden value."] if errors: raise ValidationError(errors) # Test Form.add_error() if self.cleaned_data.get("password1") == "FORBIDDEN_VALUE2": self.add_error(None, "Non-field error 1.") self.add_error("password1", "Forbidden value 2.") if self.cleaned_data.get("password2") == "FORBIDDEN_VALUE2": self.add_error("password2", "Forbidden value 2.") raise ValidationError("Non-field error 2.") return self.cleaned_data f = UserRegistration(auto_id=False) self.assertEqual(f.errors, {}) f = UserRegistration({}, auto_id=False) self.assertHTMLEqual( f.as_table(), """<tr><th>Username:</th><td> <ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="username" maxlength="10" required></td></tr> <tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul> <input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul> <input type="password" name="password2" required></td></tr>""", ) self.assertEqual(f.errors["username"], ["This field is required."]) self.assertEqual(f.errors["password1"], ["This field is required."]) self.assertEqual(f.errors["password2"], ["This field is required."]) f = UserRegistration( {"username": "adrian", "password1": "foo", "password2": "bar"}, auto_id=False, ) self.assertEqual( f.errors["__all__"], ["Please make sure your passwords match."] ) self.assertHTMLEqual( f.as_table(), """ <tr><td colspan="2"> <ul class="errorlist nonfield"> <li>Please make sure your passwords match.</li></ul></td></tr> <tr><th>Username:</th><td> <input type="text" name="username" value="adrian" maxlength="10" required> </td></tr> <tr><th>Password1:</th><td> <input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td> <input type="password" name="password2" required></td></tr> """, ) self.assertHTMLEqual( f.as_ul(), """ <li><ul class="errorlist nonfield"> <li>Please make sure your passwords match.</li></ul></li> <li>Username: <input type="text" name="username" value="adrian" maxlength="10" required> </li> <li>Password1: <input type="password" name="password1" required></li> <li>Password2: <input type="password" name="password2" required></li> """, ) self.assertHTMLEqual( f.render(f.template_name_div), '<ul class="errorlist nonfield"><li>Please make sure your passwords match.' '</li></ul><div>Username: <input type="text" name="username" ' 'value="adrian" maxlength="10" required></div><div>Password1: <input ' 'type="password" name="password1" required></div><div>Password2: <input ' 'type="password" name="password2" required></div>', ) f = UserRegistration( {"username": "adrian", "password1": "foo", "password2": "foo"}, auto_id=False, ) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["username"], "adrian") self.assertEqual(f.cleaned_data["password1"], "foo") self.assertEqual(f.cleaned_data["password2"], "foo") f = UserRegistration( { "username": "adrian", "password1": "FORBIDDEN_VALUE", "password2": "FORBIDDEN_VALUE", }, auto_id=False, ) self.assertEqual(f.errors["password1"], ["Forbidden value."]) self.assertEqual(f.errors["password2"], ["Forbidden value."]) f = UserRegistration( { "username": "adrian", "password1": "FORBIDDEN_VALUE2", "password2": "FORBIDDEN_VALUE2", }, auto_id=False, ) self.assertEqual( f.errors["__all__"], ["Non-field error 1.", "Non-field error 2."] ) self.assertEqual(f.errors["password1"], ["Forbidden value 2."]) self.assertEqual(f.errors["password2"], ["Forbidden value 2."]) with self.assertRaisesMessage(ValueError, "has no field named"): f.add_error("missing_field", "Some error.") def test_update_error_dict(self): class CodeForm(Form): code = CharField(max_length=10) def clean(self): try: raise ValidationError({"code": [ValidationError("Code error 1.")]}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError({"code": [ValidationError("Code error 2.")]}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError({"code": forms.ErrorList(["Code error 3."])}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError("Non-field error 1.") except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError([ValidationError("Non-field error 2.")]) except ValidationError as e: self._errors = e.update_error_dict(self._errors) # The newly added list of errors is an instance of ErrorList. for field, error_list in self._errors.items(): if not isinstance(error_list, self.error_class): self._errors[field] = self.error_class(error_list) form = CodeForm({"code": "hello"}) # Trigger validation. self.assertFalse(form.is_valid()) # update_error_dict didn't lose track of the ErrorDict type. self.assertIsInstance(form._errors, forms.ErrorDict) self.assertEqual( dict(form.errors), { "code": ["Code error 1.", "Code error 2.", "Code error 3."], NON_FIELD_ERRORS: ["Non-field error 1.", "Non-field error 2."], }, ) def test_has_error(self): class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput, min_length=5) password2 = CharField(widget=PasswordInput) def clean(self): if ( self.cleaned_data.get("password1") and self.cleaned_data.get("password2") and self.cleaned_data["password1"] != self.cleaned_data["password2"] ): raise ValidationError( "Please make sure your passwords match.", code="password_mismatch", ) f = UserRegistration(data={}) self.assertTrue(f.has_error("password1")) self.assertTrue(f.has_error("password1", "required")) self.assertFalse(f.has_error("password1", "anything")) f = UserRegistration(data={"password1": "Hi", "password2": "Hi"}) self.assertTrue(f.has_error("password1")) self.assertTrue(f.has_error("password1", "min_length")) self.assertFalse(f.has_error("password1", "anything")) self.assertFalse(f.has_error("password2")) self.assertFalse(f.has_error("password2", "anything")) f = UserRegistration(data={"password1": "Bonjour", "password2": "Hello"}) self.assertFalse(f.has_error("password1")) self.assertFalse(f.has_error("password1", "required")) self.assertTrue(f.has_error(NON_FIELD_ERRORS)) self.assertTrue(f.has_error(NON_FIELD_ERRORS, "password_mismatch")) self.assertFalse(f.has_error(NON_FIELD_ERRORS, "anything")) def test_html_output_with_hidden_input_field_errors(self): class TestForm(Form): hidden_input = CharField(widget=HiddenInput) def clean(self): self.add_error(None, "Form error") f = TestForm(data={}) error_dict = { "hidden_input": ["This field is required."], "__all__": ["Form error"], } self.assertEqual(f.errors, error_dict) f.as_table() self.assertEqual(f.errors, error_dict) self.assertHTMLEqual( f.as_table(), '<tr><td colspan="2"><ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<input type="hidden" name="hidden_input" id="id_hidden_input"></td></tr>', ) self.assertHTMLEqual( f.as_ul(), '<li><ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<input type="hidden" name="hidden_input" id="id_hidden_input"></li>', ) self.assertHTMLEqual( f.as_p(), '<ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<p><input type="hidden" name="hidden_input" id="id_hidden_input"></p>', ) self.assertHTMLEqual( f.render(f.template_name_div), '<ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<div><input type="hidden" name="hidden_input" id="id_hidden_input"></div>', ) def test_dynamic_construction(self): # It's possible to construct a Form dynamically by adding to the self.fields # dictionary in __init__(). Don't forget to call Form.__init__() within the # subclass' __init__(). class Person(Form): first_name = CharField() last_name = CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["birthday"] = DateField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_table(), """ <tr><th>First name:</th><td> <input type="text" name="first_name" required></td></tr> <tr><th>Last name:</th><td> <input type="text" name="last_name" required></td></tr> <tr><th>Birthday:</th><td> <input type="text" name="birthday" required></td></tr> """, ) # Instances of a dynamic Form do not persist fields from one Form instance to # the next. class MyForm(Form): def __init__(self, data=None, auto_id=False, field_list=[]): Form.__init__(self, data, auto_id=auto_id) for field in field_list: self.fields[field[0]] = field[1] field_list = [("field1", CharField()), ("field2", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr> """, ) field_list = [("field3", CharField()), ("field4", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr> """, ) class MyForm(Form): default_field_1 = CharField() default_field_2 = CharField() def __init__(self, data=None, auto_id=False, field_list=[]): Form.__init__(self, data, auto_id=auto_id) for field in field_list: self.fields[field[0]] = field[1] field_list = [("field1", CharField()), ("field2", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Default field 1:</th><td> <input type="text" name="default_field_1" required></td></tr> <tr><th>Default field 2:</th><td> <input type="text" name="default_field_2" required></td></tr> <tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr> """, ) field_list = [("field3", CharField()), ("field4", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Default field 1:</th><td> <input type="text" name="default_field_1" required></td></tr> <tr><th>Default field 2:</th><td> <input type="text" name="default_field_2" required></td></tr> <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr> """, ) # Similarly, changes to field attributes do not persist from one Form instance # to the next. class Person(Form): first_name = CharField(required=False) last_name = CharField(required=False) def __init__(self, names_required=False, *args, **kwargs): super().__init__(*args, **kwargs) if names_required: self.fields["first_name"].required = True self.fields["first_name"].widget.attrs["class"] = "required" self.fields["last_name"].required = True self.fields["last_name"].widget.attrs["class"] = "required" f = Person(names_required=False) self.assertEqual( f["first_name"].field.required, f["last_name"].field.required, (False, False), ) self.assertEqual( f["first_name"].field.widget.attrs, f["last_name"].field.widget.attrs, ({}, {}), ) f = Person(names_required=True) self.assertEqual( f["first_name"].field.required, f["last_name"].field.required, (True, True) ) self.assertEqual( f["first_name"].field.widget.attrs, f["last_name"].field.widget.attrs, ({"class": "reuired"}, {"class": "required"}), ) f = Person(names_required=False) self.assertEqual( f["first_name"].field.required, f["last_name"].field.required, (False, False), ) self.assertEqual( f["first_name"].field.widget.attrs, f["last_name"].field.widget.attrs, ({}, {}), ) class Person(Form): first_name = CharField(max_length=30) last_name = CharField(max_length=30) def __init__(self, name_max_length=None, *args, **kwargs): super().__init__(*args, **kwargs) if name_max_length: self.fields["first_name"].max_length = name_max_length self.fields["last_name"].max_length = name_max_length f = Person(name_max_length=None) self.assertEqual( f["first_name"].field.max_length, f["last_name"].field.max_length, (30, 30) ) f = Person(name_max_length=20) self.assertEqual( f["first_name"].field.max_length, f["last_name"].field.max_length, (20, 20) ) f = Person(name_max_length=None) self.assertEqual( f["first_name"].field.max_length, f["last_name"].field.max_length, (30, 30) ) # Similarly, choices do not persist from one Form instance to the next. # Refs #15127. class Person(Form): first_name = CharField(required=False) last_name = CharField(required=False) gender = ChoiceField(choices=(("f", "Female"), ("m", "Male"))) def __init__(self, allow_unspec_gender=False, *args, **kwargs): super().__init__(*args, **kwargs) if allow_unspec_gender: self.fields["gender"].choices += (("u", "Unspecified"),) f = Person() self.assertEqual(f["gender"].field.choices, [("f", "Female"), ("m", "Male")]) f = Person(allow_unspec_gender=True) self.assertEqual( f["gender"].field.choices, [("f", "Female"), ("m", "Male"), ("u", "Unspecified")], ) f = Person() self.assertEqual(f["gender"].field.choices, [("f", "Female"), ("m", "Male")]) def test_validators_independence(self): """ The list of form field validators can be modified without polluting other forms. """ class MyForm(Form): myfield = CharField(max_length=25) f1 = MyForm() f2 = MyForm() f1.fields["myfield"].validators[0] = MaxValueValidator(12) self.assertNotEqual( f1.fields["myfield"].validators[0], f2.fields["myfield"].validators[0] ) def test_hidden_widget(self): # HiddenInput widgets are displayed differently in the as_table(), as_ul()) # and as_p() output of a Form -- their verbose names are not displayed, and a # separate row is not displayed. They're displayed in the last row of the # form, directly after that row's form element. class Person(Form): first_name = CharField() last_name = CharField() hidden_text = CharField(widget=HiddenInput) birthday = DateField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_table(), """ <tr><th>First name:</th><td><input type="text" name="first_name" required> </td></tr> <tr><th>Last name:</th><td><input type="text" name="last_name" required> </td></tr> <tr><th>Birthday:</th> <td><input type="text" name="birthday" required> <input type="hidden" name="hidden_text"></td></tr> """, ) self.assertHTMLEqual( p.as_ul(), """ <li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required> <input type="hidden" name="hidden_text"></li> """, ) self.assertHTMLEqual( p.as_p(), """ <p>First name: <input type="text" name="first_name" required></p> <p>Last name: <input type="text" name="last_name" required></p> <p>Birthday: <input type="text" name="birthday" required> <input type="hidden" name="hidden_text"></p> """, ) self.assertHTMLEqual( p.as_div(), '<div>First name: <input type="text" name="first_name" required></div>' '<div>Last name: <input type="text" name="last_name" required></div><div>' 'Birthday: <input type="text" name="birthday" required><input ' 'type="hidden" name="hidden_text"></div>', ) # With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label. p = Person(auto_id="id_%s") self.assertHTMLEqual( p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></li>""", ) self.assertHTMLEqual( p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" id="id_first_name" required></div><div><label ' 'for="id_last_name">Last name:</label><input type="text" name="last_name" ' 'id="id_last_name" required></div><div><label for="id_birthday">Birthday:' '</label><input type="text" name="birthday" id="id_birthday" required>' '<input type="hidden" name="hidden_text" id="id_hidden_text"></div>', ) # If a field with a HiddenInput has errors, the as_table() and as_ul() output # will include the error message(s) with the text "(Hidden field [fieldname]) " # prepended. This message is displayed at the top of the output, regardless of # its field's order in the form. p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"}, auto_id=False, ) self.assertHTMLEqual( p.as_table(), """ <tr><td colspan="2"> <ul class="errorlist nonfield"><li> (Hidden field hidden_text) This field is required.</li></ul></td></tr> <tr><th>First name:</th><td> <input type="text" name="first_name" value="John" required></td></tr> <tr><th>Last name:</th><td> <input type="text" name="last_name" value="Lennon" required></td></tr> <tr><th>Birthday:</th><td> <input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></td></tr> """, ) self.assertHTMLEqual( p.as_ul(), """ <li><ul class="errorlist nonfield"><li> (Hidden field hidden_text) This field is required.</li></ul></li> <li>First name: <input type="text" name="first_name" value="John" required> </li> <li>Last name: <input type="text" name="last_name" value="Lennon" required> </li> <li>Birthday: <input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></li> """, ) self.assertHTMLEqual( p.as_p(), """ <ul class="errorlist nonfield"><li> (Hidden field hidden_text) This field is required.</li></ul> <p>First name: <input type="text" name="first_name" value="John" required> </p> <p>Last name: <input type="text" name="last_name" value="Lennon" required> </p> <p>Birthday: <input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></p> """, ) self.assertHTMLEqual( p.as_div(), '<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field ' 'is required.</li></ul><div>First name: <input type="text" ' 'name="first_name" value="John" required></div><div>Last name: <input ' 'type="text" name="last_name" value="Lennon" required></div><div>' 'Birthday: <input type="text" name="birthday" value="1940-10-9" required>' '<input type="hidden" name="hidden_text"></div>', ) # A corner case: It's possible for a form to have only HiddenInputs. class TestForm(Form): foo = CharField(widget=HiddenInput) bar = CharField(widget=HiddenInput) p = TestForm(auto_id=False) self.assertHTMLEqual( p.as_table(), '<input type="hidden" name="foo"><input type="hidden" name="bar">', ) self.assertHTMLEqual( p.as_ul(), '<input type="hidden" name="foo"><input type="hidden" name="bar">', ) self.assertHTMLEqual( p.as_p(), '<input type="hidden" name="foo"><input type="hidden" name="bar">' ) def test_field_order(self): # A Form's fields are displayed in the same order in which they were defined. class TestForm(Form): field1 = CharField() field2 = CharField() field3 = CharField() field4 = CharField() field5 = CharField() field6 = CharField() field7 = CharField() field8 = CharField() field9 = CharField() field10 = CharField() field11 = CharField() field12 = CharField() field13 = CharField() field14 = CharField() p = TestForm(auto_id=False) self.assertHTMLEqual( p.as_table(), "".join( f"<tr><th>Field{i}:</th><td>" f'<input type="text" name="field{i}" required></td></tr>' for i in range(1, 15) ), ) def test_explicit_field_order(self): class TestFormParent(Form): field1 = CharField() field2 = CharField() field4 = CharField() field5 = CharField() field6 = CharField() field_order = ["field6", "field5", "field4", "field2", "field1"] class TestForm(TestFormParent): field3 = CharField() field_order = ["field2", "field4", "field3", "field5", "field6"] class TestFormRemove(TestForm): field1 = None class TestFormMissing(TestForm): field_order = ["field2", "field4", "field3", "field5", "field6", "field1"] field1 = None class TestFormInit(TestFormParent): field3 = CharField() field_order = None def __init__(self, **kwargs): super().__init__(**kwargs) self.order_fields(field_order=TestForm.field_order) p = TestFormParent() self.assertEqual(list(p.fields), TestFormParent.field_order) p = TestFormRemove() self.assertEqual(list(p.fields), TestForm.field_order) p = TestFormMissing() self.assertEqual(list(p.fields), TestForm.field_order) p = TestForm() self.assertEqual(list(p.fields), TestFormMissing.field_order) p = TestFormInit() order = [*TestForm.field_order, "field1"] self.assertEqual(list(p.fields), order) TestForm.field_order = ["unknown"] p = TestForm() self.assertEqual( list(p.fields), ["field1", "field2", "field4", "field5", "field6", "field3"] ) def test_form_html_attributes(self): # Some Field classes have an effect on the HTML attributes of their associated # Widget. If you set max_length in a CharField and its associated widget is # either a TextInput or PasswordInput, then the widget's rendered HTML will # include the "maxlength" attribute. class UserRegistration(Form): username = CharField(max_length=10) # uses TextInput by default password = CharField(max_length=10, widget=PasswordInput) realname = CharField( max_length=10, widget=TextInput ) # redundantly define widget, just to test address = CharField() # no max_length defined here p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" maxlength="10" required> </li> <li>Password: <input type="password" name="password" maxlength="10" required></li> <li>Realname: <input type="text" name="realname" maxlength="10" required> </li> <li>Address: <input type="text" name="address" required></li> """, ) # If you specify a custom "attrs" that includes the "maxlength" # attribute, the Field's max_length attribute will override whatever # "maxlength" you specify in "attrs". class UserRegistration(Form): username = CharField( max_length=10, widget=TextInput(attrs={"maxlength": 20}) ) password = CharField(max_length=10, widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), '<li>Username: <input type="text" name="username" maxlength="10" required>' "</li>" '<li>Password: <input type="password" name="password" maxlength="10" ' "required></li>", ) def test_specifying_labels(self): # You can specify the label for a field by using the 'label' argument to a Field # class. If you don't specify 'label', Django will use the field name with # underscores converted to spaces, and the initial letter capitalized. class UserRegistration(Form): username = CharField(max_length=10, label="Your username") password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput, label="Contraseña (de nuevo)") p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Your username: <input type="text" name="username" maxlength="10" required></li> <li>Password1: <input type="password" name="password1" required></li> <li>Contraseña (de nuevo): <input type="password" name="password2" required></li> """, ) # Labels for as_* methods will only end in a colon if they don't end in other # punctuation already. class Questions(Form): q1 = CharField(label="The first question") q2 = CharField(label="What is your name?") q3 = CharField(label="The answer to life is:") q4 = CharField(label="Answer this question!") q5 = CharField(label="The last question. Period.") self.assertHTMLEqual( Questions(auto_id=False).as_p(), """<p>The first question: <input type="text" name="q1" required></p> <p>What is your name? <input type="text" name="q2" required></p> <p>The answer to life is: <input type="text" name="q3" required></p> <p>Answer this question! <input type="text" name="q4" required></p> <p>The last question. Period. <input type="text" name="q5" required></p>""", ) self.assertHTMLEqual( Questions().as_p(), """ <p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" required></p> <p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" required></p> <p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" required></p> <p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" required></p> <p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" required></p> """, ) # If a label is set to the empty string for a field, that field won't # get a label. class UserRegistration(Form): username = CharField(max_length=10, label="") password = CharField(widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li> <input type="text" name="username" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""", ) p = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( p.as_ul(), """ <li> <input id="id_username" type="text" name="username" maxlength="10" required> </li> <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" required></li> """, ) # If label is None, Django will auto-create the label from the field name. This # is default behavior. class UserRegistration(Form): username = CharField(max_length=10, label=None) password = CharField(widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), '<li>Username: <input type="text" name="username" maxlength="10" required>' "</li>" '<li>Password: <input type="password" name="password" required></li>', ) p = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( p.as_ul(), """<li><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" required></li> <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" required></li>""", ) def test_label_suffix(self): # You can specify the 'label_suffix' argument to a Form class to modify # the punctuation symbol used at the end of a label. By default, the # colon (:) is used, and is only appended to the label if the label # doesn't already end with a punctuation symbol: ., !, ? or :. If you # specify a different suffix, it will be appended regardless of the # last character of the label. class FavoriteForm(Form): color = CharField(label="Favorite color?") animal = CharField(label="Favorite animal") answer = CharField(label="Secret answer", label_suffix=" =") f = FavoriteForm(auto_id=False) self.assertHTMLEqual( f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal: <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""", ) f = FavoriteForm(auto_id=False, label_suffix="?") self.assertHTMLEqual( f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal? <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""", ) f = FavoriteForm(auto_id=False, label_suffix="") self.assertHTMLEqual( f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""", ) f = FavoriteForm(auto_id=False, label_suffix="\u2192") self.assertHTMLEqual( f.as_ul(), '<li>Favorite color? <input type="text" name="color" required></li>\n' "<li>Favorite animal\u2192 " '<input type="text" name="animal" required></li>\n' '<li>Secret answer = <input type="text" name="answer" required></li>', ) def test_initial_data(self): # You can specify initial data for a field by using the 'initial' argument to a # Field class. This initial data is displayed when a Form is rendered with *no* # data. It is not displayed when a Form is rendered with any data (including an # empty dictionary). Also, the initial value is *not* used if data for a # particular required field isn't provided. class UserRegistration(Form): username = CharField(max_length=10, initial="django") password = CharField(widget=PasswordInput) # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) # Here, we're submitting data, so the initial value will *not* be displayed. p = UserRegistration({}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration({"username": ""}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration({"username": "foo"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> """, ) # An 'initial' value is *not* used as a fallback if data is not # provided. In this example, we don't provide a value for 'username', # and the form raises a validation error rather than using the initial # value for 'username'. p = UserRegistration({"password": "secret"}) self.assertEqual(p.errors["username"], ["This field is required."]) self.assertFalse(p.is_valid()) def test_dynamic_initial_data(self): # The previous technique dealt with "hard-coded" initial data, but it's also # possible to specify initial data after you've already created the Form class # (i.e., at runtime). Use the 'initial' parameter to the Form constructor. This # should be a dictionary containing initial values for one or more fields in the # form, keyed by field name. class UserRegistration(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(initial={"username": "django"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) p = UserRegistration(initial={"username": "stephane"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) # The 'initial' parameter is meaningless if you pass data. p = UserRegistration({}, initial={"username": "django"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration( {"username": ""}, initial={"username": "django"}, auto_id=False ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration( {"username": "foo"}, initial={"username": "django"}, auto_id=False ) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> """, ) # A dynamic 'initial' value is *not* used as a fallback if data is not provided. # In this example, we don't provide a value for 'username', and the # form raises a validation error rather than using the initial value # for 'username'. p = UserRegistration({"password": "secret"}, initial={"username": "django"}) self.assertEqual(p.errors["username"], ["This field is required."]) self.assertFalse(p.is_valid()) # If a Form defines 'initial' *and* 'initial' is passed as a parameter # to Form(), then the latter will get precedence. class UserRegistration(Form): username = CharField(max_length=10, initial="django") password = CharField(widget=PasswordInput) p = UserRegistration(initial={"username": "babik"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="babik" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) def test_callable_initial_data(self): # The previous technique dealt with raw values as initial data, but it's also # possible to specify callable data. class UserRegistration(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) options = MultipleChoiceField( choices=[("f", "foo"), ("b", "bar"), ("w", "whiz")] ) # We need to define functions that get called later.) def initial_django(): return "django" def initial_stephane(): return "stephane" def initial_options(): return ["f", "b"] def initial_other_options(): return ["b", "w"] # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration( initial={"username": initial_django, "options": initial_options}, auto_id=False, ) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li> """, ) # The 'initial' parameter is meaningless if you pass data. p = UserRegistration( {}, initial={"username": initial_django, "options": initial_options}, auto_id=False, ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b">bar</option> <option value="w">whiz</option> </select></li>""", ) p = UserRegistration( {"username": ""}, initial={"username": initial_django}, auto_id=False ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b">bar</option> <option value="w">whiz</option> </select></li>""", ) p = UserRegistration( {"username": "foo", "options": ["f", "b"]}, initial={"username": initial_django}, auto_id=False, ) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li> """, ) # A callable 'initial' value is *not* used as a fallback if data is not # provided. In this example, we don't provide a value for 'username', # and the form raises a validation error rather than using the initial # value for 'username'. p = UserRegistration( {"password": "secret"}, initial={"username": initial_django, "options": initial_options}, ) self.assertEqual(p.errors["username"], ["This field is required."]) self.assertFalse(p.is_valid()) # If a Form defines 'initial' *and* 'initial' is passed as a parameter # to Form(), then the latter will get precedence. class UserRegistration(Form): username = CharField(max_length=10, initial=initial_django) password = CharField(widget=PasswordInput) options = MultipleChoiceField( choices=[("f", "foo"), ("b", "bar"), ("w", "whiz")], initial=initial_other_options, ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b" selected>bar</option> <option value="w" selected>whiz</option> </select></li> """, ) p = UserRegistration( initial={"username": initial_stephane, "options": initial_options}, auto_id=False, ) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li> """, ) def test_get_initial_for_field(self): now = datetime.datetime(2006, 10, 25, 14, 30, 45, 123456) class PersonForm(Form): first_name = CharField(initial="John") last_name = CharField(initial="Doe") age = IntegerField() occupation = CharField(initial=lambda: "Unknown") dt_fixed = DateTimeField(initial=now) dt_callable = DateTimeField(initial=lambda: now) form = PersonForm(initial={"first_name": "Jane"}) cases = [ ("age", None), ("last_name", "Doe"), # Form.initial overrides Field.initial. ("first_name", "Jane"), # Callables are evaluated. ("occupation", "Unknown"), # Microseconds are removed from datetimes. ("dt_fixed", datetime.datetime(2006, 10, 25, 14, 30, 45)), ("dt_callable", datetime.datetime(2006, 10, 25, 14, 30, 45)), ] for field_name, expected in cases: with self.subTest(field_name=field_name): field = form.fields[field_name] actual = form.get_initial_for_field(field, field_name) self.assertEqual(actual, expected) def test_changed_data(self): class Person(Form): first_name = CharField(initial="Hans") last_name = CharField(initial="Greatel") birthday = DateField(initial=datetime.date(1974, 8, 16)) p = Person( data={"first_name": "Hans", "last_name": "Scrmbl", "birthday": "1974-08-16"} ) self.assertTrue(p.is_valid()) self.assertNotIn("first_name", p.changed_data) self.assertIn("last_name", p.changed_data) self.assertNotIn("birthday", p.changed_data) # A field raising ValidationError is always in changed_data class PedanticField(forms.Field): def to_python(self, value): raise ValidationError("Whatever") class Person2(Person): pedantic = PedanticField(initial="whatever", show_hidden_initial=True) p = Person2( data={ "first_name": "Hans", "last_name": "Scrmbl", "birthday": "1974-08-16", "initial-pedantic": "whatever", } ) self.assertFalse(p.is_valid()) self.assertIn("pedantic", p.changed_data) def test_boundfield_values(self): # It's possible to get to the value which would be used for rendering # the widget for a field by using the BoundField's value method. class UserRegistration(Form): username = CharField(max_length=10, initial="djangonaut") password = CharField(widget=PasswordInput) unbound = UserRegistration() bound = UserRegistration({"password": "foo"}) self.assertIsNone(bound["username"].value()) self.assertEqual(unbound["username"].value(), "djangonaut") self.assertEqual(bound["password"].value(), "foo") self.assertIsNone(unbound["password"].value()) def test_boundfield_initial_called_once(self): """ Multiple calls to BoundField().value() in an unbound form should return the same result each time (#24391). """ class MyForm(Form): name = CharField(max_length=10, initial=uuid.uuid4) form = MyForm() name = form["name"] self.assertEqual(name.value(), name.value()) # BoundField is also cached self.assertIs(form["name"], name) def test_boundfield_value_disabled_callable_initial(self): class PersonForm(Form): name = CharField(initial=lambda: "John Doe", disabled=True) # Without form data. form = PersonForm() self.assertEqual(form["name"].value(), "John Doe") # With form data. As the field is disabled, the value should not be # affected by the form data. form = PersonForm({}) self.assertEqual(form["name"].value(), "John Doe") def test_custom_boundfield(self): class CustomField(CharField): def get_bound_field(self, form, name): return (form, name) class SampleForm(Form): name = CustomField() f = SampleForm() self.assertEqual(f["name"], (f, "name")) def test_initial_datetime_values(self): now = datetime.datetime.now() # Nix microseconds (since they should be ignored). #22502 now_no_ms = now.replace(microsecond=0) if now == now_no_ms: now = now.replace(microsecond=1) def delayed_now(): return now def delayed_now_time(): return now.time() class HiddenInputWithoutMicrosec(HiddenInput): supports_microseconds = False class TextInputWithoutMicrosec(TextInput): supports_microseconds = False class DateTimeForm(Form): # Test a non-callable. fixed = DateTimeField(initial=now) auto_timestamp = DateTimeField(initial=delayed_now) auto_time_only = TimeField(initial=delayed_now_time) supports_microseconds = DateTimeField(initial=delayed_now, widget=TextInput) hi_default_microsec = DateTimeField(initial=delayed_now, widget=HiddenInput) hi_without_microsec = DateTimeField( initial=delayed_now, widget=HiddenInputWithoutMicrosec ) ti_without_microsec = DateTimeField( initial=delayed_now, widget=TextInputWithoutMicrosec ) unbound = DateTimeForm() cases = [ ("fixed", now_no_ms), ("auto_timestamp", now_no_ms), ("auto_time_only", now_no_ms.time()), ("supports_microseconds", now), ("hi_default_microsec", now), ("hi_without_microsec", now_no_ms), ("ti_without_microsec", now_no_ms), ] for field_name, expected in cases: with self.subTest(field_name=field_name): actual = unbound[field_name].value() self.assertEqual(actual, expected) # Also check get_initial_for_field(). field = unbound.fields[field_name] actual = unbound.get_initial_for_field(field, field_name) self.assertEqual(actual, expected) def get_datetime_form_with_callable_initial(self, disabled, microseconds=0): class FakeTime: def __init__(self): self.elapsed_seconds = 0 def now(self): self.elapsed_seconds += 1 return datetime.datetime( 2006, 10, 25, 14, 30, 45 + self.elapsed_seconds, microseconds, ) class DateTimeForm(forms.Form): dt = DateTimeField(initial=FakeTime().now, disabled=disabled) return DateTimeForm({}) def test_datetime_clean_disabled_callable_initial_microseconds(self): """ Cleaning a form with a disabled DateTimeField and callable initial removes microseconds. """ form = self.get_datetime_form_with_callable_initial( disabled=True, microseconds=123456, ) self.assertEqual(form.errors, {}) self.assertEqual( form.cleaned_data, { "dt": datetime.datetime(2006, 10, 25, 14, 30, 46), }, ) def test_datetime_clean_disabled_callable_initial_bound_field(self): """ The cleaned value for a form with a disabled DateTimeField and callable initial matches the bound field's cached initial value. """ form = self.get_datetime_form_with_callable_initial(disabled=True) self.assertEqual(form.errors, {}) cleaned = form.cleaned_data["dt"] self.assertEqual(cleaned, datetime.datetime(2006, 10, 25, 14, 30, 46)) bf = form["dt"] self.assertEqual(cleaned, bf.initial) def test_datetime_changed_data_callable_with_microseconds(self): class DateTimeForm(forms.Form): dt = DateTimeField( initial=lambda: datetime.datetime(2006, 10, 25, 14, 30, 45, 123456), disabled=True, ) form = DateTimeForm({"dt": "2006-10-25 14:30:45"}) self.assertEqual(form.changed_data, []) def test_help_text(self): # You can specify descriptive text for a field by using the 'help_text' # argument. class UserRegistration(Form): username = CharField(max_length=10, help_text="e.g., [email protected]") password = CharField( widget=PasswordInput, help_text="Wählen Sie mit Bedacht." ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></li> <li>Password: <input type="password" name="password" required> <span class="helptext">Wählen Sie mit Bedacht.</span></li>""", ) self.assertHTMLEqual( p.as_p(), """<p>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></p> <p>Password: <input type="password" name="password" required> <span class="helptext">Wählen Sie mit Bedacht.</span></p>""", ) self.assertHTMLEqual( p.as_table(), """ <tr><th>Username:</th><td> <input type="text" name="username" maxlength="10" required><br> <span class="helptext">e.g., [email protected]</span></td></tr> <tr><th>Password:</th><td><input type="password" name="password" required> <br> <span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>""", ) self.assertHTMLEqual( p.as_div(), '<div>Username: <div class="helptext">e.g., [email protected]</div>' '<input type="text" name="username" maxlength="10" required></div>' '<div>Password: <div class="helptext">Wählen Sie mit Bedacht.</div>' '<input type="password" name="password" required></div>', ) # The help text is displayed whether or not data is provided for the form. p = UserRegistration({"username": "foo"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), '<li>Username: <input type="text" name="username" value="foo" ' 'maxlength="10" required>' '<span class="helptext">e.g., [email protected]</span></li>' '<li><ul class="errorlist"><li>This field is required.</li></ul>' 'Password: <input type="password" name="password" required>' '<span class="helptext">Wählen Sie mit Bedacht.</span></li>', ) # help_text is not displayed for hidden fields. It can be used for documentation # purposes, though. class UserRegistration(Form): username = CharField(max_length=10, help_text="e.g., [email protected]") password = CharField(widget=PasswordInput) next = CharField( widget=HiddenInput, initial="/", help_text="Redirect destination" ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></li> <li>Password: <input type="password" name="password" required> <input type="hidden" name="next" value="/"></li>""", ) def test_help_text_html_safe(self): """help_text should not be escaped.""" class UserRegistration(Form): username = CharField(max_length=10, help_text="e.g., [email protected]") password = CharField( widget=PasswordInput, help_text="Help text is <strong>escaped</strong>.", ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), '<li>Username: <input type="text" name="username" maxlength="10" required>' '<span class="helptext">e.g., [email protected]</span></li>' '<li>Password: <input type="password" name="password" required>' '<span class="helptext">Help text is <strong>escaped</strong>.</span></li>', ) self.assertHTMLEqual( p.as_p(), '<p>Username: <input type="text" name="username" maxlength="10" required>' '<span class="helptext">e.g., [email protected]</span></p>' '<p>Password: <input type="password" name="password" required>' '<span class="helptext">Help text is <strong>escaped</strong>.</span></p>', ) self.assertHTMLEqual( p.as_table(), "<tr><th>Username:</th><td>" '<input type="text" name="username" maxlength="10" required><br>' '<span class="helptext">e.g., [email protected]</span></td></tr>' "<tr><th>Password:</th><td>" '<input type="password" name="password" required><br>' '<span class="helptext">Help text is <strong>escaped</strong>.</span>' "</td></tr>", ) def test_subclassing_forms(self): # You can subclass a Form to add fields. The resulting form subclass will have # all of the fields of the parent Form, plus whichever fields you define in the # subclass. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class Musician(Person): instrument = CharField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""", ) m = Musician(auto_id=False) self.assertHTMLEqual( m.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li> <li>Instrument: <input type="text" name="instrument" required></li>""", ) # Yes, you can subclass multiple forms. The fields are added in the order in # which the parent classes are listed. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class Instrument(Form): instrument = CharField() class Beatle(Person, Instrument): haircut_type = CharField() b = Beatle(auto_id=False) self.assertHTMLEqual( b.as_ul(), """<li>Instrument: <input type="text" name="instrument" required></li> <li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li> <li>Haircut type: <input type="text" name="haircut_type" required></li>""", ) def test_forms_with_prefixes(self): # Sometimes it's necessary to have multiple forms display on the same # HTML page, or multiple copies of the same form. We can accomplish # this with form prefixes. Pass the keyword argument 'prefix' to the # Form constructor to use this feature. This value will be prepended to # each HTML form field name. One way to think about this is "namespaces # for HTML forms". Notice that in the data argument, each field's key # has the prefix, in this case 'person1', prepended to the actual field # name. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() data = { "person1-first_name": "John", "person1-last_name": "Lennon", "person1-birthday": "1940-10-9", } p = Person(data, prefix="person1") self.assertHTMLEqual( p.as_ul(), """ <li><label for="id_person1-first_name">First name:</label> <input type="text" name="person1-first_name" value="John" id="id_person1-first_name" required></li> <li><label for="id_person1-last_name">Last name:</label> <input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" required></li> <li><label for="id_person1-birthday">Birthday:</label> <input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required></li> """, ) self.assertHTMLEqual( str(p["first_name"]), '<input type="text" name="person1-first_name" value="John" ' 'id="id_person1-first_name" required>', ) self.assertHTMLEqual( str(p["last_name"]), '<input type="text" name="person1-last_name" value="Lennon" ' 'id="id_person1-last_name" required>', ) self.assertHTMLEqual( str(p["birthday"]), '<input type="text" name="person1-birthday" value="1940-10-9" ' 'id="id_person1-birthday" required>', ) self.assertEqual(p.errors, {}) self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data["first_name"], "John") self.assertEqual(p.cleaned_data["last_name"], "Lennon") self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) # Let's try submitting some bad data to make sure form.errors and field.errors # work as expected. data = { "person1-first_name": "", "person1-last_name": "", "person1-birthday": "", } p = Person(data, prefix="person1") self.assertEqual(p.errors["first_name"], ["This field is required."]) self.assertEqual(p.errors["last_name"], ["This field is required."]) self.assertEqual(p.errors["birthday"], ["This field is required."]) self.assertEqual(p["first_name"].errors, ["This field is required."]) # Accessing a nonexistent field. with self.assertRaises(KeyError): p["person1-first_name"].errors # In this example, the data doesn't have a prefix, but the form requires it, so # the form doesn't "see" the fields. data = {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"} p = Person(data, prefix="person1") self.assertEqual(p.errors["first_name"], ["This field is required."]) self.assertEqual(p.errors["last_name"], ["This field is required."]) self.assertEqual(p.errors["birthday"], ["This field is required."]) # With prefixes, a single data dictionary can hold data for multiple instances # of the same form. data = { "person1-first_name": "John", "person1-last_name": "Lennon", "person1-birthday": "1940-10-9", "person2-first_name": "Jim", "person2-last_name": "Morrison", "person2-birthday": "1943-12-8", } p1 = Person(data, prefix="person1") self.assertTrue(p1.is_valid()) self.assertEqual(p1.cleaned_data["first_name"], "John") self.assertEqual(p1.cleaned_data["last_name"], "Lennon") self.assertEqual(p1.cleaned_data["birthday"], datetime.date(1940, 10, 9)) p2 = Person(data, prefix="person2") self.assertTrue(p2.is_valid()) self.assertEqual(p2.cleaned_data["first_name"], "Jim") self.assertEqual(p2.cleaned_data["last_name"], "Morrison") self.assertEqual(p2.cleaned_data["birthday"], datetime.date(1943, 12, 8)) # By default, forms append a hyphen between the prefix and the field name, but a # form can alter that behavior by implementing the add_prefix() method. This # method takes a field name and returns the prefixed field, according to # self.prefix. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() def add_prefix(self, field_name): return ( "%s-prefix-%s" % (self.prefix, field_name) if self.prefix else field_name ) p = Person(prefix="foo") self.assertHTMLEqual( p.as_ul(), """ <li><label for="id_foo-prefix-first_name">First name:</label> <input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" required></li> <li><label for="id_foo-prefix-last_name">Last name:</label> <input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" required></li> <li><label for="id_foo-prefix-birthday">Birthday:</label> <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" required></li> """, ) data = { "foo-prefix-first_name": "John", "foo-prefix-last_name": "Lennon", "foo-prefix-birthday": "1940-10-9", } p = Person(data, prefix="foo") self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data["first_name"], "John") self.assertEqual(p.cleaned_data["last_name"], "Lennon") self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) def test_class_prefix(self): # Prefix can be also specified at the class level. class Person(Form): first_name = CharField() prefix = "foo" p = Person() self.assertEqual(p.prefix, "foo") p = Person(prefix="bar") self.assertEqual(p.prefix, "bar") def test_forms_with_null_boolean(self): # NullBooleanField is a bit of a special case because its presentation (widget) # is different than its data. This is handled transparently, though. class Person(Form): name = CharField() is_cool = NullBooleanField() p = Person({"name": "Joe"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "1"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "2"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true" selected>Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "3"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true">Yes</option> <option value="false" selected>No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": True}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true" selected>Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": False}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true">Yes</option> <option value="false" selected>No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "unknown"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "true"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true" selected>Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "false"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true">Yes</option> <option value="false" selected>No</option> </select>""", ) def test_forms_with_file_fields(self): # FileFields are a special case because they take their data from the # request.FILES, not request.POST. class FileForm(Form): file1 = FileField() f = FileForm(auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) f = FileForm(data={}, files={}, auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="file" name="file1" required></td></tr>', ) f = FileForm( data={}, files={"file1": SimpleUploadedFile("name", b"")}, auto_id=False ) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<ul class="errorlist"><li>The submitted file is empty.</li></ul>' '<input type="file" name="file1" required></td></tr>', ) f = FileForm( data={}, files={"file1": "something that is not a file"}, auto_id=False ) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<ul class="errorlist"><li>No file was submitted. Check the ' "encoding type on the form.</li></ul>" '<input type="file" name="file1" required></td></tr>', ) f = FileForm( data={}, files={"file1": SimpleUploadedFile("name", b"some content")}, auto_id=False, ) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) self.assertTrue(f.is_valid()) file1 = SimpleUploadedFile( "我隻氣墊船裝滿晒鱔.txt", "मेरी मँडराने वाली नाव सर्पमीनों से भरी ह".encode() ) f = FileForm(data={}, files={"file1": file1}, auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) # A required file field with initial data should not contain the # required HTML attribute. The file input is left blank by the user to # keep the existing, initial value. f = FileForm(initial={"file1": "resume.txt"}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1"></td></tr>', ) def test_filefield_initial_callable(self): class FileForm(forms.Form): file1 = forms.FileField(initial=lambda: "resume.txt") f = FileForm({}) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["file1"], "resume.txt") def test_filefield_with_fileinput_required(self): class FileForm(Form): file1 = forms.FileField(widget=FileInput) f = FileForm(auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) # A required file field with initial data doesn't contain the required # HTML attribute. The file input is left blank by the user to keep the # existing, initial value. f = FileForm(initial={"file1": "resume.txt"}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1"></td></tr>', ) def test_empty_permitted(self): # Sometimes (pretty much in formsets) we want to allow a form to pass validation # if it is completely empty. We can accomplish this by using the empty_permitted # argument to a form constructor. class SongForm(Form): artist = CharField() name = CharField() # First let's show what happens id empty_permitted=False (the default): data = {"artist": "", "song": ""} form = SongForm(data, empty_permitted=False) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, { "name": ["This field is required."], "artist": ["This field is required."], }, ) self.assertEqual(form.cleaned_data, {}) # Now let's show what happens when empty_permitted=True and the form is empty. form = SongForm(data, empty_permitted=True, use_required_attribute=False) self.assertTrue(form.is_valid()) self.assertEqual(form.errors, {}) self.assertEqual(form.cleaned_data, {}) # But if we fill in data for one of the fields, the form is no longer empty and # the whole thing must pass validation. data = {"artist": "The Doors", "song": ""} form = SongForm(data, empty_permitted=False) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {"name": ["This field is required."]}) self.assertEqual(form.cleaned_data, {"artist": "The Doors"}) # If a field is not given in the data then None is returned for its data. Lets # make sure that when checking for empty_permitted that None is treated # accordingly. data = {"artist": None, "song": ""} form = SongForm(data, empty_permitted=True, use_required_attribute=False) self.assertTrue(form.is_valid()) # However, we *really* need to be sure we are checking for None as any data in # initial that returns False on a boolean call needs to be treated literally. class PriceForm(Form): amount = FloatField() qty = IntegerField() data = {"amount": "0.0", "qty": ""} form = PriceForm( data, initial={"amount": 0.0}, empty_permitted=True, use_required_attribute=False, ) self.assertTrue(form.is_valid()) def test_empty_permitted_and_use_required_attribute(self): msg = ( "The empty_permitted and use_required_attribute arguments may not " "both be True." ) with self.assertRaisesMessage(ValueError, msg): Person(empty_permitted=True, use_required_attribute=True) def test_extracting_hidden_and_visible(self): class SongForm(Form): token = CharField(widget=HiddenInput) artist = CharField() name = CharField() form = SongForm() self.assertEqual([f.name for f in form.hidden_fields()], ["token"]) self.assertEqual([f.name for f in form.visible_fields()], ["artist", "name"]) def test_hidden_initial_gets_id(self): class MyForm(Form): field1 = CharField(max_length=50, show_hidden_initial=True) self.assertHTMLEqual( MyForm().as_table(), '<tr><th><label for="id_field1">Field1:</label></th><td>' '<input id="id_field1" type="text" name="field1" maxlength="50" required>' '<input type="hidden" name="initial-field1" id="initial-id_field1">' "</td></tr>", ) def test_error_html_required_html_classes(self): class Person(Form): name = CharField() is_cool = NullBooleanField() email = EmailField(required=False) age = IntegerField() p = Person({}) p.error_css_class = "error" p.required_css_class = "required" self.assertHTMLEqual( p.as_ul(), """ <li class="required error"><ul class="errorlist"> <li>This field is required.</li></ul> <label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li> <li class="required"> <label class="required" for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select></li> <li><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></li> <li class="required error"><ul class="errorlist"> <li>This field is required.</li></ul> <label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required></li>""", ) self.assertHTMLEqual( p.as_p(), """ <ul class="errorlist"><li>This field is required.</li></ul> <p class="required error"> <label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></p> <p class="required"> <label class="required" for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select></p> <p><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></p> <ul class="errorlist"><li>This field is required.</li></ul> <p class="required error"><label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required></p> """, ) self.assertHTMLEqual( p.as_table(), """<tr class="required error"> <th><label class="required" for="id_name">Name:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="name" id="id_name" required></td></tr> <tr class="required"><th><label class="required" for="id_is_cool">Is cool:</label></th> <td><select name="is_cool" id="id_is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select></td></tr> <tr><th><label for="id_email">Email:</label></th><td> <input type="email" name="email" id="id_email"></td></tr> <tr class="required error"><th><label class="required" for="id_age">Age:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="number" name="age" id="id_age" required></td></tr>""", ) self.assertHTMLEqual( p.as_div(), '<div class="required error"><label for="id_name" class="required">Name:' '</label><ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="name" required id="id_name" /></div>' '<div class="required"><label for="id_is_cool" class="required">Is cool:' '</label><select name="is_cool" id="id_is_cool">' '<option value="unknown" selected>Unknown</option>' '<option value="true">Yes</option><option value="false">No</option>' '</select></div><div><label for="id_email">Email:</label>' '<input type="email" name="email" id="id_email" /></div>' '<div class="required error"><label for="id_age" class="required">Age:' '</label><ul class="errorlist"><li>This field is required.</li></ul>' '<input type="number" name="age" required id="id_age" /></div>', ) def test_label_has_required_css_class(self): """ required_css_class is added to label_tag() and legend_tag() of required fields. """ class SomeForm(Form): required_css_class = "required" field = CharField(max_length=10) field2 = IntegerField(required=False) f = SomeForm({"field": "test"}) self.assertHTMLEqual( f["field"].label_tag(), '<label for="id_field" class="required">Field:</label>', ) self.assertHTMLEqual( f["field"].legend_tag(), '<legend for="id_field" class="required">Field:</legend>', ) self.assertHTMLEqual( f["field"].label_tag(attrs={"class": "foo"}), '<label for="id_field" class="foo required">Field:</label>', ) self.assertHTMLEqual( f["field"].legend_tag(attrs={"class": "foo"}), '<legend for="id_field" class="foo required">Field:</legend>', ) self.assertHTMLEqual( f["field2"].label_tag(), '<label for="id_field2">Field2:</label>' ) self.assertHTMLEqual( f["field2"].legend_tag(), '<legend for="id_field2">Field2:</legend>', ) def test_label_split_datetime_not_displayed(self): class EventForm(Form): happened_at = SplitDateTimeField(widget=SplitHiddenDateTimeWidget) form = EventForm() self.assertHTMLEqual( form.as_ul(), '<input type="hidden" name="happened_at_0" id="id_happened_at_0">' '<input type="hidden" name="happened_at_1" id="id_happened_at_1">', ) def test_multivalue_field_validation(self): def bad_names(value): if value == "bad value": raise ValidationError("bad value not allowed") class NameField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = ( CharField(label="First name", max_length=10), CharField(label="Last name", max_length=10), ) super().__init__(fields=fields, *args, **kwargs) def compress(self, data_list): return " ".join(data_list) class NameForm(Form): name = NameField(validators=[bad_names]) form = NameForm(data={"name": ["bad", "value"]}) form.full_clean() self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {"name": ["bad value not allowed"]}) form = NameForm(data={"name": ["should be overly", "long for the field names"]}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, { "name": [ "Ensure this value has at most 10 characters (it has 16).", "Ensure this value has at most 10 characters (it has 24).", ], }, ) form = NameForm(data={"name": ["fname", "lname"]}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data, {"name": "fname lname"}) def test_multivalue_deep_copy(self): """ #19298 -- MultiValueField needs to override the default as it needs to deep-copy subfields: """ class ChoicesField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = ( ChoiceField(label="Rank", choices=((1, 1), (2, 2))), CharField(label="Name", max_length=10), ) super().__init__(fields=fields, *args, **kwargs) field = ChoicesField() field2 = copy.deepcopy(field) self.assertIsInstance(field2, ChoicesField) self.assertIsNot(field2.fields, field.fields) self.assertIsNot(field2.fields[0].choices, field.fields[0].choices) def test_multivalue_initial_data(self): """ #23674 -- invalid initial data should not break form.changed_data() """ class DateAgeField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = (DateField(label="Date"), IntegerField(label="Age")) super().__init__(fields=fields, *args, **kwargs) class DateAgeForm(Form): date_age = DateAgeField() data = {"date_age": ["1998-12-06", 16]} form = DateAgeForm(data, initial={"date_age": ["200-10-10", 14]}) self.assertTrue(form.has_changed()) def test_multivalue_optional_subfields(self): class PhoneField(MultiValueField): def __init__(self, *args, **kwargs): fields = ( CharField( label="Country Code", validators=[ RegexValidator( r"^\+[0-9]{1,2}$", message="Enter a valid country code." ) ], ), CharField(label="Phone Number"), CharField( label="Extension", error_messages={"incomplete": "Enter an extension."}, ), CharField( label="Label", required=False, help_text="E.g. home, work." ), ) super().__init__(fields, *args, **kwargs) def compress(self, data_list): if data_list: return "%s.%s ext. %s (label: %s)" % tuple(data_list) return None # An empty value for any field will raise a `required` error on a # required `MultiValueField`. f = PhoneField() with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean([]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(["+61"]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(["+61", "287654321", "123"]) self.assertEqual( "+61.287654321 ext. 123 (label: Home)", f.clean(["+61", "287654321", "123", "Home"]), ) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) # Empty values for fields will NOT raise a `required` error on an # optional `MultiValueField` f = PhoneField(required=False) self.assertIsNone(f.clean("")) self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean([])) self.assertEqual("+61. ext. (label: )", f.clean(["+61"])) self.assertEqual( "+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"]) ) self.assertEqual( "+61.287654321 ext. 123 (label: Home)", f.clean(["+61", "287654321", "123", "Home"]), ) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) # For a required `MultiValueField` with `require_all_fields=False`, a # `required` error will only be raised if all fields are empty. Fields # can individually be required or optional. An empty value for any # required field will raise an `incomplete` error. f = PhoneField(require_all_fields=False) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean([]) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): f.clean(["+61"]) self.assertEqual( "+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"]) ) with self.assertRaisesMessage( ValidationError, "'Enter a complete value.', 'Enter an extension.'" ): f.clean(["", "", "", "Home"]) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) # For an optional `MultiValueField` with `require_all_fields=False`, we # don't get any `required` error but we still get `incomplete` errors. f = PhoneField(required=False, require_all_fields=False) self.assertIsNone(f.clean("")) self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean([])) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): f.clean(["+61"]) self.assertEqual( "+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"]) ) with self.assertRaisesMessage( ValidationError, "'Enter a complete value.', 'Enter an extension.'" ): f.clean(["", "", "", "Home"]) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) def test_multivalue_optional_subfields_rendering(self): class PhoneWidget(MultiWidget): def __init__(self, attrs=None): widgets = [TextInput(), TextInput()] super().__init__(widgets, attrs) def decompress(self, value): return [None, None] class PhoneField(MultiValueField): def __init__(self, *args, **kwargs): fields = [CharField(), CharField(required=False)] super().__init__(fields, *args, **kwargs) class PhoneForm(Form): phone1 = PhoneField(widget=PhoneWidget) phone2 = PhoneField(widget=PhoneWidget, required=False) phone3 = PhoneField(widget=PhoneWidget, require_all_fields=False) phone4 = PhoneField( widget=PhoneWidget, required=False, require_all_fields=False, ) form = PhoneForm(auto_id=False) self.assertHTMLEqual( form.as_p(), """ <p>Phone1:<input type="text" name="phone1_0" required> <input type="text" name="phone1_1" required></p> <p>Phone2:<input type="text" name="phone2_0"> <input type="text" name="phone2_1"></p> <p>Phone3:<input type="text" name="phone3_0" required> <input type="text" name="phone3_1"></p> <p>Phone4:<input type="text" name="phone4_0"> <input type="text" name="phone4_1"></p> """, ) def test_custom_empty_values(self): """ Form fields can customize what is considered as an empty value for themselves (#19997). """ class CustomJSONField(CharField): empty_values = [None, ""] def to_python(self, value): # Fake json.loads if value == "{}": return {} return super().to_python(value) class JSONForm(forms.Form): json = CustomJSONField() form = JSONForm(data={"json": "{}"}) form.full_clean() self.assertEqual(form.cleaned_data, {"json": {}}) def test_boundfield_label_tag(self): class SomeForm(Form): field = CharField() boundfield = SomeForm()["field"] testcases = [ # (args, kwargs, expected) # without anything: just print the <label> ((), {}, '<%(tag)s for="id_field">Field:</%(tag)s>'), # passing just one argument: overrides the field's label (("custom",), {}, '<%(tag)s for="id_field">custom:</%(tag)s>'), # the overridden label is escaped (("custom&",), {}, '<%(tag)s for="id_field">custom&amp;:</%(tag)s>'), ((mark_safe("custom&"),), {}, '<%(tag)s for="id_field">custom&:</%(tag)s>'), # Passing attrs to add extra attributes on the <label> ( (), {"attrs": {"class": "pretty"}}, '<%(tag)s for="id_field" class="pretty">Field:</%(tag)s>', ), ] for args, kwargs, expected in testcases: with self.subTest(args=args, kwargs=kwargs): self.assertHTMLEqual( boundfield.label_tag(*args, **kwargs), expected % {"tag": "label"}, ) self.assertHTMLEqual( boundfield.legend_tag(*args, **kwargs), expected % {"tag": "legend"}, ) def test_boundfield_label_tag_no_id(self): """ If a widget has no id, label_tag() and legend_tag() return the text with no surrounding <label>. """ class SomeForm(Form): field = CharField() boundfield = SomeForm(auto_id="")["field"] self.assertHTMLEqual(boundfield.label_tag(), "Field:") self.assertHTMLEqual(boundfield.legend_tag(), "Field:") self.assertHTMLEqual(boundfield.label_tag("Custom&"), "Custom&amp;:") self.assertHTMLEqual(boundfield.legend_tag("Custom&"), "Custom&amp;:") def test_boundfield_label_tag_custom_widget_id_for_label(self): class CustomIdForLabelTextInput(TextInput): def id_for_label(self, id): return "custom_" + id class EmptyIdForLabelTextInput(TextInput): def id_for_label(self, id): return None class SomeForm(Form): custom = CharField(widget=CustomIdForLabelTextInput) empty = CharField(widget=EmptyIdForLabelTextInput) form = SomeForm() self.assertHTMLEqual( form["custom"].label_tag(), '<label for="custom_id_custom">Custom:</label>' ) self.assertHTMLEqual( form["custom"].legend_tag(), '<legend for="custom_id_custom">Custom:</legend>', ) self.assertHTMLEqual(form["empty"].label_tag(), "<label>Empty:</label>") self.assertHTMLEqual(form["empty"].legend_tag(), "<legend>Empty:</legend>") def test_boundfield_empty_label(self): class SomeForm(Form): field = CharField(label="") boundfield = SomeForm()["field"] self.assertHTMLEqual(boundfield.label_tag(), '<label for="id_field"></label>') self.assertHTMLEqual( boundfield.legend_tag(), '<legend for="id_field"></legend>', ) def test_boundfield_id_for_label(self): class SomeForm(Form): field = CharField(label="") self.assertEqual(SomeForm()["field"].id_for_label, "id_field") def test_boundfield_id_for_label_override_by_attrs(self): """ If an id is provided in `Widget.attrs`, it overrides the generated ID, unless it is `None`. """ class SomeForm(Form): field = CharField(widget=TextInput(attrs={"id": "myCustomID"})) field_none = CharField(widget=TextInput(attrs={"id": None})) form = SomeForm() self.assertEqual(form["field"].id_for_label, "myCustomID") self.assertEqual(form["field_none"].id_for_label, "id_field_none") def test_boundfield_subwidget_id_for_label(self): """ If auto_id is provided when initializing the form, the generated ID in subwidgets must reflect that prefix. """ class SomeForm(Form): field = MultipleChoiceField( choices=[("a", "A"), ("b", "B")], widget=CheckboxSelectMultiple, ) form = SomeForm(auto_id="prefix_%s") subwidgets = form["field"].subwidgets self.assertEqual(subwidgets[0].id_for_label, "prefix_field_0") self.assertEqual(subwidgets[1].id_for_label, "prefix_field_1") def test_boundfield_widget_type(self): class SomeForm(Form): first_name = CharField() birthday = SplitDateTimeField(widget=SplitHiddenDateTimeWidget) f = SomeForm() self.assertEqual(f["first_name"].widget_type, "text") self.assertEqual(f["birthday"].widget_type, "splithiddendatetime") def test_boundfield_css_classes(self): form = Person() field = form["first_name"] self.assertEqual(field.css_classes(), "") self.assertEqual(field.css_classes(extra_classes=""), "") self.assertEqual(field.css_classes(extra_classes="test"), "test") self.assertEqual(field.css_classes(extra_classes="test test"), "test") def test_label_suffix_override(self): """ BoundField label_suffix (if provided) overrides Form label_suffix """ class SomeForm(Form): field = CharField() boundfield = SomeForm(label_suffix="!")["field"] self.assertHTMLEqual( boundfield.label_tag(label_suffix="$"), '<label for="id_field">Field$</label>', ) self.assertHTMLEqual( boundfield.legend_tag(label_suffix="$"), '<legend for="id_field">Field$</legend>', ) def test_error_dict(self): class MyForm(Form): foo = CharField() bar = CharField() def clean(self): raise ValidationError( "Non-field error.", code="secret", params={"a": 1, "b": 2} ) form = MyForm({}) self.assertIs(form.is_valid(), False) errors = form.errors.as_text() control = [ "* foo\n * This field is required.", "* bar\n * This field is required.", "* __all__\n * Non-field error.", ] for error in control: self.assertIn(error, errors) errors = form.errors.as_ul() control = [ '<li>foo<ul class="errorlist"><li>This field is required.</li></ul></li>', '<li>bar<ul class="errorlist"><li>This field is required.</li></ul></li>', '<li>__all__<ul class="errorlist nonfield"><li>Non-field error.</li></ul>' "</li>", ] for error in control: self.assertInHTML(error, errors) errors = form.errors.get_json_data() control = { "foo": [{"code": "required", "message": "This field is required."}], "bar": [{"code": "required", "message": "This field is required."}], "__all__": [{"code": "secret", "message": "Non-field error."}], } self.assertEqual(errors, control) self.assertEqual(json.dumps(errors), form.errors.as_json()) def test_error_dict_as_json_escape_html(self): """#21962 - adding html escape flag to ErrorDict""" class MyForm(Form): foo = CharField() bar = CharField() def clean(self): raise ValidationError( "<p>Non-field error.</p>", code="secret", params={"a": 1, "b": 2}, ) control = { "foo": [{"code": "required", "message": "This field is required."}], "bar": [{"code": "required", "message": "This field is required."}], "__all__": [{"code": "secret", "message": "<p>Non-field error.</p>"}], } form = MyForm({}) self.assertFalse(form.is_valid()) errors = json.loads(form.errors.as_json()) self.assertEqual(errors, control) escaped_error = "&lt;p&gt;Non-field error.&lt;/p&gt;" self.assertEqual( form.errors.get_json_data(escape_html=True)["__all__"][0]["message"], escaped_error, ) errors = json.loads(form.errors.as_json(escape_html=True)) control["__all__"][0]["message"] = escaped_error self.assertEqual(errors, control) def test_error_list(self): e = ErrorList() e.append("Foo") e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"})) self.assertIsInstance(e, list) self.assertIn("Foo", e) self.assertIn("Foo", ValidationError(e)) self.assertEqual(e.as_text(), "* Foo\n* Foobar") self.assertEqual( e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>' ) errors = e.get_json_data() self.assertEqual( errors, [{"message": "Foo", "code": ""}, {"message": "Foobar", "code": "foobar"}], ) self.assertEqual(json.dumps(errors), e.as_json()) def test_error_list_class_not_specified(self): e = ErrorList() e.append("Foo") e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"})) self.assertEqual( e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>' ) def test_error_list_class_has_one_class_specified(self): e = ErrorList(error_class="foobar-error-class") e.append("Foo") e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"})) self.assertEqual( e.as_ul(), '<ul class="errorlist foobar-error-class"><li>Foo</li><li>Foobar</li></ul>', ) def test_error_list_with_hidden_field_errors_has_correct_class(self): class Person(Form): first_name = CharField() last_name = CharField(widget=HiddenInput) p = Person({"first_name": "John"}) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul></li><li> <label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></li>""", ) self.assertHTMLEqual( p.as_p(), """ <ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul> <p><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></p> """, ) self.assertHTMLEqual( p.as_table(), """<tr><td colspan="2"><ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul></td></tr> <tr><th><label for="id_first_name">First name:</label></th><td> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></td></tr>""", ) self.assertHTMLEqual( p.as_div(), '<ul class="errorlist nonfield"><li>(Hidden field last_name) This field ' 'is required.</li></ul><div><label for="id_first_name">First name:</label>' '<input id="id_first_name" name="first_name" type="text" value="John" ' 'required><input id="id_last_name" name="last_name" type="hidden"></div>', ) def test_error_list_with_non_field_errors_has_correct_class(self): class Person(Form): first_name = CharField() last_name = CharField() def clean(self): raise ValidationError("Generic validation error") p = Person({"first_name": "John", "last_name": "Lennon"}) self.assertHTMLEqual( str(p.non_field_errors()), '<ul class="errorlist nonfield"><li>Generic validation error</li></ul>', ) self.assertHTMLEqual( p.as_ul(), """<li> <ul class="errorlist nonfield"><li>Generic validation error</li></ul></li> <li><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required></li> <li><label for="id_last_name">Last name:</label> <input id="id_last_name" name="last_name" type="text" value="Lennon" required></li>""", ) self.assertHTMLEqual( p.non_field_errors().as_text(), "* Generic validation error" ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist nonfield"><li>Generic validation error</li></ul> <p><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required></p> <p><label for="id_last_name">Last name:</label> <input id="id_last_name" name="last_name" type="text" value="Lennon" required></p>""", ) self.assertHTMLEqual( p.as_table(), """ <tr><td colspan="2"><ul class="errorlist nonfield"> <li>Generic validation error</li></ul></td></tr> <tr><th><label for="id_first_name">First name:</label></th><td> <input id="id_first_name" name="first_name" type="text" value="John" required> </td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input id="id_last_name" name="last_name" type="text" value="Lennon" required> </td></tr> """, ) self.assertHTMLEqual( p.as_div(), '<ul class="errorlist nonfield"><li>Generic validation error</li></ul>' '<div><label for="id_first_name">First name:</label><input ' 'id="id_first_name" name="first_name" type="text" value="John" required>' '</div><div><label for="id_last_name">Last name:</label><input ' 'id="id_last_name" name="last_name" type="text" value="Lennon" required>' "</div>", ) def test_error_escaping(self): class TestForm(Form): hidden = CharField(widget=HiddenInput(), required=False) visible = CharField() def clean_hidden(self): raise ValidationError('Foo & "bar"!') clean_visible = clean_hidden form = TestForm({"hidden": "a", "visible": "b"}) form.is_valid() self.assertHTMLEqual( form.as_ul(), '<li><ul class="errorlist nonfield">' "<li>(Hidden field hidden) Foo &amp; &quot;bar&quot;!</li></ul></li>" '<li><ul class="errorlist"><li>Foo &amp; &quot;bar&quot;!</li></ul>' '<label for="id_visible">Visible:</label> ' '<input type="text" name="visible" value="b" id="id_visible" required>' '<input type="hidden" name="hidden" value="a" id="id_hidden"></li>', ) def test_baseform_repr(self): """ BaseForm.__repr__() should contain some basic information about the form. """ p = Person() self.assertEqual( repr(p), "<Person bound=False, valid=Unknown, " "fields=(first_name;last_name;birthday)>", ) p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"} ) self.assertEqual( repr(p), "<Person bound=True, valid=Unknown, " "fields=(first_name;last_name;birthday)>", ) p.is_valid() self.assertEqual( repr(p), "<Person bound=True, valid=True, fields=(first_name;last_name;birthday)>", ) p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "fakedate"} ) p.is_valid() self.assertEqual( repr(p), "<Person bound=True, valid=False, fields=(first_name;last_name;birthday)>", ) def test_baseform_repr_dont_trigger_validation(self): """ BaseForm.__repr__() shouldn't trigger the form validation. """ p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "fakedate"} ) repr(p) with self.assertRaises(AttributeError): p.cleaned_data self.assertFalse(p.is_valid()) self.assertEqual(p.cleaned_data, {"first_name": "John", "last_name": "Lennon"}) def test_accessing_clean(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): data = self.cleaned_data if not self.errors: data["username"] = data["username"].lower() return data f = UserForm({"username": "SirRobin", "password": "blue"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["username"], "sirrobin") def test_changing_cleaned_data_nothing_returned(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): self.cleaned_data["username"] = self.cleaned_data["username"].lower() # don't return anything f = UserForm({"username": "SirRobin", "password": "blue"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["username"], "sirrobin") def test_changing_cleaned_data_in_clean(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): data = self.cleaned_data # Return a different dict. We have not changed self.cleaned_data. return { "username": data["username"].lower(), "password": "this_is_not_a_secret", } f = UserForm({"username": "SirRobin", "password": "blue"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["username"], "sirrobin") def test_multipart_encoded_form(self): class FormWithoutFile(Form): username = CharField() class FormWithFile(Form): username = CharField() file = FileField() class FormWithImage(Form): image = ImageField() self.assertFalse(FormWithoutFile().is_multipart()) self.assertTrue(FormWithFile().is_multipart()) self.assertTrue(FormWithImage().is_multipart()) def test_html_safe(self): class SimpleForm(Form): username = CharField() form = SimpleForm() self.assertTrue(hasattr(SimpleForm, "__html__")) self.assertEqual(str(form), form.__html__()) self.assertTrue(hasattr(form["username"], "__html__")) self.assertEqual(str(form["username"]), form["username"].__html__()) def test_use_required_attribute_true(self): class MyForm(Form): use_required_attribute = True f1 = CharField(max_length=30) f2 = CharField(max_length=30, required=False) f3 = CharField(widget=Textarea) f4 = ChoiceField(choices=[("P", "Python"), ("J", "Java")]) form = MyForm() self.assertHTMLEqual( form.as_p(), '<p><label for="id_f1">F1:</label>' '<input id="id_f1" maxlength="30" name="f1" type="text" required></p>' '<p><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></p>' '<p><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10" required>' "</textarea></p>" '<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></p>", ) self.assertHTMLEqual( form.as_ul(), '<li><label for="id_f1">F1:</label> ' '<input id="id_f1" maxlength="30" name="f1" type="text" required></li>' '<li><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></li>' '<li><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10" required>' "</textarea></li>" '<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></li>", ) self.assertHTMLEqual( form.as_table(), '<tr><th><label for="id_f1">F1:</label></th>' '<td><input id="id_f1" maxlength="30" name="f1" type="text" required>' "</td></tr>" '<tr><th><label for="id_f2">F2:</label></th>' '<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>' '<tr><th><label for="id_f3">F3:</label></th>' '<td><textarea cols="40" id="id_f3" name="f3" rows="10" required>' "</textarea></td></tr>" '<tr><th><label for="id_f4">F4:</label></th><td>' '<select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></td></tr>", ) self.assertHTMLEqual( form.render(form.template_name_div), '<div><label for="id_f1">F1:</label><input id="id_f1" maxlength="30" ' 'name="f1" type="text" required></div><div><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></div><div><label ' 'for="id_f3">F3:</label><textarea cols="40" id="id_f3" name="f3" ' 'rows="10" required></textarea></div><div><label for="id_f4">F4:</label>' '<select id="id_f4" name="f4"><option value="P">Python</option>' '<option value="J">Java</option></select></div>', ) def test_use_required_attribute_false(self): class MyForm(Form): use_required_attribute = False f1 = CharField(max_length=30) f2 = CharField(max_length=30, required=False) f3 = CharField(widget=Textarea) f4 = ChoiceField(choices=[("P", "Python"), ("J", "Java")]) form = MyForm() self.assertHTMLEqual( form.as_p(), '<p><label for="id_f1">F1:</label>' '<input id="id_f1" maxlength="30" name="f1" type="text"></p>' '<p><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></p>' '<p><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></p>' '<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></p>", ) self.assertHTMLEqual( form.as_ul(), '<li><label for="id_f1">F1:</label>' '<input id="id_f1" maxlength="30" name="f1" type="text"></li>' '<li><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></li>' '<li><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></li>' '<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></li>", ) self.assertHTMLEqual( form.as_table(), '<tr><th><label for="id_f1">F1:</label></th>' '<td><input id="id_f1" maxlength="30" name="f1" type="text"></td></tr>' '<tr><th><label for="id_f2">F2:</label></th>' '<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>' '<tr><th><label for="id_f3">F3:</label></th><td>' '<textarea cols="40" id="id_f3" name="f3" rows="10">' "</textarea></td></tr>" '<tr><th><label for="id_f4">F4:</label></th><td>' '<select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></td></tr>", ) self.assertHTMLEqual( form.render(form.template_name_div), '<div><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" ' 'name="f1" type="text"></div><div><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></div><div>' '<label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" ' 'rows="10"></textarea></div><div><label for="id_f4">F4:</label>' '<select id="id_f4" name="f4"><option value="P">Python</option>' '<option value="J">Java</option></select></div>', ) def test_only_hidden_fields(self): # A form with *only* hidden fields that has errors is going to be very unusual. class HiddenForm(Form): data = IntegerField(widget=HiddenInput) f = HiddenForm({}) self.assertHTMLEqual( f.as_p(), '<ul class="errorlist nonfield">' "<li>(Hidden field data) This field is required.</li></ul>\n<p> " '<input type="hidden" name="data" id="id_data"></p>', ) self.assertHTMLEqual( f.as_table(), '<tr><td colspan="2"><ul class="errorlist nonfield">' "<li>(Hidden field data) This field is required.</li></ul>" '<input type="hidden" name="data" id="id_data"></td></tr>', ) def test_field_named_data(self): class DataForm(Form): data = CharField(max_length=10) f = DataForm({"data": "xyzzy"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data, {"data": "xyzzy"}) def test_empty_data_files_multi_value_dict(self): p = Person() self.assertIsInstance(p.data, MultiValueDict) self.assertIsInstance(p.files, MultiValueDict) def test_field_deep_copy_error_messages(self): class CustomCharField(CharField): def __init__(self, **kwargs): kwargs["error_messages"] = {"invalid": "Form custom error message."} super().__init__(**kwargs) field = CustomCharField() field_copy = copy.deepcopy(field) self.assertIsInstance(field_copy, CustomCharField) self.assertIsNot(field_copy.error_messages, field.error_messages) def test_label_does_not_include_new_line(self): form = Person() field = form["first_name"] self.assertEqual( field.label_tag(), '<label for="id_first_name">First name:</label>' ) self.assertEqual( field.legend_tag(), '<legend for="id_first_name">First name:</legend>', ) @override_settings(USE_THOUSAND_SEPARATOR=True) def test_label_attrs_not_localized(self): form = Person() field = form["first_name"] self.assertHTMLEqual( field.label_tag(attrs={"number": 9999}), '<label number="9999" for="id_first_name">First name:</label>', ) self.assertHTMLEqual( field.legend_tag(attrs={"number": 9999}), '<legend number="9999" for="id_first_name">First name:</legend>', ) def test_remove_cached_field(self): class TestForm(Form): name = CharField(max_length=10) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Populate fields cache. [field for field in self] # Removed cached field. del self.fields["name"] f = TestForm({"name": "abcde"}) with self.assertRaises(KeyError): f["name"] @jinja2_tests class Jinja2FormsTestCase(FormsTestCase): pass class CustomRenderer(DjangoTemplates): form_template_name = "forms_tests/form_snippet.html" field_template_name = "forms_tests/custom_field.html" class RendererTests(SimpleTestCase): def test_default(self): form = Form() self.assertEqual(form.renderer, get_default_renderer()) def test_kwarg_instance(self): custom = CustomRenderer() form = Form(renderer=custom) self.assertEqual(form.renderer, custom) def test_kwarg_class(self): custom = CustomRenderer() form = Form(renderer=custom) self.assertEqual(form.renderer, custom) def test_attribute_instance(self): class CustomForm(Form): default_renderer = DjangoTemplates() form = CustomForm() self.assertEqual(form.renderer, CustomForm.default_renderer) def test_attribute_class(self): class CustomForm(Form): default_renderer = CustomRenderer form = CustomForm() self.assertIsInstance(form.renderer, CustomForm.default_renderer) def test_attribute_override(self): class CustomForm(Form): default_renderer = DjangoTemplates() custom = CustomRenderer() form = CustomForm(renderer=custom) self.assertEqual(form.renderer, custom) class TemplateTests(SimpleTestCase): def test_iterate_radios(self): f = FrameworkForm(auto_id="id_%s") t = Template( "{% for radio in form.language %}" '<div class="myradio">{{ radio }}</div>' "{% endfor %}" ) self.assertHTMLEqual( t.render(Context({"form": f})), '<div class="myradio"><label for="id_language_0">' '<input id="id_language_0" name="language" type="radio" value="P" ' "required> Python</label></div>" '<div class="myradio"><label for="id_language_1">' '<input id="id_language_1" name="language" type="radio" value="J" ' "required> Java</label></div>", ) def test_iterate_checkboxes(self): f = SongForm({"composers": ["J", "P"]}, auto_id=False) t = Template( "{% for checkbox in form.composers %}" '<div class="mycheckbox">{{ checkbox }}</div>' "{% endfor %}" ) self.assertHTMLEqual( t.render(Context({"form": f})), '<div class="mycheckbox"><label>' '<input checked name="composers" type="checkbox" value="J"> ' "John Lennon</label></div>" '<div class="mycheckbox"><label>' '<input checked name="composers" type="checkbox" value="P"> ' "Paul McCartney</label></div>", ) def test_templates_with_forms(self): class UserRegistration(Form): username = CharField( max_length=10, help_text=("Good luck picking a username that doesn't already exist."), ) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean(self): if ( self.cleaned_data.get("password1") and self.cleaned_data.get("password2") and self.cleaned_data["password1"] != self.cleaned_data["password2"] ): raise ValidationError("Please make sure your passwords match.") return self.cleaned_data # There is full flexibility in displaying form fields in a template. # Just pass a Form instance to the template, and use "dot" access to # refer to individual fields. However, this flexibility comes with the # responsibility of displaying all the errors, including any that might # not be associated with a particular field. t = Template( "<form>" "{{ form.username.errors.as_ul }}" "<p><label>Your username: {{ form.username }}</label></p>" "{{ form.password1.errors.as_ul }}" "<p><label>Password: {{ form.password1 }}</label></p>" "{{ form.password2.errors.as_ul }}" "<p><label>Password (again): {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Your username: " '<input type="text" name="username" maxlength="10" required></label></p>' "<p><label>Password: " '<input type="password" name="password1" required></label></p>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) f = UserRegistration({"username": "django"}, auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Your username: " '<input type="text" name="username" value="django" maxlength="10" required>' "</label></p>" '<ul class="errorlist"><li>This field is required.</li></ul><p>' "<label>Password: " '<input type="password" name="password1" required></label></p>' '<ul class="errorlist"><li>This field is required.</li></ul>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].label to output a field's label. 'label' for a field # can by specified by using the 'label' argument to a Field class. If # 'label' is not specified, Django will use the field name with # underscores converted to spaces, and the initial letter capitalized. t = Template( "<form>" "<p><label>{{ form.username.label }}: {{ form.username }}</label></p>" "<p><label>{{ form.password1.label }}: {{ form.password1 }}</label></p>" "<p><label>{{ form.password2.label }}: {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Username: " '<input type="text" name="username" maxlength="10" required></label></p>' "<p><label>Password1: " '<input type="password" name="password1" required></label></p>' "<p><label>Password2: " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].label_tag to output a field's label with a <label> # tag wrapped around it, but *only* if the given field has an "id" # attribute. Recall from above that passing the "auto_id" argument to a # Form gives each field an "id" attribute. t = Template( "<form>" "<p>{{ form.username.label_tag }} {{ form.username }}</p>" "<p>{{ form.password1.label_tag }} {{ form.password1 }}</p>" "<p>{{ form.password2.label_tag }} {{ form.password2 }}</p>" '<input type="submit" required>' "</form>" ) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p>Username: " '<input type="text" name="username" maxlength="10" required></p>' '<p>Password1: <input type="password" name="password1" required></p>' '<p>Password2: <input type="password" name="password2" required></p>' '<input type="submit" required>' "</form>", ) f = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" '<p><label for="id_username">Username:</label>' '<input id="id_username" type="text" name="username" maxlength="10" ' "required></p>" '<p><label for="id_password1">Password1:</label>' '<input type="password" name="password1" id="id_password1" required></p>' '<p><label for="id_password2">Password2:</label>' '<input type="password" name="password2" id="id_password2" required></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].legend_tag to output a field's label with a <legend> # tag wrapped around it, but *only* if the given field has an "id" # attribute. Recall from above that passing the "auto_id" argument to a # Form gives each field an "id" attribute. t = Template( "<form>" "<p>{{ form.username.legend_tag }} {{ form.username }}</p>" "<p>{{ form.password1.legend_tag }} {{ form.password1 }}</p>" "<p>{{ form.password2.legend_tag }} {{ form.password2 }}</p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p>Username: " '<input type="text" name="username" maxlength="10" required></p>' '<p>Password1: <input type="password" name="password1" required></p>' '<p>Password2: <input type="password" name="password2" required></p>' '<input type="submit" required>' "</form>", ) f = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" '<p><legend for="id_username">Username:</legend>' '<input id="id_username" type="text" name="username" maxlength="10" ' "required></p>" '<p><legend for="id_password1">Password1:</legend>' '<input type="password" name="password1" id="id_password1" required></p>' '<p><legend for="id_password2">Password2:</legend>' '<input type="password" name="password2" id="id_password2" required></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].help_text to output a field's help text. If the # given field does not have help text, nothing will be output. t = Template( "<form>" "<p>{{ form.username.label_tag }} {{ form.username }}<br>" "{{ form.username.help_text }}</p>" "<p>{{ form.password1.label_tag }} {{ form.password1 }}</p>" "<p>{{ form.password2.label_tag }} {{ form.password2 }}</p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p>Username: " '<input type="text" name="username" maxlength="10" required><br>' "Good luck picking a username that doesn&#x27;t already exist.</p>" '<p>Password1: <input type="password" name="password1" required></p>' '<p>Password2: <input type="password" name="password2" required></p>' '<input type="submit" required>' "</form>", ) self.assertEqual( Template("{{ form.password1.help_text }}").render(Context({"form": f})), "", ) # To display the errors that aren't associated with a particular field # e.g. the errors caused by Form.clean() -- use # {{ form.non_field_errors }} in the template. If used on its own, it # is displayed as a <ul> (or an empty string, if the list of errors is # empty). t = Template( "<form>" "{{ form.username.errors.as_ul }}" "<p><label>Your username: {{ form.username }}</label></p>" "{{ form.password1.errors.as_ul }}" "<p><label>Password: {{ form.password1 }}</label></p>" "{{ form.password2.errors.as_ul }}" "<p><label>Password (again): {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) f = UserRegistration( {"username": "django", "password1": "foo", "password2": "bar"}, auto_id=False, ) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Your username: " '<input type="text" name="username" value="django" maxlength="10" required>' "</label></p>" "<p><label>Password: " '<input type="password" name="password1" required></label></p>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) t = Template( "<form>" "{{ form.non_field_errors }}" "{{ form.username.errors.as_ul }}" "<p><label>Your username: {{ form.username }}</label></p>" "{{ form.password1.errors.as_ul }}" "<p><label>Password: {{ form.password1 }}</label></p>" "{{ form.password2.errors.as_ul }}" "<p><label>Password (again): {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" '<ul class="errorlist nonfield">' "<li>Please make sure your passwords match.</li></ul>" "<p><label>Your username: " '<input type="text" name="username" value="django" maxlength="10" required>' "</label></p>" "<p><label>Password: " '<input type="password" name="password1" required></label></p>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) def test_basic_processing_in_view(self): class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean(self): if ( self.cleaned_data.get("password1") and self.cleaned_data.get("password2") and self.cleaned_data["password1"] != self.cleaned_data["password2"] ): raise ValidationError("Please make sure your passwords match.") return self.cleaned_data def my_function(method, post_data): if method == "POST": form = UserRegistration(post_data, auto_id=False) else: form = UserRegistration(auto_id=False) if form.is_valid(): return "VALID: %r" % sorted(form.cleaned_data.items()) t = Template( '<form method="post">' "{{ form }}" '<input type="submit" required>' "</form>" ) return t.render(Context({"form": form})) # GET with an empty form and no errors. self.assertHTMLEqual( my_function("GET", {}), '<form method="post">' "<div>Username:" '<input type="text" name="username" maxlength="10" required></div>' "<div>Password1:" '<input type="password" name="password1" required></div>' "<div>Password2:" '<input type="password" name="password2" required></div>' '<input type="submit" required>' "</form>", ) # POST with erroneous data, a redisplayed form, with errors. self.assertHTMLEqual( my_function( "POST", { "username": "this-is-a-long-username", "password1": "foo", "password2": "bar", }, ), '<form method="post">' '<ul class="errorlist nonfield">' "<li>Please make sure your passwords match.</li></ul>" '<div>Username:<ul class="errorlist">' "<li>Ensure this value has at most 10 characters (it has 23).</li></ul>" '<input type="text" name="username" ' 'value="this-is-a-long-username" maxlength="10" required></div>' "<div>Password1:" '<input type="password" name="password1" required></div>' "<div>Password2:" '<input type="password" name="password2" required></div>' '<input type="submit" required>' "</form>", ) # POST with valid data (the success message). self.assertEqual( my_function( "POST", { "username": "adrian", "password1": "secret", "password2": "secret", }, ), "VALID: [('password1', 'secret'), ('password2', 'secret'), " "('username', 'adrian')]", ) def test_custom_field_template(self): class MyForm(Form): first_name = CharField(template_name="forms_tests/custom_field.html") f = MyForm() self.assertHTMLEqual( f.render(), '<div><label for="id_first_name">First name:</label><p>Custom Field<p>' '<input type="text" name="first_name" required id="id_first_name"></div>', ) def test_custom_field_render_template(self): class MyForm(Form): first_name = CharField() f = MyForm() self.assertHTMLEqual( f["first_name"].render(template_name="forms_tests/custom_field.html"), '<label for="id_first_name">First name:</label><p>Custom Field<p>' '<input type="text" name="first_name" required id="id_first_name">', ) class OverrideTests(SimpleTestCase): @override_settings(FORM_RENDERER="forms_tests.tests.test_forms.CustomRenderer") def test_custom_renderer_template_name(self): class Person(Form): first_name = CharField() get_default_renderer.cache_clear() t = Template("{{ form }}") html = t.render(Context({"form": Person()})) expected = """ <div class="fieldWrapper"><label for="id_first_name">First name:</label> <input type="text" name="first_name" required id="id_first_name"></div> """ self.assertHTMLEqual(html, expected) get_default_renderer.cache_clear() @override_settings(FORM_RENDERER="forms_tests.tests.test_forms.CustomRenderer") def test_custom_renderer_field_template_name(self): class Person(Form): first_name = CharField() get_default_renderer.cache_clear() t = Template("{{ form.first_name.as_field_group }}") html = t.render(Context({"form": Person()})) expected = """ <label for="id_first_name">First name:</label> <p>Custom Field<p> <input type="text" name="first_name" required id="id_first_name"> """ self.assertHTMLEqual(html, expected) get_default_renderer.cache_clear() def test_per_form_template_name(self): class Person(Form): first_name = CharField() template_name = "forms_tests/form_snippet.html" t = Template("{{ form }}") html = t.render(Context({"form": Person()})) expected = """ <div class="fieldWrapper"><label for="id_first_name">First name:</label> <input type="text" name="first_name" required id="id_first_name"></div> """ self.assertHTMLEqual(html, expected) def test_errorlist_override(self): class CustomErrorList(ErrorList): template_name = "forms_tests/error.html" class CommentForm(Form): name = CharField(max_length=50, required=False) email = EmailField() comment = CharField() data = {"email": "invalid"} f = CommentForm(data, auto_id=False, error_class=CustomErrorList) self.assertHTMLEqual( f.as_p(), '<p>Name: <input type="text" name="name" maxlength="50"></p>' '<div class="errorlist">' '<div class="error">Enter a valid email address.</div></div>' '<p>Email: <input type="email" name="email" value="invalid" required></p>' '<div class="errorlist">' '<div class="error">This field is required.</div></div>' '<p>Comment: <input type="text" name="comment" required></p>', ) def test_cyclic_context_boundfield_render(self): class FirstNameForm(Form): first_name = CharField() template_name_label = "forms_tests/cyclic_context_boundfield_render.html" f = FirstNameForm() try: f.render() except RecursionError: self.fail("Cyclic reference in BoundField.render().") def test_legend_tag(self): class CustomFrameworkForm(FrameworkForm): template_name = "forms_tests/legend_test.html" required_css_class = "required" f = CustomFrameworkForm() self.assertHTMLEqual( str(f), '<label for="id_name" class="required">Name:</label>' '<legend class="required">Language:</legend>', )
bcc021cc5fd3a23132071c93c4ffae5413da646c448da515250e4cebe114a76b
from django.template import Library, Node register = Library() class CountRenderNode(Node): count = 0 def render(self, context): self.count += 1 for v in context.flatten().values(): try: str(v) except AttributeError: pass return str(self.count) @register.tag def count_render(parser, token): return CountRenderNode()
62fefab9a6b2fdd74f75b2505ca016d6d2342c96d458e6f1779d413fa98a4df9
import importlib import inspect import os import re import sys import tempfile import threading from io import StringIO from pathlib import Path from unittest import mock, skipIf, skipUnless from asgiref.sync import async_to_sync, iscoroutinefunction from django.core import mail from django.core.files.uploadedfile import SimpleUploadedFile from django.db import DatabaseError, connection from django.http import Http404, HttpRequest, HttpResponse from django.shortcuts import render from django.template import TemplateDoesNotExist from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.utils import LoggingCaptureMixin from django.urls import path, reverse from django.urls.converters import IntConverter from django.utils.functional import SimpleLazyObject from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import mark_safe from django.utils.version import PY311 from django.views.debug import ( CallableSettingWrapper, ExceptionCycleWarning, ExceptionReporter, ) from django.views.debug import Path as DebugPath from django.views.debug import ( SafeExceptionReporterFilter, default_urlconf, get_default_exception_reporter_filter, technical_404_response, technical_500_response, ) from django.views.decorators.debug import sensitive_post_parameters, sensitive_variables from ..views import ( async_sensitive_view, custom_exception_reporter_filter_view, index_page, multivalue_dict_key_error, non_sensitive_view, paranoid_view, sensitive_args_function_caller, sensitive_kwargs_function_caller, sensitive_method_view, sensitive_view, ) class User: def __str__(self): return "jacob" class WithoutEmptyPathUrls: urlpatterns = [path("url/", index_page, name="url")] class CallableSettingWrapperTests(SimpleTestCase): """Unittests for CallableSettingWrapper""" def test_repr(self): class WrappedCallable: def __repr__(self): return "repr from the wrapped callable" def __call__(self): pass actual = repr(CallableSettingWrapper(WrappedCallable())) self.assertEqual(actual, "repr from the wrapped callable") @override_settings(DEBUG=True, ROOT_URLCONF="view_tests.urls") class DebugViewTests(SimpleTestCase): def test_files(self): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/raises/") self.assertEqual(response.status_code, 500) data = { "file_data.txt": SimpleUploadedFile("file_data.txt", b"haha"), } with self.assertLogs("django.request", "ERROR"): response = self.client.post("/raises/", data) self.assertContains(response, "file_data.txt", status_code=500) self.assertNotContains(response, "haha", status_code=500) def test_400(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs("django.security", "WARNING"): response = self.client.get("/raises400/") self.assertContains(response, '<div class="context" id="', status_code=400) def test_400_bad_request(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs("django.request", "WARNING") as cm: response = self.client.get("/raises400_bad_request/") self.assertContains(response, '<div class="context" id="', status_code=400) self.assertEqual( cm.records[0].getMessage(), "Malformed request syntax: /raises400_bad_request/", ) # Ensure no 403.html template exists to test the default case. @override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", } ] ) def test_403(self): response = self.client.get("/raises403/") self.assertContains(response, "<h1>403 Forbidden</h1>", status_code=403) # Set up a test 403.html template. @override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "loaders": [ ( "django.template.loaders.locmem.Loader", { "403.html": ( "This is a test template for a 403 error " "({{ exception }})." ), }, ), ], }, } ] ) def test_403_template(self): response = self.client.get("/raises403/") self.assertContains(response, "test template", status_code=403) self.assertContains(response, "(Insufficient Permissions).", status_code=403) def test_404(self): response = self.client.get("/raises404/") self.assertNotContains( response, '<pre class="exception_value">', status_code=404, ) self.assertContains( response, "<p>The current path, <code>not-in-urls</code>, didn’t match any " "of these.</p>", status_code=404, html=True, ) def test_404_not_in_urls(self): response = self.client.get("/not-in-urls") self.assertNotContains(response, "Raised by:", status_code=404) self.assertNotContains( response, '<pre class="exception_value">', status_code=404, ) self.assertContains( response, "Django tried these URL patterns", status_code=404 ) self.assertContains( response, "<p>The current path, <code>not-in-urls</code>, didn’t match any " "of these.</p>", status_code=404, html=True, ) # Pattern and view name of a RegexURLPattern appear. self.assertContains( response, r"^regex-post/(?P&lt;pk&gt;[0-9]+)/$", status_code=404 ) self.assertContains(response, "[name='regex-post']", status_code=404) # Pattern and view name of a RoutePattern appear. self.assertContains(response, r"path-post/&lt;int:pk&gt;/", status_code=404) self.assertContains(response, "[name='path-post']", status_code=404) @override_settings(ROOT_URLCONF=WithoutEmptyPathUrls) def test_404_empty_path_not_in_urls(self): response = self.client.get("/") self.assertContains( response, "<p>The empty path didn’t match any of these.</p>", status_code=404, html=True, ) def test_technical_404(self): response = self.client.get("/technical404/") self.assertContains( response, '<pre class="exception_value">Testing technical 404.</pre>', status_code=404, html=True, ) self.assertContains(response, "Raised by:", status_code=404) self.assertContains( response, "<td>view_tests.views.technical404</td>", status_code=404, ) self.assertContains( response, "<p>The current path, <code>technical404/</code>, matched the " "last one.</p>", status_code=404, html=True, ) def test_classbased_technical_404(self): response = self.client.get("/classbased404/") self.assertContains( response, "<th>Raised by:</th><td>view_tests.views.Http404View</td>", status_code=404, html=True, ) def test_technical_500(self): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/raises500/") self.assertContains( response, "<th>Raised during:</th><td>view_tests.views.raises500</td>", status_code=500, html=True, ) with self.assertLogs("django.request", "ERROR"): response = self.client.get("/raises500/", headers={"accept": "text/plain"}) self.assertContains( response, "Raised during: view_tests.views.raises500", status_code=500, ) def test_classbased_technical_500(self): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/classbased500/") self.assertContains( response, "<th>Raised during:</th><td>view_tests.views.Raises500View</td>", status_code=500, html=True, ) with self.assertLogs("django.request", "ERROR"): response = self.client.get( "/classbased500/", headers={"accept": "text/plain"} ) self.assertContains( response, "Raised during: view_tests.views.Raises500View", status_code=500, ) def test_non_l10ned_numeric_ids(self): """ Numeric IDs and fancy traceback context blocks line numbers shouldn't be localized. """ with self.settings(DEBUG=True): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/raises500/") # We look for a HTML fragment of the form # '<div class="context" id="c38123208">', # not '<div class="context" id="c38,123,208"'. self.assertContains(response, '<div class="context" id="', status_code=500) match = re.search( b'<div class="context" id="(?P<id>[^"]+)">', response.content ) self.assertIsNotNone(match) id_repr = match["id"] self.assertFalse( re.search(b"[^c0-9]", id_repr), "Numeric IDs in debug response HTML page shouldn't be localized " "(value: %s)." % id_repr.decode(), ) def test_template_exceptions(self): with self.assertLogs("django.request", "ERROR"): try: self.client.get(reverse("template_exception")) except Exception: raising_loc = inspect.trace()[-1][-2][0].strip() self.assertNotEqual( raising_loc.find('raise Exception("boom")'), -1, "Failed to find 'raise Exception' in last frame of " "traceback, instead found: %s" % raising_loc, ) @skipIf( sys.platform == "win32", "Raises OSError instead of TemplateDoesNotExist on Windows.", ) def test_safestring_in_exception(self): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/safestring_exception/") self.assertNotContains( response, "<script>alert(1);</script>", status_code=500, html=True, ) self.assertContains( response, "&lt;script&gt;alert(1);&lt;/script&gt;", count=3, status_code=500, html=True, ) def test_template_loader_postmortem(self): """Tests for not existing file""" template_name = "notfound.html" with tempfile.NamedTemporaryFile(prefix=template_name) as tmpfile: tempdir = os.path.dirname(tmpfile.name) template_path = os.path.join(tempdir, template_name) with override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [tempdir], } ] ), self.assertLogs("django.request", "ERROR"): response = self.client.get( reverse( "raises_template_does_not_exist", kwargs={"path": template_name} ) ) self.assertContains( response, "%s (Source does not exist)" % template_path, status_code=500, count=2, ) # Assert as HTML. self.assertContains( response, "<li><code>django.template.loaders.filesystem.Loader</code>: " "%s (Source does not exist)</li>" % os.path.join(tempdir, "notfound.html"), status_code=500, html=True, ) def test_no_template_source_loaders(self): """ Make sure if you don't specify a template, the debug view doesn't blow up. """ with self.assertLogs("django.request", "ERROR"): with self.assertRaises(TemplateDoesNotExist): self.client.get("/render_no_template/") @override_settings(ROOT_URLCONF="view_tests.default_urls") def test_default_urlconf_template(self): """ Make sure that the default URLconf template is shown instead of the technical 404 page, if the user has not altered their URLconf yet. """ response = self.client.get("/") self.assertContains( response, "<h1>The install worked successfully! Congratulations!</h1>" ) @override_settings(ROOT_URLCONF="view_tests.regression_21530_urls") def test_regression_21530(self): """ Regression test for bug #21530. If the admin app include is replaced with exactly one url pattern, then the technical 404 template should be displayed. The bug here was that an AttributeError caused a 500 response. """ response = self.client.get("/") self.assertContains( response, "Page not found <span>(404)</span>", status_code=404 ) def test_template_encoding(self): """ The templates are loaded directly, not via a template loader, and should be opened as utf-8 charset as is the default specified on template engines. """ with mock.patch.object(DebugPath, "open") as m: default_urlconf(None) m.assert_called_once_with(encoding="utf-8") m.reset_mock() technical_404_response(mock.MagicMock(), mock.Mock()) m.assert_called_once_with(encoding="utf-8") def test_technical_404_converter_raise_404(self): with mock.patch.object(IntConverter, "to_python", side_effect=Http404): response = self.client.get("/path-post/1/") self.assertContains(response, "Page not found", status_code=404) def test_exception_reporter_from_request(self): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/custom_reporter_class_view/") self.assertContains(response, "custom traceback text", status_code=500) @override_settings( DEFAULT_EXCEPTION_REPORTER="view_tests.views.CustomExceptionReporter" ) def test_exception_reporter_from_settings(self): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/raises500/") self.assertContains(response, "custom traceback text", status_code=500) @override_settings( DEFAULT_EXCEPTION_REPORTER="view_tests.views.TemplateOverrideExceptionReporter" ) def test_template_override_exception_reporter(self): with self.assertLogs("django.request", "ERROR"): response = self.client.get("/raises500/") self.assertContains( response, "<h1>Oh no, an error occurred!</h1>", status_code=500, html=True, ) with self.assertLogs("django.request", "ERROR"): response = self.client.get("/raises500/", headers={"accept": "text/plain"}) self.assertContains(response, "Oh dear, an error occurred!", status_code=500) class DebugViewQueriesAllowedTests(SimpleTestCase): # May need a query to initialize MySQL connection databases = {"default"} def test_handle_db_exception(self): """ Ensure the debug view works when a database exception is raised by performing an invalid query and passing the exception to the debug view. """ with connection.cursor() as cursor: try: cursor.execute("INVALID SQL") except DatabaseError: exc_info = sys.exc_info() rf = RequestFactory() response = technical_500_response(rf.get("/"), *exc_info) self.assertContains(response, "OperationalError at /", status_code=500) @override_settings( DEBUG=True, ROOT_URLCONF="view_tests.urls", # No template directories are configured, so no templates will be found. TEMPLATES=[ { "BACKEND": "django.template.backends.dummy.TemplateStrings", } ], ) class NonDjangoTemplatesDebugViewTests(SimpleTestCase): def test_400(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs("django.security", "WARNING"): response = self.client.get("/raises400/") self.assertContains(response, '<div class="context" id="', status_code=400) def test_400_bad_request(self): # When DEBUG=True, technical_500_template() is called. with self.assertLogs("django.request", "WARNING") as cm: response = self.client.get("/raises400_bad_request/") self.assertContains(response, '<div class="context" id="', status_code=400) self.assertEqual( cm.records[0].getMessage(), "Malformed request syntax: /raises400_bad_request/", ) def test_403(self): response = self.client.get("/raises403/") self.assertContains(response, "<h1>403 Forbidden</h1>", status_code=403) def test_404(self): response = self.client.get("/raises404/") self.assertEqual(response.status_code, 404) def test_template_not_found_error(self): # Raises a TemplateDoesNotExist exception and shows the debug view. url = reverse( "raises_template_does_not_exist", kwargs={"path": "notfound.html"} ) with self.assertLogs("django.request", "ERROR"): response = self.client.get(url) self.assertContains(response, '<div class="context" id="', status_code=500) class ExceptionReporterTests(SimpleTestCase): rf = RequestFactory() def test_request_and_exception(self): "A simple exception report can be generated" try: request = self.rf.get("/test_view/") request.user = User() raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML("<h1>ValueError at /test_view/</h1>", html) self.assertIn( '<pre class="exception_value">Can&#x27;t find my keys</pre>', html ) self.assertIn("<th>Request Method:</th>", html) self.assertIn("<th>Request URL:</th>", html) self.assertIn('<h3 id="user-info">USER</h3>', html) self.assertIn("<p>jacob</p>", html) self.assertIn("<th>Exception Type:</th>", html) self.assertIn("<th>Exception Value:</th>", html) self.assertIn("<h2>Traceback ", html) self.assertIn("<h2>Request information</h2>", html) self.assertNotIn("<p>Request data not supplied</p>", html) self.assertIn("<p>No POST data</p>", html) def test_no_request(self): "An exception report can be generated without request" try: raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML("<h1>ValueError</h1>", html) self.assertIn( '<pre class="exception_value">Can&#x27;t find my keys</pre>', html ) self.assertNotIn("<th>Request Method:</th>", html) self.assertNotIn("<th>Request URL:</th>", html) self.assertNotIn('<h3 id="user-info">USER</h3>', html) self.assertIn("<th>Exception Type:</th>", html) self.assertIn("<th>Exception Value:</th>", html) self.assertIn("<h2>Traceback ", html) self.assertIn("<h2>Request information</h2>", html) self.assertIn("<p>Request data not supplied</p>", html) def test_sharing_traceback(self): try: raise ValueError("Oops") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn( '<form action="https://dpaste.com/" name="pasteform" ' 'id="pasteform" method="post">', html, ) def test_eol_support(self): """The ExceptionReporter supports Unix, Windows and Macintosh EOL markers""" LINES = ["print %d" % i for i in range(1, 6)] reporter = ExceptionReporter(None, None, None, None) for newline in ["\n", "\r\n", "\r"]: fd, filename = tempfile.mkstemp(text=False) os.write(fd, (newline.join(LINES) + newline).encode()) os.close(fd) try: self.assertEqual( reporter._get_lines_from_file(filename, 3, 2), (1, LINES[1:3], LINES[3], LINES[4:]), ) finally: os.unlink(filename) def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML("<h1>Report at /test_view/</h1>", html) self.assertIn( '<pre class="exception_value">No exception message supplied</pre>', html ) self.assertIn("<th>Request Method:</th>", html) self.assertIn("<th>Request URL:</th>", html) self.assertNotIn("<th>Exception Type:</th>", html) self.assertNotIn("<th>Exception Value:</th>", html) self.assertNotIn("<h2>Traceback ", html) self.assertIn("<h2>Request information</h2>", html) self.assertNotIn("<p>Request data not supplied</p>", html) def test_suppressed_context(self): try: try: raise RuntimeError("Can't find my keys") except RuntimeError: raise ValueError("Can't find my keys") from None except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML("<h1>ValueError</h1>", html) self.assertIn( '<pre class="exception_value">Can&#x27;t find my keys</pre>', html ) self.assertIn("<th>Exception Type:</th>", html) self.assertIn("<th>Exception Value:</th>", html) self.assertIn("<h2>Traceback ", html) self.assertIn("<h2>Request information</h2>", html) self.assertIn("<p>Request data not supplied</p>", html) self.assertNotIn("During handling of the above exception", html) def test_innermost_exception_without_traceback(self): try: try: raise RuntimeError("Oops") except Exception as exc: new_exc = RuntimeError("My context") exc.__context__ = new_exc raise except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() self.assertEqual(len(frames), 2) html = reporter.get_traceback_html() self.assertInHTML("<h1>RuntimeError</h1>", html) self.assertIn('<pre class="exception_value">Oops</pre>', html) self.assertIn("<th>Exception Type:</th>", html) self.assertIn("<th>Exception Value:</th>", html) self.assertIn("<h2>Traceback ", html) self.assertIn("<h2>Request information</h2>", html) self.assertIn("<p>Request data not supplied</p>", html) self.assertIn( "During handling of the above exception (My context), another " "exception occurred", html, ) self.assertInHTML('<li class="frame user">None</li>', html) self.assertIn("Traceback (most recent call last):\n None", html) text = reporter.get_traceback_text() self.assertIn("Exception Type: RuntimeError", text) self.assertIn("Exception Value: Oops", text) self.assertIn("Traceback (most recent call last):\n None", text) self.assertIn( "During handling of the above exception (My context), another " "exception occurred", text, ) @skipUnless(PY311, "Exception notes were added in Python 3.11.") def test_exception_with_notes(self): request = self.rf.get("/test_view/") try: try: raise RuntimeError("Oops") except Exception as err: err.add_note("First Note") err.add_note("Second Note") err.add_note(mark_safe("<script>alert(1);</script>")) raise err except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn( '<pre class="exception_value">Oops\nFirst Note\nSecond Note\n' "&lt;script&gt;alert(1);&lt;/script&gt;</pre>", html, ) self.assertIn( "Exception Value: Oops\nFirst Note\nSecond Note\n" "&lt;script&gt;alert(1);&lt;/script&gt;", html, ) text = reporter.get_traceback_text() self.assertIn( "Exception Value: Oops\nFirst Note\nSecond Note\n" "<script>alert(1);</script>", text, ) def test_mid_stack_exception_without_traceback(self): try: try: raise RuntimeError("Inner Oops") except Exception as exc: new_exc = RuntimeError("My context") new_exc.__context__ = exc raise RuntimeError("Oops") from new_exc except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML("<h1>RuntimeError</h1>", html) self.assertIn('<pre class="exception_value">Oops</pre>', html) self.assertIn("<th>Exception Type:</th>", html) self.assertIn("<th>Exception Value:</th>", html) self.assertIn("<h2>Traceback ", html) self.assertInHTML('<li class="frame user">Traceback: None</li>', html) self.assertIn( "During handling of the above exception (Inner Oops), another " "exception occurred:\n Traceback: None", html, ) text = reporter.get_traceback_text() self.assertIn("Exception Type: RuntimeError", text) self.assertIn("Exception Value: Oops", text) self.assertIn("Traceback (most recent call last):", text) self.assertIn( "During handling of the above exception (Inner Oops), another " "exception occurred:\n Traceback: None", text, ) def test_reporting_of_nested_exceptions(self): request = self.rf.get("/test_view/") try: try: raise AttributeError(mark_safe("<p>Top level</p>")) except AttributeError as explicit: try: raise ValueError(mark_safe("<p>Second exception</p>")) from explicit except ValueError: raise IndexError(mark_safe("<p>Final exception</p>")) except Exception: # Custom exception handler, just pass it into ExceptionReporter exc_type, exc_value, tb = sys.exc_info() explicit_exc = ( "The above exception ({0}) was the direct cause of the following exception:" ) implicit_exc = ( "During handling of the above exception ({0}), another exception occurred:" ) reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() # Both messages are twice on page -- one rendered as html, # one as plain text (for pastebin) self.assertEqual( 2, html.count(explicit_exc.format("&lt;p&gt;Top level&lt;/p&gt;")) ) self.assertEqual( 2, html.count(implicit_exc.format("&lt;p&gt;Second exception&lt;/p&gt;")) ) self.assertEqual(10, html.count("&lt;p&gt;Final exception&lt;/p&gt;")) text = reporter.get_traceback_text() self.assertIn(explicit_exc.format("<p>Top level</p>"), text) self.assertIn(implicit_exc.format("<p>Second exception</p>"), text) self.assertEqual(3, text.count("<p>Final exception</p>")) @skipIf( sys._xoptions.get("no_debug_ranges", False) or os.environ.get("PYTHONNODEBUGRANGES", False), "Fine-grained error locations are disabled.", ) @skipUnless(PY311, "Fine-grained error locations were added in Python 3.11.") def test_highlight_error_position(self): request = self.rf.get("/test_view/") try: try: raise AttributeError("Top level") except AttributeError as explicit: try: raise ValueError(mark_safe("<p>2nd exception</p>")) from explicit except ValueError: raise IndexError("Final exception") except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn( "<pre> raise AttributeError(&quot;Top level&quot;)\n" " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre>", html, ) self.assertIn( "<pre> raise ValueError(mark_safe(" "&quot;&lt;p&gt;2nd exception&lt;/p&gt;&quot;)) from explicit\n" " " "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre>", html, ) self.assertIn( "<pre> raise IndexError(&quot;Final exception&quot;)\n" " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre>", html, ) # Pastebin. self.assertIn( " raise AttributeError(&quot;Top level&quot;)\n" " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", html, ) self.assertIn( " raise ValueError(mark_safe(" "&quot;&lt;p&gt;2nd exception&lt;/p&gt;&quot;)) from explicit\n" " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", html, ) self.assertIn( " raise IndexError(&quot;Final exception&quot;)\n" " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", html, ) # Text traceback. text = reporter.get_traceback_text() self.assertIn( ' raise AttributeError("Top level")\n' " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", text, ) self.assertIn( ' raise ValueError(mark_safe("<p>2nd exception</p>")) from explicit\n' " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", text, ) self.assertIn( ' raise IndexError("Final exception")\n' " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n", text, ) def test_reporting_frames_without_source(self): try: source = "def funcName():\n raise Error('Whoops')\nfuncName()" namespace = {} code = compile(source, "generated", "exec") exec(code, namespace) except Exception: exc_type, exc_value, tb = sys.exc_info() request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() last_frame = frames[-1] self.assertEqual(last_frame["context_line"], "<source code not available>") self.assertEqual(last_frame["filename"], "generated") self.assertEqual(last_frame["function"], "funcName") self.assertEqual(last_frame["lineno"], 2) html = reporter.get_traceback_html() self.assertIn( '<span class="fname">generated</span>, line 2, in funcName', html, ) self.assertIn( '<code class="fname">generated</code>, line 2, in funcName', html, ) self.assertIn( '"generated", line 2, in funcName\n &lt;source code not available&gt;', html, ) text = reporter.get_traceback_text() self.assertIn( '"generated", line 2, in funcName\n <source code not available>', text, ) def test_reporting_frames_source_not_match(self): try: source = "def funcName():\n raise Error('Whoops')\nfuncName()" namespace = {} code = compile(source, "generated", "exec") exec(code, namespace) except Exception: exc_type, exc_value, tb = sys.exc_info() with mock.patch( "django.views.debug.ExceptionReporter._get_source", return_value=["wrong source"], ): request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, exc_type, exc_value, tb) frames = reporter.get_traceback_frames() last_frame = frames[-1] self.assertEqual(last_frame["context_line"], "<source code not available>") self.assertEqual(last_frame["filename"], "generated") self.assertEqual(last_frame["function"], "funcName") self.assertEqual(last_frame["lineno"], 2) html = reporter.get_traceback_html() self.assertIn( '<span class="fname">generated</span>, line 2, in funcName', html, ) self.assertIn( '<code class="fname">generated</code>, line 2, in funcName', html, ) self.assertIn( '"generated", line 2, in funcName\n' " &lt;source code not available&gt;", html, ) text = reporter.get_traceback_text() self.assertIn( '"generated", line 2, in funcName\n <source code not available>', text, ) def test_reporting_frames_for_cyclic_reference(self): try: def test_func(): try: raise RuntimeError("outer") from RuntimeError("inner") except RuntimeError as exc: raise exc.__cause__ test_func() except Exception: exc_type, exc_value, tb = sys.exc_info() request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, exc_type, exc_value, tb) def generate_traceback_frames(*args, **kwargs): nonlocal tb_frames tb_frames = reporter.get_traceback_frames() tb_frames = None tb_generator = threading.Thread(target=generate_traceback_frames, daemon=True) msg = ( "Cycle in the exception chain detected: exception 'inner' " "encountered again." ) with self.assertWarnsMessage(ExceptionCycleWarning, msg): tb_generator.start() tb_generator.join(timeout=5) if tb_generator.is_alive(): # tb_generator is a daemon that runs until the main thread/process # exits. This is resource heavy when running the full test suite. # Setting the following values to None makes # reporter.get_traceback_frames() exit early. exc_value.__traceback__ = exc_value.__context__ = exc_value.__cause__ = None tb_generator.join() self.fail("Cyclic reference in Exception Reporter.get_traceback_frames()") if tb_frames is None: # can happen if the thread generating traceback got killed # or exception while generating the traceback self.fail("Traceback generation failed") last_frame = tb_frames[-1] self.assertIn("raise exc.__cause__", last_frame["context_line"]) self.assertEqual(last_frame["filename"], __file__) self.assertEqual(last_frame["function"], "test_func") def test_request_and_message(self): "A message can be provided in addition to a request" request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, None, "I'm a little teapot", None) html = reporter.get_traceback_html() self.assertInHTML("<h1>Report at /test_view/</h1>", html) self.assertIn( '<pre class="exception_value">I&#x27;m a little teapot</pre>', html ) self.assertIn("<th>Request Method:</th>", html) self.assertIn("<th>Request URL:</th>", html) self.assertNotIn("<th>Exception Type:</th>", html) self.assertNotIn("<th>Exception Value:</th>", html) self.assertIn("<h2>Traceback ", html) self.assertIn("<h2>Request information</h2>", html) self.assertNotIn("<p>Request data not supplied</p>", html) def test_message_only(self): reporter = ExceptionReporter(None, None, "I'm a little teapot", None) html = reporter.get_traceback_html() self.assertInHTML("<h1>Report</h1>", html) self.assertIn( '<pre class="exception_value">I&#x27;m a little teapot</pre>', html ) self.assertNotIn("<th>Request Method:</th>", html) self.assertNotIn("<th>Request URL:</th>", html) self.assertNotIn("<th>Exception Type:</th>", html) self.assertNotIn("<th>Exception Value:</th>", html) self.assertIn("<h2>Traceback ", html) self.assertIn("<h2>Request information</h2>", html) self.assertIn("<p>Request data not supplied</p>", html) def test_non_utf8_values_handling(self): "Non-UTF-8 exceptions/values should not make the output generation choke." try: class NonUtf8Output(Exception): def __repr__(self): return b"EXC\xe9EXC" somevar = b"VAL\xe9VAL" # NOQA raise NonUtf8Output() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn("VAL\\xe9VAL", html) self.assertIn("EXC\\xe9EXC", html) def test_local_variable_escaping(self): """Safe strings in local variables are escaped.""" try: local = mark_safe("<p>Local variable</p>") raise ValueError(local) except Exception: exc_type, exc_value, tb = sys.exc_info() html = ExceptionReporter(None, exc_type, exc_value, tb).get_traceback_html() self.assertIn( '<td class="code"><pre>&#x27;&lt;p&gt;Local variable&lt;/p&gt;&#x27;</pre>' "</td>", html, ) def test_unprintable_values_handling(self): "Unprintable values should not make the output generation choke." try: class OomOutput: def __repr__(self): raise MemoryError("OOM") oomvalue = OomOutput() # NOQA raise ValueError() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn('<td class="code"><pre>Error in formatting', html) def test_too_large_values_handling(self): "Large values should not create a large HTML." large = 256 * 1024 repr_of_str_adds = len(repr("")) try: class LargeOutput: def __repr__(self): return repr("A" * large) largevalue = LargeOutput() # NOQA raise ValueError() except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertEqual(len(html) // 1024 // 128, 0) # still fit in 128Kb self.assertIn( "&lt;trimmed %d bytes string&gt;" % (large + repr_of_str_adds,), html ) def test_encoding_error(self): """ A UnicodeError displays a portion of the problematic string. HTML in safe strings is escaped. """ try: mark_safe("abcdefghijkl<p>mnὀp</p>qrstuwxyz").encode("ascii") except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertIn("<h2>Unicode error hint</h2>", html) self.assertIn("The string that could not be encoded/decoded was: ", html) self.assertIn("<strong>&lt;p&gt;mnὀp&lt;/p&gt;</strong>", html) def test_unfrozen_importlib(self): """ importlib is not a frozen app, but its loader thinks it's frozen which results in an ImportError. Refs #21443. """ try: request = self.rf.get("/test_view/") importlib.import_module("abc.def.invalid.name") except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML("<h1>ModuleNotFoundError at /test_view/</h1>", html) def test_ignore_traceback_evaluation_exceptions(self): """ Don't trip over exceptions generated by crafted objects when evaluating them while cleansing (#24455). """ class BrokenEvaluation(Exception): pass def broken_setup(): raise BrokenEvaluation request = self.rf.get("/test_view/") broken_lazy = SimpleLazyObject(broken_setup) try: bool(broken_lazy) except BrokenEvaluation: exc_type, exc_value, tb = sys.exc_info() self.assertIn( "BrokenEvaluation", ExceptionReporter(request, exc_type, exc_value, tb).get_traceback_html(), "Evaluation exception reason not mentioned in traceback", ) @override_settings(ALLOWED_HOSTS="example.com") def test_disallowed_host(self): "An exception report can be generated even for a disallowed host." request = self.rf.get("/", headers={"host": "evil.com"}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertIn("http://evil.com/", html) def test_request_with_items_key(self): """ An exception report can be generated for requests with 'items' in request GET, POST, FILES, or COOKIES QueryDicts. """ value = '<td>items</td><td class="code"><pre>&#x27;Oops&#x27;</pre></td>' # GET request = self.rf.get("/test_view/?items=Oops") reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML(value, html) # POST request = self.rf.post("/test_view/", data={"items": "Oops"}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML(value, html) # FILES fp = StringIO("filecontent") request = self.rf.post("/test_view/", data={"name": "filename", "items": fp}) reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML( '<td>items</td><td class="code"><pre>&lt;InMemoryUploadedFile: ' "items (application/octet-stream)&gt;</pre></td>", html, ) # COOKIES rf = RequestFactory() rf.cookies["items"] = "Oops" request = rf.get("/test_view/") reporter = ExceptionReporter(request, None, None, None) html = reporter.get_traceback_html() self.assertInHTML( '<td>items</td><td class="code"><pre>&#x27;Oops&#x27;</pre></td>', html ) def test_exception_fetching_user(self): """ The error page can be rendered if the current user can't be retrieved (such as when the database is unavailable). """ class ExceptionUser: def __str__(self): raise Exception() request = self.rf.get("/test_view/") request.user = ExceptionUser() try: raise ValueError("Oops") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) html = reporter.get_traceback_html() self.assertInHTML("<h1>ValueError at /test_view/</h1>", html) self.assertIn('<pre class="exception_value">Oops</pre>', html) self.assertIn('<h3 id="user-info">USER</h3>', html) self.assertIn("<p>[unable to retrieve the current user]</p>", html) text = reporter.get_traceback_text() self.assertIn("USER: [unable to retrieve the current user]", text) def test_template_encoding(self): """ The templates are loaded directly, not via a template loader, and should be opened as utf-8 charset as is the default specified on template engines. """ reporter = ExceptionReporter(None, None, None, None) with mock.patch.object(DebugPath, "open") as m: reporter.get_traceback_html() m.assert_called_once_with(encoding="utf-8") m.reset_mock() reporter.get_traceback_text() m.assert_called_once_with(encoding="utf-8") @override_settings(ALLOWED_HOSTS=["example.com"]) def test_get_raw_insecure_uri(self): factory = RequestFactory(headers={"host": "evil.com"}) tests = [ ("////absolute-uri", "http://evil.com//absolute-uri"), ("/?foo=bar", "http://evil.com/?foo=bar"), ("/path/with:colons", "http://evil.com/path/with:colons"), ] for url, expected in tests: with self.subTest(url=url): request = factory.get(url) reporter = ExceptionReporter(request, None, None, None) self.assertEqual(reporter._get_raw_insecure_uri(), expected) class PlainTextReportTests(SimpleTestCase): rf = RequestFactory() def test_request_and_exception(self): "A simple exception report can be generated" try: request = self.rf.get("/test_view/") request.user = User() raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn("ValueError at /test_view/", text) self.assertIn("Can't find my keys", text) self.assertIn("Request Method:", text) self.assertIn("Request URL:", text) self.assertIn("USER: jacob", text) self.assertIn("Exception Type:", text) self.assertIn("Exception Value:", text) self.assertIn("Traceback (most recent call last):", text) self.assertIn("Request information:", text) self.assertNotIn("Request data not supplied", text) def test_no_request(self): "An exception report can be generated without request" try: raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn("ValueError", text) self.assertIn("Can't find my keys", text) self.assertNotIn("Request Method:", text) self.assertNotIn("Request URL:", text) self.assertNotIn("USER:", text) self.assertIn("Exception Type:", text) self.assertIn("Exception Value:", text) self.assertIn("Traceback (most recent call last):", text) self.assertIn("Request data not supplied", text) def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, None, None, None) reporter.get_traceback_text() def test_request_and_message(self): "A message can be provided in addition to a request" request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(DEBUG=True) def test_template_exception(self): request = self.rf.get("/test_view/") try: render(request, "debug/template_error.html") except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() templ_path = Path( Path(__file__).parents[1], "templates", "debug", "template_error.html" ) self.assertIn( "Template error:\n" "In template %(path)s, error at line 2\n" " 'cycle' tag requires at least two arguments\n" " 1 : Template with error:\n" " 2 : {%% cycle %%} \n" " 3 : " % {"path": templ_path}, text, ) def test_request_with_items_key(self): """ An exception report can be generated for requests with 'items' in request GET, POST, FILES, or COOKIES QueryDicts. """ # GET request = self.rf.get("/test_view/?items=Oops") reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # POST request = self.rf.post("/test_view/", data={"items": "Oops"}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # FILES fp = StringIO("filecontent") request = self.rf.post("/test_view/", data={"name": "filename", "items": fp}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = <InMemoryUploadedFile:", text) # COOKIES rf = RequestFactory() rf.cookies["items"] = "Oops" request = rf.get("/test_view/") reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) def test_message_only(self): reporter = ExceptionReporter(None, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(ALLOWED_HOSTS="example.com") def test_disallowed_host(self): "An exception report can be generated even for a disallowed host." request = self.rf.get("/", headers={"host": "evil.com"}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("http://evil.com/", text) class ExceptionReportTestMixin: # Mixin used in the ExceptionReporterFilterTests and # AjaxResponseExceptionReporterFilter tests below breakfast_data = { "sausage-key": "sausage-value", "baked-beans-key": "baked-beans-value", "hash-brown-key": "hash-brown-value", "bacon-key": "bacon-value", } def verify_unsafe_response( self, view, check_for_vars=True, check_for_POST_params=True ): """ Asserts that potentially sensitive info are displayed in the response. """ request = self.rf.post("/some_url/", self.breakfast_data) if iscoroutinefunction(view): response = async_to_sync(view)(request) else: response = view(request) if check_for_vars: # All variables are shown. self.assertContains(response, "cooked_eggs", status_code=500) self.assertContains(response, "scrambled", status_code=500) self.assertContains(response, "sauce", status_code=500) self.assertContains(response, "worcestershire", status_code=500) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters are shown. self.assertContains(response, k, status_code=500) self.assertContains(response, v, status_code=500) def verify_safe_response( self, view, check_for_vars=True, check_for_POST_params=True ): """ Asserts that certain sensitive info are not displayed in the response. """ request = self.rf.post("/some_url/", self.breakfast_data) if iscoroutinefunction(view): response = async_to_sync(view)(request) else: response = view(request) if check_for_vars: # Non-sensitive variable's name and value are shown. self.assertContains(response, "cooked_eggs", status_code=500) self.assertContains(response, "scrambled", status_code=500) # Sensitive variable's name is shown but not its value. self.assertContains(response, "sauce", status_code=500) self.assertNotContains(response, "worcestershire", status_code=500) if check_for_POST_params: for k in self.breakfast_data: # All POST parameters' names are shown. self.assertContains(response, k, status_code=500) # Non-sensitive POST parameters' values are shown. self.assertContains(response, "baked-beans-value", status_code=500) self.assertContains(response, "hash-brown-value", status_code=500) # Sensitive POST parameters' values are not shown. self.assertNotContains(response, "sausage-value", status_code=500) self.assertNotContains(response, "bacon-value", status_code=500) def verify_paranoid_response( self, view, check_for_vars=True, check_for_POST_params=True ): """ Asserts that no variables or POST parameters are displayed in the response. """ request = self.rf.post("/some_url/", self.breakfast_data) response = view(request) if check_for_vars: # Show variable names but not their values. self.assertContains(response, "cooked_eggs", status_code=500) self.assertNotContains(response, "scrambled", status_code=500) self.assertContains(response, "sauce", status_code=500) self.assertNotContains(response, "worcestershire", status_code=500) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters' names are shown. self.assertContains(response, k, status_code=500) # No POST parameters' values are shown. self.assertNotContains(response, v, status_code=500) def verify_unsafe_email(self, view, check_for_POST_params=True): """ Asserts that potentially sensitive info are displayed in the email report. """ with self.settings(ADMINS=[("Admin", "[email protected]")]): mail.outbox = [] # Empty outbox request = self.rf.post("/some_url/", self.breakfast_data) if iscoroutinefunction(view): async_to_sync(view)(request) else: view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body_plain = str(email.body) self.assertNotIn("cooked_eggs", body_plain) self.assertNotIn("scrambled", body_plain) self.assertNotIn("sauce", body_plain) self.assertNotIn("worcestershire", body_plain) # Frames vars are shown in html email reports. body_html = str(email.alternatives[0][0]) self.assertIn("cooked_eggs", body_html) self.assertIn("scrambled", body_html) self.assertIn("sauce", body_html) self.assertIn("worcestershire", body_html) if check_for_POST_params: for k, v in self.breakfast_data.items(): # All POST parameters are shown. self.assertIn(k, body_plain) self.assertIn(v, body_plain) self.assertIn(k, body_html) self.assertIn(v, body_html) def verify_safe_email(self, view, check_for_POST_params=True): """ Asserts that certain sensitive info are not displayed in the email report. """ with self.settings(ADMINS=[("Admin", "[email protected]")]): mail.outbox = [] # Empty outbox request = self.rf.post("/some_url/", self.breakfast_data) if iscoroutinefunction(view): async_to_sync(view)(request) else: view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body_plain = str(email.body) self.assertNotIn("cooked_eggs", body_plain) self.assertNotIn("scrambled", body_plain) self.assertNotIn("sauce", body_plain) self.assertNotIn("worcestershire", body_plain) # Frames vars are shown in html email reports. body_html = str(email.alternatives[0][0]) self.assertIn("cooked_eggs", body_html) self.assertIn("scrambled", body_html) self.assertIn("sauce", body_html) self.assertNotIn("worcestershire", body_html) if check_for_POST_params: for k in self.breakfast_data: # All POST parameters' names are shown. self.assertIn(k, body_plain) # Non-sensitive POST parameters' values are shown. self.assertIn("baked-beans-value", body_plain) self.assertIn("hash-brown-value", body_plain) self.assertIn("baked-beans-value", body_html) self.assertIn("hash-brown-value", body_html) # Sensitive POST parameters' values are not shown. self.assertNotIn("sausage-value", body_plain) self.assertNotIn("bacon-value", body_plain) self.assertNotIn("sausage-value", body_html) self.assertNotIn("bacon-value", body_html) def verify_paranoid_email(self, view): """ Asserts that no variables or POST parameters are displayed in the email report. """ with self.settings(ADMINS=[("Admin", "[email protected]")]): mail.outbox = [] # Empty outbox request = self.rf.post("/some_url/", self.breakfast_data) view(request) self.assertEqual(len(mail.outbox), 1) email = mail.outbox[0] # Frames vars are never shown in plain text email reports. body = str(email.body) self.assertNotIn("cooked_eggs", body) self.assertNotIn("scrambled", body) self.assertNotIn("sauce", body) self.assertNotIn("worcestershire", body) for k, v in self.breakfast_data.items(): # All POST parameters' names are shown. self.assertIn(k, body) # No POST parameters' values are shown. self.assertNotIn(v, body) @override_settings(ROOT_URLCONF="view_tests.urls") class ExceptionReporterFilterTests( ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase ): """ Sensitive information can be filtered out of error reports (#14614). """ rf = RequestFactory() def test_non_sensitive_request(self): """ Everything (request info and frame variables) can bee seen in the default error reports for non-sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(non_sensitive_view) self.verify_unsafe_email(non_sensitive_view) with self.settings(DEBUG=False): self.verify_unsafe_response(non_sensitive_view) self.verify_unsafe_email(non_sensitive_view) def test_sensitive_request(self): """ Sensitive POST parameters and frame variables cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_view) self.verify_unsafe_email(sensitive_view) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_view) self.verify_safe_email(sensitive_view) def test_async_sensitive_request(self): with self.settings(DEBUG=True): self.verify_unsafe_response(async_sensitive_view) self.verify_unsafe_email(async_sensitive_view) with self.settings(DEBUG=False): self.verify_safe_response(async_sensitive_view) self.verify_safe_email(async_sensitive_view) def test_paranoid_request(self): """ No POST parameters and frame variables can be seen in the default error reports for "paranoid" requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(paranoid_view) self.verify_unsafe_email(paranoid_view) with self.settings(DEBUG=False): self.verify_paranoid_response(paranoid_view) self.verify_paranoid_email(paranoid_view) def test_multivalue_dict_key_error(self): """ #21098 -- Sensitive POST parameters cannot be seen in the error reports for if request.POST['nonexistent_key'] throws an error. """ with self.settings(DEBUG=True): self.verify_unsafe_response(multivalue_dict_key_error) self.verify_unsafe_email(multivalue_dict_key_error) with self.settings(DEBUG=False): self.verify_safe_response(multivalue_dict_key_error) self.verify_safe_email(multivalue_dict_key_error) def test_custom_exception_reporter_filter(self): """ It's possible to assign an exception reporter filter to the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER. """ with self.settings(DEBUG=True): self.verify_unsafe_response(custom_exception_reporter_filter_view) self.verify_unsafe_email(custom_exception_reporter_filter_view) with self.settings(DEBUG=False): self.verify_unsafe_response(custom_exception_reporter_filter_view) self.verify_unsafe_email(custom_exception_reporter_filter_view) def test_sensitive_method(self): """ The sensitive_variables decorator works with object methods. """ with self.settings(DEBUG=True): self.verify_unsafe_response( sensitive_method_view, check_for_POST_params=False ) self.verify_unsafe_email(sensitive_method_view, check_for_POST_params=False) with self.settings(DEBUG=False): self.verify_safe_response( sensitive_method_view, check_for_POST_params=False ) self.verify_safe_email(sensitive_method_view, check_for_POST_params=False) def test_sensitive_function_arguments(self): """ Sensitive variables don't leak in the sensitive_variables decorator's frame, when those variables are passed as arguments to the decorated function. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_args_function_caller) self.verify_unsafe_email(sensitive_args_function_caller) with self.settings(DEBUG=False): self.verify_safe_response( sensitive_args_function_caller, check_for_POST_params=False ) self.verify_safe_email( sensitive_args_function_caller, check_for_POST_params=False ) def test_sensitive_function_keyword_arguments(self): """ Sensitive variables don't leak in the sensitive_variables decorator's frame, when those variables are passed as keyword arguments to the decorated function. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_kwargs_function_caller) self.verify_unsafe_email(sensitive_kwargs_function_caller) with self.settings(DEBUG=False): self.verify_safe_response( sensitive_kwargs_function_caller, check_for_POST_params=False ) self.verify_safe_email( sensitive_kwargs_function_caller, check_for_POST_params=False ) def test_callable_settings(self): """ Callable settings should not be evaluated in the debug page (#21345). """ def callable_setting(): return "This should not be displayed" with self.settings(DEBUG=True, FOOBAR=callable_setting): response = self.client.get("/raises500/") self.assertNotContains( response, "This should not be displayed", status_code=500 ) def test_callable_settings_forbidding_to_set_attributes(self): """ Callable settings which forbid to set attributes should not break the debug page (#23070). """ class CallableSettingWithSlots: __slots__ = [] def __call__(self): return "This should not be displayed" with self.settings(DEBUG=True, WITH_SLOTS=CallableSettingWithSlots()): response = self.client.get("/raises500/") self.assertNotContains( response, "This should not be displayed", status_code=500 ) def test_dict_setting_with_non_str_key(self): """ A dict setting containing a non-string key should not break the debug page (#12744). """ with self.settings(DEBUG=True, FOOBAR={42: None}): response = self.client.get("/raises500/") self.assertContains(response, "FOOBAR", status_code=500) def test_sensitive_settings(self): """ The debug page should not show some sensitive settings (password, secret key, ...). """ sensitive_settings = [ "SECRET_KEY", "SECRET_KEY_FALLBACKS", "PASSWORD", "API_KEY", "AUTH_TOKEN", ] for setting in sensitive_settings: with self.settings(DEBUG=True, **{setting: "should not be displayed"}): response = self.client.get("/raises500/") self.assertNotContains( response, "should not be displayed", status_code=500 ) def test_settings_with_sensitive_keys(self): """ The debug page should filter out some sensitive information found in dict settings. """ sensitive_settings = [ "SECRET_KEY", "SECRET_KEY_FALLBACKS", "PASSWORD", "API_KEY", "AUTH_TOKEN", ] for setting in sensitive_settings: FOOBAR = { setting: "should not be displayed", "recursive": {setting: "should not be displayed"}, } with self.settings(DEBUG=True, FOOBAR=FOOBAR): response = self.client.get("/raises500/") self.assertNotContains( response, "should not be displayed", status_code=500 ) def test_cleanse_setting_basic(self): reporter_filter = SafeExceptionReporterFilter() self.assertEqual(reporter_filter.cleanse_setting("TEST", "TEST"), "TEST") self.assertEqual( reporter_filter.cleanse_setting("PASSWORD", "super_secret"), reporter_filter.cleansed_substitute, ) def test_cleanse_setting_ignore_case(self): reporter_filter = SafeExceptionReporterFilter() self.assertEqual( reporter_filter.cleanse_setting("password", "super_secret"), reporter_filter.cleansed_substitute, ) def test_cleanse_setting_recurses_in_dictionary(self): reporter_filter = SafeExceptionReporterFilter() initial = {"login": "cooper", "password": "secret"} self.assertEqual( reporter_filter.cleanse_setting("SETTING_NAME", initial), {"login": "cooper", "password": reporter_filter.cleansed_substitute}, ) def test_cleanse_setting_recurses_in_dictionary_with_non_string_key(self): reporter_filter = SafeExceptionReporterFilter() initial = {("localhost", 8000): {"login": "cooper", "password": "secret"}} self.assertEqual( reporter_filter.cleanse_setting("SETTING_NAME", initial), { ("localhost", 8000): { "login": "cooper", "password": reporter_filter.cleansed_substitute, }, }, ) def test_cleanse_setting_recurses_in_list_tuples(self): reporter_filter = SafeExceptionReporterFilter() initial = [ { "login": "cooper", "password": "secret", "apps": ( {"name": "app1", "api_key": "a06b-c462cffae87a"}, {"name": "app2", "api_key": "a9f4-f152e97ad808"}, ), "tokens": ["98b37c57-ec62-4e39", "8690ef7d-8004-4916"], }, {"SECRET_KEY": "c4d77c62-6196-4f17-a06b-c462cffae87a"}, ] cleansed = [ { "login": "cooper", "password": reporter_filter.cleansed_substitute, "apps": ( {"name": "app1", "api_key": reporter_filter.cleansed_substitute}, {"name": "app2", "api_key": reporter_filter.cleansed_substitute}, ), "tokens": reporter_filter.cleansed_substitute, }, {"SECRET_KEY": reporter_filter.cleansed_substitute}, ] self.assertEqual( reporter_filter.cleanse_setting("SETTING_NAME", initial), cleansed, ) self.assertEqual( reporter_filter.cleanse_setting("SETTING_NAME", tuple(initial)), tuple(cleansed), ) def test_request_meta_filtering(self): request = self.rf.get("/", headers={"secret-header": "super_secret"}) reporter_filter = SafeExceptionReporterFilter() self.assertEqual( reporter_filter.get_safe_request_meta(request)["HTTP_SECRET_HEADER"], reporter_filter.cleansed_substitute, ) def test_exception_report_uses_meta_filtering(self): response = self.client.get( "/raises500/", headers={"secret-header": "super_secret"} ) self.assertNotIn(b"super_secret", response.content) response = self.client.get( "/raises500/", headers={"secret-header": "super_secret", "accept": "application/json"}, ) self.assertNotIn(b"super_secret", response.content) @override_settings(SESSION_COOKIE_NAME="djangosession") def test_cleanse_session_cookie_value(self): self.client.cookies.load({"djangosession": "should not be displayed"}) response = self.client.get("/raises500/") self.assertNotContains(response, "should not be displayed", status_code=500) class CustomExceptionReporterFilter(SafeExceptionReporterFilter): cleansed_substitute = "XXXXXXXXXXXXXXXXXXXX" hidden_settings = _lazy_re_compile( "API|TOKEN|KEY|SECRET|PASS|SIGNATURE|DATABASE_URL", flags=re.I ) @override_settings( ROOT_URLCONF="view_tests.urls", DEFAULT_EXCEPTION_REPORTER_FILTER="%s.CustomExceptionReporterFilter" % __name__, ) class CustomExceptionReporterFilterTests(SimpleTestCase): def setUp(self): get_default_exception_reporter_filter.cache_clear() def tearDown(self): get_default_exception_reporter_filter.cache_clear() def test_setting_allows_custom_subclass(self): self.assertIsInstance( get_default_exception_reporter_filter(), CustomExceptionReporterFilter, ) def test_cleansed_substitute_override(self): reporter_filter = get_default_exception_reporter_filter() self.assertEqual( reporter_filter.cleanse_setting("password", "super_secret"), reporter_filter.cleansed_substitute, ) def test_hidden_settings_override(self): reporter_filter = get_default_exception_reporter_filter() self.assertEqual( reporter_filter.cleanse_setting("database_url", "super_secret"), reporter_filter.cleansed_substitute, ) class NonHTMLResponseExceptionReporterFilter( ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase ): """ Sensitive information can be filtered out of error reports. The plain text 500 debug-only error page is served when it has been detected the request doesn't accept HTML content. Don't check for (non)existence of frames vars in the traceback information section of the response content because they're not included in these error pages. Refs #14614. """ rf = RequestFactory(headers={"accept": "application/json"}) def test_non_sensitive_request(self): """ Request info can bee seen in the default error reports for non-sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(non_sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_unsafe_response(non_sensitive_view, check_for_vars=False) def test_sensitive_request(self): """ Sensitive POST parameters cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_view, check_for_vars=False) def test_async_sensitive_request(self): """ Sensitive POST parameters cannot be seen in the default error reports for sensitive requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(async_sensitive_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_safe_response(async_sensitive_view, check_for_vars=False) def test_paranoid_request(self): """ No POST parameters can be seen in the default error reports for "paranoid" requests. """ with self.settings(DEBUG=True): self.verify_unsafe_response(paranoid_view, check_for_vars=False) with self.settings(DEBUG=False): self.verify_paranoid_response(paranoid_view, check_for_vars=False) def test_custom_exception_reporter_filter(self): """ It's possible to assign an exception reporter filter to the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER. """ with self.settings(DEBUG=True): self.verify_unsafe_response( custom_exception_reporter_filter_view, check_for_vars=False ) with self.settings(DEBUG=False): self.verify_unsafe_response( custom_exception_reporter_filter_view, check_for_vars=False ) @override_settings(DEBUG=True, ROOT_URLCONF="view_tests.urls") def test_non_html_response_encoding(self): response = self.client.get( "/raises500/", headers={"accept": "application/json"} ) self.assertEqual(response.headers["Content-Type"], "text/plain; charset=utf-8") class DecoratorsTests(SimpleTestCase): def test_sensitive_variables_not_called(self): msg = ( "sensitive_variables() must be called to use it as a decorator, " "e.g., use @sensitive_variables(), not @sensitive_variables." ) with self.assertRaisesMessage(TypeError, msg): @sensitive_variables def test_func(password): pass def test_sensitive_post_parameters_not_called(self): msg = ( "sensitive_post_parameters() must be called to use it as a " "decorator, e.g., use @sensitive_post_parameters(), not " "@sensitive_post_parameters." ) with self.assertRaisesMessage(TypeError, msg): @sensitive_post_parameters def test_func(request): return index_page(request) def test_sensitive_post_parameters_http_request(self): class MyClass: @sensitive_post_parameters() def a_view(self, request): return HttpResponse() msg = ( "sensitive_post_parameters didn't receive an HttpRequest object. " "If you are decorating a classmethod, make sure to use " "@method_decorator." ) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(HttpRequest())
f8fcee4a5346be4f9ba06b318277a643b5fcf168e9721294161399b75d9d624f
import datetime import decimal import unittest from django.db import connection, models from django.db.models.functions import Cast from django.test import TestCase, ignore_warnings, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from ..models import Author, DTModel, Fan, FloatModel class CastTests(TestCase): @classmethod def setUpTestData(self): Author.objects.create(name="Bob", age=1, alias="1") def test_cast_from_value(self): numbers = Author.objects.annotate( cast_integer=Cast(models.Value("0"), models.IntegerField()) ) self.assertEqual(numbers.get().cast_integer, 0) def test_cast_from_field(self): numbers = Author.objects.annotate( cast_string=Cast("age", models.CharField(max_length=255)), ) self.assertEqual(numbers.get().cast_string, "1") def test_cast_to_char_field_without_max_length(self): numbers = Author.objects.annotate(cast_string=Cast("age", models.CharField())) self.assertEqual(numbers.get().cast_string, "1") # Silence "Truncated incorrect CHAR(1) value: 'Bob'". @ignore_warnings(module="django.db.backends.mysql.base") @skipUnlessDBFeature("supports_cast_with_precision") def test_cast_to_char_field_with_max_length(self): names = Author.objects.annotate( cast_string=Cast("name", models.CharField(max_length=1)) ) self.assertEqual(names.get().cast_string, "B") @skipUnlessDBFeature("supports_cast_with_precision") def test_cast_to_decimal_field(self): FloatModel.objects.create(f1=-1.934, f2=3.467) float_obj = FloatModel.objects.annotate( cast_f1_decimal=Cast( "f1", models.DecimalField(max_digits=8, decimal_places=2) ), cast_f2_decimal=Cast( "f2", models.DecimalField(max_digits=8, decimal_places=1) ), ).get() self.assertEqual(float_obj.cast_f1_decimal, decimal.Decimal("-1.93")) self.assertEqual(float_obj.cast_f2_decimal, decimal.Decimal("3.5")) author_obj = Author.objects.annotate( cast_alias_decimal=Cast( "alias", models.DecimalField(max_digits=8, decimal_places=2) ), ).get() self.assertEqual(author_obj.cast_alias_decimal, decimal.Decimal("1")) def test_cast_to_integer(self): for field_class in ( models.AutoField, models.BigAutoField, models.SmallAutoField, models.IntegerField, models.BigIntegerField, models.SmallIntegerField, models.PositiveBigIntegerField, models.PositiveIntegerField, models.PositiveSmallIntegerField, ): with self.subTest(field_class=field_class): numbers = Author.objects.annotate(cast_int=Cast("alias", field_class())) self.assertEqual(numbers.get().cast_int, 1) def test_cast_to_integer_foreign_key(self): numbers = Author.objects.annotate( cast_fk=Cast( models.Value("0"), models.ForeignKey(Author, on_delete=models.SET_NULL), ) ) self.assertEqual(numbers.get().cast_fk, 0) def test_cast_to_duration(self): duration = datetime.timedelta(days=1, seconds=2, microseconds=3) DTModel.objects.create(duration=duration) dtm = DTModel.objects.annotate( cast_duration=Cast("duration", models.DurationField()), cast_neg_duration=Cast(-duration, models.DurationField()), ).get() self.assertEqual(dtm.cast_duration, duration) self.assertEqual(dtm.cast_neg_duration, -duration) def test_cast_from_db_datetime_to_date(self): dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567) DTModel.objects.create(start_datetime=dt_value) dtm = DTModel.objects.annotate( start_datetime_as_date=Cast("start_datetime", models.DateField()) ).first() self.assertEqual(dtm.start_datetime_as_date, datetime.date(2018, 9, 28)) def test_cast_from_db_datetime_to_time(self): dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567) DTModel.objects.create(start_datetime=dt_value) dtm = DTModel.objects.annotate( start_datetime_as_time=Cast("start_datetime", models.TimeField()) ).first() rounded_ms = int( round(0.234567, connection.features.time_cast_precision) * 10**6 ) self.assertEqual( dtm.start_datetime_as_time, datetime.time(12, 42, 10, rounded_ms) ) def test_cast_from_db_date_to_datetime(self): dt_value = datetime.date(2018, 9, 28) DTModel.objects.create(start_date=dt_value) dtm = DTModel.objects.annotate( start_as_datetime=Cast("start_date", models.DateTimeField()) ).first() self.assertEqual( dtm.start_as_datetime, datetime.datetime(2018, 9, 28, 0, 0, 0, 0) ) def test_cast_from_db_datetime_to_date_group_by(self): author = Author.objects.create(name="John Smith", age=45) dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567) Fan.objects.create(name="Margaret", age=50, author=author, fan_since=dt_value) fans = ( Fan.objects.values("author") .annotate( fan_for_day=Cast("fan_since", models.DateField()), fans=models.Count("*"), ) .values() ) self.assertEqual(fans[0]["fan_for_day"], datetime.date(2018, 9, 28)) self.assertEqual(fans[0]["fans"], 1) def test_cast_from_python_to_date(self): today = datetime.date.today() dates = Author.objects.annotate(cast_date=Cast(today, models.DateField())) self.assertEqual(dates.get().cast_date, today) def test_cast_from_python_to_datetime(self): now = datetime.datetime.now() dates = Author.objects.annotate(cast_datetime=Cast(now, models.DateTimeField())) time_precision = datetime.timedelta( microseconds=10 ** (6 - connection.features.time_cast_precision) ) self.assertAlmostEqual(dates.get().cast_datetime, now, delta=time_precision) def test_cast_from_python(self): numbers = Author.objects.annotate( cast_float=Cast(decimal.Decimal(0.125), models.FloatField()) ) cast_float = numbers.get().cast_float self.assertIsInstance(cast_float, float) self.assertEqual(cast_float, 0.125) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL test") def test_expression_wrapped_with_parentheses_on_postgresql(self): """ The SQL for the Cast expression is wrapped with parentheses in case it's a complex expression. """ with CaptureQueriesContext(connection) as captured_queries: list( Author.objects.annotate( cast_float=Cast(models.Avg("age"), models.FloatField()), ) ) self.assertIn( '(AVG("db_functions_author"."age"))::double precision', captured_queries[0]["sql"], ) def test_cast_to_text_field(self): self.assertEqual( Author.objects.values_list( Cast("age", models.TextField()), flat=True ).get(), "1", )
af627dc0fb0ac68e7ec1813eef27338aa979213f927bf257e3d95338246797e5
""" Field classes. """ import copy import datetime import json import math import operator import os import re import uuid from decimal import Decimal, DecimalException from io import BytesIO from urllib.parse import urlsplit, urlunsplit from django.core import validators from django.core.exceptions import ValidationError from django.db.models.enums import ChoicesMeta from django.forms.boundfield import BoundField from django.forms.utils import from_current_timezone, to_current_timezone from django.forms.widgets import ( FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput, DateInput, DateTimeInput, EmailInput, FileInput, HiddenInput, MultipleHiddenInput, NullBooleanSelect, NumberInput, Select, SelectMultiple, SplitDateTimeWidget, SplitHiddenDateTimeWidget, Textarea, TextInput, TimeInput, URLInput, ) from django.utils import formats from django.utils.dateparse import parse_datetime, parse_duration from django.utils.duration import duration_string from django.utils.ipv6 import clean_ipv6_address from django.utils.regex_helper import _lazy_re_compile from django.utils.translation import gettext_lazy as _ from django.utils.translation import ngettext_lazy __all__ = ( "Field", "CharField", "IntegerField", "DateField", "TimeField", "DateTimeField", "DurationField", "RegexField", "EmailField", "FileField", "ImageField", "URLField", "BooleanField", "NullBooleanField", "ChoiceField", "MultipleChoiceField", "ComboField", "MultiValueField", "FloatField", "DecimalField", "SplitDateTimeField", "GenericIPAddressField", "FilePathField", "JSONField", "SlugField", "TypedChoiceField", "TypedMultipleChoiceField", "UUIDField", ) class Field: widget = TextInput # Default widget to use when rendering this type of Field. hidden_widget = ( HiddenInput # Default widget to use when rendering this as "hidden". ) default_validators = [] # Default set of validators # Add an 'invalid' entry to default_error_message if you want a specific # field error message not raised by the field validators. default_error_messages = { "required": _("This field is required."), } empty_values = list(validators.EMPTY_VALUES) def __init__( self, *, required=True, widget=None, label=None, initial=None, help_text="", error_messages=None, show_hidden_initial=False, validators=(), localize=False, disabled=False, label_suffix=None, ): # required -- Boolean that specifies whether the field is required. # True by default. # widget -- A Widget class, or instance of a Widget class, that should # be used for this Field when displaying it. Each Field has a # default Widget that it'll use if you don't specify this. In # most cases, the default widget is TextInput. # label -- A verbose name for this field, for use in displaying this # field in a form. By default, Django will use a "pretty" # version of the form field name, if the Field is part of a # Form. # initial -- A value to use in this Field's initial display. This value # is *not* used as a fallback if data isn't given. # help_text -- An optional string to use as "help text" for this Field. # error_messages -- An optional dictionary to override the default # messages that the field will raise. # show_hidden_initial -- Boolean that specifies if it is needed to render a # hidden widget with initial value after widget. # validators -- List of additional validators to use # localize -- Boolean that specifies if the field should be localized. # disabled -- Boolean that specifies whether the field is disabled, that # is its widget is shown in the form but not editable. # label_suffix -- Suffix to be added to the label. Overrides # form's label_suffix. self.required, self.label, self.initial = required, label, initial self.show_hidden_initial = show_hidden_initial self.help_text = help_text self.disabled = disabled self.label_suffix = label_suffix widget = widget or self.widget if isinstance(widget, type): widget = widget() else: widget = copy.deepcopy(widget) # Trigger the localization machinery if needed. self.localize = localize if self.localize: widget.is_localized = True # Let the widget know whether it should display as required. widget.is_required = self.required # Hook into self.widget_attrs() for any Field-specific HTML attributes. extra_attrs = self.widget_attrs(widget) if extra_attrs: widget.attrs.update(extra_attrs) self.widget = widget messages = {} for c in reversed(self.__class__.__mro__): messages.update(getattr(c, "default_error_messages", {})) messages.update(error_messages or {}) self.error_messages = messages self.validators = [*self.default_validators, *validators] super().__init__() def prepare_value(self, value): return value def to_python(self, value): return value def validate(self, value): if value in self.empty_values and self.required: raise ValidationError(self.error_messages["required"], code="required") def run_validators(self, value): if value in self.empty_values: return errors = [] for v in self.validators: try: v(value) except ValidationError as e: if hasattr(e, "code") and e.code in self.error_messages: e.message = self.error_messages[e.code] errors.extend(e.error_list) if errors: raise ValidationError(errors) def clean(self, value): """ Validate the given value and return its "cleaned" value as an appropriate Python object. Raise ValidationError for any errors. """ value = self.to_python(value) self.validate(value) self.run_validators(value) return value def bound_data(self, data, initial): """ Return the value that should be shown for this field on render of a bound form, given the submitted POST data for the field and the initial data, if any. For most fields, this will simply be data; FileFields need to handle it a bit differently. """ if self.disabled: return initial return data def widget_attrs(self, widget): """ Given a Widget instance (*not* a Widget class), return a dictionary of any HTML attributes that should be added to the Widget, based on this Field. """ return {} def has_changed(self, initial, data): """Return True if data differs from initial.""" # Always return False if the field is disabled since self.bound_data # always uses the initial value in this case. if self.disabled: return False try: data = self.to_python(data) if hasattr(self, "_coerce"): return self._coerce(data) != self._coerce(initial) except ValidationError: return True # For purposes of seeing whether something has changed, None is # the same as an empty string, if the data or initial value we get # is None, replace it with ''. initial_value = initial if initial is not None else "" data_value = data if data is not None else "" return initial_value != data_value def get_bound_field(self, form, field_name): """ Return a BoundField instance that will be used when accessing the form field in a template. """ return BoundField(form, self, field_name) def __deepcopy__(self, memo): result = copy.copy(self) memo[id(self)] = result result.widget = copy.deepcopy(self.widget, memo) result.error_messages = self.error_messages.copy() result.validators = self.validators[:] return result class CharField(Field): def __init__( self, *, max_length=None, min_length=None, strip=True, empty_value="", **kwargs ): self.max_length = max_length self.min_length = min_length self.strip = strip self.empty_value = empty_value super().__init__(**kwargs) if min_length is not None: self.validators.append(validators.MinLengthValidator(int(min_length))) if max_length is not None: self.validators.append(validators.MaxLengthValidator(int(max_length))) self.validators.append(validators.ProhibitNullCharactersValidator()) def to_python(self, value): """Return a string.""" if value not in self.empty_values: value = str(value) if self.strip: value = value.strip() if value in self.empty_values: return self.empty_value return value def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if self.max_length is not None and not widget.is_hidden: # The HTML attribute is maxlength, not max_length. attrs["maxlength"] = str(self.max_length) if self.min_length is not None and not widget.is_hidden: # The HTML attribute is minlength, not min_length. attrs["minlength"] = str(self.min_length) return attrs class IntegerField(Field): widget = NumberInput default_error_messages = { "invalid": _("Enter a whole number."), } re_decimal = _lazy_re_compile(r"\.0*\s*$") def __init__(self, *, max_value=None, min_value=None, step_size=None, **kwargs): self.max_value, self.min_value, self.step_size = max_value, min_value, step_size if kwargs.get("localize") and self.widget == NumberInput: # Localized number input is not well supported on most browsers kwargs.setdefault("widget", super().widget) super().__init__(**kwargs) if max_value is not None: self.validators.append(validators.MaxValueValidator(max_value)) if min_value is not None: self.validators.append(validators.MinValueValidator(min_value)) if step_size is not None: self.validators.append(validators.StepValueValidator(step_size)) def to_python(self, value): """ Validate that int() can be called on the input. Return the result of int() or None for empty values. """ value = super().to_python(value) if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) # Strip trailing decimal and zeros. try: value = int(self.re_decimal.sub("", str(value))) except (ValueError, TypeError): raise ValidationError(self.error_messages["invalid"], code="invalid") return value def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput): if self.min_value is not None: attrs["min"] = self.min_value if self.max_value is not None: attrs["max"] = self.max_value if self.step_size is not None: attrs["step"] = self.step_size return attrs class FloatField(IntegerField): default_error_messages = { "invalid": _("Enter a number."), } def to_python(self, value): """ Validate that float() can be called on the input. Return the result of float() or None for empty values. """ value = super(IntegerField, self).to_python(value) if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) try: value = float(value) except (ValueError, TypeError): raise ValidationError(self.error_messages["invalid"], code="invalid") return value def validate(self, value): super().validate(value) if value in self.empty_values: return if not math.isfinite(value): raise ValidationError(self.error_messages["invalid"], code="invalid") def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput) and "step" not in widget.attrs: if self.step_size is not None: step = str(self.step_size) else: step = "any" attrs.setdefault("step", step) return attrs class DecimalField(IntegerField): default_error_messages = { "invalid": _("Enter a number."), } def __init__( self, *, max_value=None, min_value=None, max_digits=None, decimal_places=None, **kwargs, ): self.max_digits, self.decimal_places = max_digits, decimal_places super().__init__(max_value=max_value, min_value=min_value, **kwargs) self.validators.append(validators.DecimalValidator(max_digits, decimal_places)) def to_python(self, value): """ Validate that the input is a decimal number. Return a Decimal instance or None for empty values. Ensure that there are no more than max_digits in the number and no more than decimal_places digits after the decimal point. """ if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) try: value = Decimal(str(value)) except DecimalException: raise ValidationError(self.error_messages["invalid"], code="invalid") return value def validate(self, value): super().validate(value) if value in self.empty_values: return if not value.is_finite(): raise ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput) and "step" not in widget.attrs: if self.decimal_places is not None: # Use exponential notation for small values since they might # be parsed as 0 otherwise. ref #20765 step = str(Decimal(1).scaleb(-self.decimal_places)).lower() else: step = "any" attrs.setdefault("step", step) return attrs class BaseTemporalField(Field): def __init__(self, *, input_formats=None, **kwargs): super().__init__(**kwargs) if input_formats is not None: self.input_formats = input_formats def to_python(self, value): value = value.strip() # Try to strptime against each input format. for format in self.input_formats: try: return self.strptime(value, format) except (ValueError, TypeError): continue raise ValidationError(self.error_messages["invalid"], code="invalid") def strptime(self, value, format): raise NotImplementedError("Subclasses must define this method.") class DateField(BaseTemporalField): widget = DateInput input_formats = formats.get_format_lazy("DATE_INPUT_FORMATS") default_error_messages = { "invalid": _("Enter a valid date."), } def to_python(self, value): """ Validate that the input can be converted to a date. Return a Python datetime.date object. """ if value in self.empty_values: return None if isinstance(value, datetime.datetime): return value.date() if isinstance(value, datetime.date): return value return super().to_python(value) def strptime(self, value, format): return datetime.datetime.strptime(value, format).date() class TimeField(BaseTemporalField): widget = TimeInput input_formats = formats.get_format_lazy("TIME_INPUT_FORMATS") default_error_messages = {"invalid": _("Enter a valid time.")} def to_python(self, value): """ Validate that the input can be converted to a time. Return a Python datetime.time object. """ if value in self.empty_values: return None if isinstance(value, datetime.time): return value return super().to_python(value) def strptime(self, value, format): return datetime.datetime.strptime(value, format).time() class DateTimeFormatsIterator: def __iter__(self): yield from formats.get_format("DATETIME_INPUT_FORMATS") yield from formats.get_format("DATE_INPUT_FORMATS") class DateTimeField(BaseTemporalField): widget = DateTimeInput input_formats = DateTimeFormatsIterator() default_error_messages = { "invalid": _("Enter a valid date/time."), } def prepare_value(self, value): if isinstance(value, datetime.datetime): value = to_current_timezone(value) return value def to_python(self, value): """ Validate that the input can be converted to a datetime. Return a Python datetime.datetime object. """ if value in self.empty_values: return None if isinstance(value, datetime.datetime): return from_current_timezone(value) if isinstance(value, datetime.date): result = datetime.datetime(value.year, value.month, value.day) return from_current_timezone(result) try: result = parse_datetime(value.strip()) except ValueError: raise ValidationError(self.error_messages["invalid"], code="invalid") if not result: result = super().to_python(value) return from_current_timezone(result) def strptime(self, value, format): return datetime.datetime.strptime(value, format) class DurationField(Field): default_error_messages = { "invalid": _("Enter a valid duration."), "overflow": _("The number of days must be between {min_days} and {max_days}."), } def prepare_value(self, value): if isinstance(value, datetime.timedelta): return duration_string(value) return value def to_python(self, value): if value in self.empty_values: return None if isinstance(value, datetime.timedelta): return value try: value = parse_duration(str(value)) except OverflowError: raise ValidationError( self.error_messages["overflow"].format( min_days=datetime.timedelta.min.days, max_days=datetime.timedelta.max.days, ), code="overflow", ) if value is None: raise ValidationError(self.error_messages["invalid"], code="invalid") return value class RegexField(CharField): def __init__(self, regex, **kwargs): """ regex can be either a string or a compiled regular expression object. """ kwargs.setdefault("strip", False) super().__init__(**kwargs) self._set_regex(regex) def _get_regex(self): return self._regex def _set_regex(self, regex): if isinstance(regex, str): regex = re.compile(regex) self._regex = regex if ( hasattr(self, "_regex_validator") and self._regex_validator in self.validators ): self.validators.remove(self._regex_validator) self._regex_validator = validators.RegexValidator(regex=regex) self.validators.append(self._regex_validator) regex = property(_get_regex, _set_regex) class EmailField(CharField): widget = EmailInput default_validators = [validators.validate_email] def __init__(self, **kwargs): super().__init__(strip=True, **kwargs) class FileField(Field): widget = ClearableFileInput default_error_messages = { "invalid": _("No file was submitted. Check the encoding type on the form."), "missing": _("No file was submitted."), "empty": _("The submitted file is empty."), "max_length": ngettext_lazy( "Ensure this filename has at most %(max)d character (it has %(length)d).", "Ensure this filename has at most %(max)d characters (it has %(length)d).", "max", ), "contradiction": _( "Please either submit a file or check the clear checkbox, not both." ), } def __init__(self, *, max_length=None, allow_empty_file=False, **kwargs): self.max_length = max_length self.allow_empty_file = allow_empty_file super().__init__(**kwargs) def to_python(self, data): if data in self.empty_values: return None # UploadedFile objects should have name and size attributes. try: file_name = data.name file_size = data.size except AttributeError: raise ValidationError(self.error_messages["invalid"], code="invalid") if self.max_length is not None and len(file_name) > self.max_length: params = {"max": self.max_length, "length": len(file_name)} raise ValidationError( self.error_messages["max_length"], code="max_length", params=params ) if not file_name: raise ValidationError(self.error_messages["invalid"], code="invalid") if not self.allow_empty_file and not file_size: raise ValidationError(self.error_messages["empty"], code="empty") return data def clean(self, data, initial=None): # If the widget got contradictory inputs, we raise a validation error if data is FILE_INPUT_CONTRADICTION: raise ValidationError( self.error_messages["contradiction"], code="contradiction" ) # False means the field value should be cleared; further validation is # not needed. if data is False: if not self.required: return False # If the field is required, clearing is not possible (the widget # shouldn't return False data in that case anyway). False is not # in self.empty_value; if a False value makes it this far # it should be validated from here on out as None (so it will be # caught by the required check). data = None if not data and initial: return initial return super().clean(data) def bound_data(self, _, initial): return initial def has_changed(self, initial, data): return not self.disabled and data is not None class ImageField(FileField): default_validators = [validators.validate_image_file_extension] default_error_messages = { "invalid_image": _( "Upload a valid image. The file you uploaded was either not an " "image or a corrupted image." ), } def to_python(self, data): """ Check that the file-upload field data contains a valid image (GIF, JPG, PNG, etc. -- whatever Pillow supports). """ f = super().to_python(data) if f is None: return None from PIL import Image # We need to get a file object for Pillow. We might have a path or we might # have to read the data into memory. if hasattr(data, "temporary_file_path"): file = data.temporary_file_path() else: if hasattr(data, "read"): file = BytesIO(data.read()) else: file = BytesIO(data["content"]) try: # load() could spot a truncated JPEG, but it loads the entire # image in memory, which is a DoS vector. See #3848 and #18520. image = Image.open(file) # verify() must be called immediately after the constructor. image.verify() # Annotating so subclasses can reuse it for their own validation f.image = image # Pillow doesn't detect the MIME type of all formats. In those # cases, content_type will be None. f.content_type = Image.MIME.get(image.format) except Exception as exc: # Pillow doesn't recognize it as an image. raise ValidationError( self.error_messages["invalid_image"], code="invalid_image", ) from exc if hasattr(f, "seek") and callable(f.seek): f.seek(0) return f def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, FileInput) and "accept" not in widget.attrs: attrs.setdefault("accept", "image/*") return attrs class URLField(CharField): widget = URLInput default_error_messages = { "invalid": _("Enter a valid URL."), } default_validators = [validators.URLValidator()] def __init__(self, **kwargs): super().__init__(strip=True, **kwargs) def to_python(self, value): def split_url(url): """ Return a list of url parts via urlparse.urlsplit(), or raise ValidationError for some malformed URLs. """ try: return list(urlsplit(url)) except ValueError: # urlparse.urlsplit can raise a ValueError with some # misformatted URLs. raise ValidationError(self.error_messages["invalid"], code="invalid") value = super().to_python(value) if value: url_fields = split_url(value) if not url_fields[0]: # If no URL scheme given, assume http:// url_fields[0] = "http" if not url_fields[1]: # Assume that if no domain is provided, that the path segment # contains the domain. url_fields[1] = url_fields[2] url_fields[2] = "" # Rebuild the url_fields list, since the domain segment may now # contain the path too. url_fields = split_url(urlunsplit(url_fields)) value = urlunsplit(url_fields) return value class BooleanField(Field): widget = CheckboxInput def to_python(self, value): """Return a Python boolean object.""" # Explicitly check for the string 'False', which is what a hidden field # will submit for False. Also check for '0', since this is what # RadioSelect will provide. Because bool("True") == bool('1') == True, # we don't need to handle that explicitly. if isinstance(value, str) and value.lower() in ("false", "0"): value = False else: value = bool(value) return super().to_python(value) def validate(self, value): if not value and self.required: raise ValidationError(self.error_messages["required"], code="required") def has_changed(self, initial, data): if self.disabled: return False # Sometimes data or initial may be a string equivalent of a boolean # so we should run it through to_python first to get a boolean value return self.to_python(initial) != self.to_python(data) class NullBooleanField(BooleanField): """ A field whose valid values are None, True, and False. Clean invalid values to None. """ widget = NullBooleanSelect def to_python(self, value): """ Explicitly check for the string 'True' and 'False', which is what a hidden field will submit for True and False, for 'true' and 'false', which are likely to be returned by JavaScript serializations of forms, and for '1' and '0', which is what a RadioField will submit. Unlike the Booleanfield, this field must check for True because it doesn't use the bool() function. """ if value in (True, "True", "true", "1"): return True elif value in (False, "False", "false", "0"): return False else: return None def validate(self, value): pass class CallableChoiceIterator: def __init__(self, choices_func): self.choices_func = choices_func def __iter__(self): yield from self.choices_func() class ChoiceField(Field): widget = Select default_error_messages = { "invalid_choice": _( "Select a valid choice. %(value)s is not one of the available choices." ), } def __init__(self, *, choices=(), **kwargs): super().__init__(**kwargs) if isinstance(choices, ChoicesMeta): choices = choices.choices self.choices = choices def __deepcopy__(self, memo): result = super().__deepcopy__(memo) result._choices = copy.deepcopy(self._choices, memo) return result def _get_choices(self): return self._choices def _set_choices(self, value): # Setting choices also sets the choices on the widget. # choices can be any iterable, but we call list() on it because # it will be consumed more than once. if callable(value): value = CallableChoiceIterator(value) else: value = list(value) self._choices = self.widget.choices = value choices = property(_get_choices, _set_choices) def to_python(self, value): """Return a string.""" if value in self.empty_values: return "" return str(value) def validate(self, value): """Validate that the input is in self.choices.""" super().validate(value) if value and not self.valid_value(value): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}, ) def valid_value(self, value): """Check to see if the provided value is a valid choice.""" text_value = str(value) for k, v in self.choices: if isinstance(v, (list, tuple)): # This is an optgroup, so look inside the group for options for k2, v2 in v: if value == k2 or text_value == str(k2): return True else: if value == k or text_value == str(k): return True return False class TypedChoiceField(ChoiceField): def __init__(self, *, coerce=lambda val: val, empty_value="", **kwargs): self.coerce = coerce self.empty_value = empty_value super().__init__(**kwargs) def _coerce(self, value): """ Validate that the value can be coerced to the right type (if not empty). """ if value == self.empty_value or value in self.empty_values: return self.empty_value try: value = self.coerce(value) except (ValueError, TypeError, ValidationError): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}, ) return value def clean(self, value): value = super().clean(value) return self._coerce(value) class MultipleChoiceField(ChoiceField): hidden_widget = MultipleHiddenInput widget = SelectMultiple default_error_messages = { "invalid_choice": _( "Select a valid choice. %(value)s is not one of the available choices." ), "invalid_list": _("Enter a list of values."), } def to_python(self, value): if not value: return [] elif not isinstance(value, (list, tuple)): raise ValidationError( self.error_messages["invalid_list"], code="invalid_list" ) return [str(val) for val in value] def validate(self, value): """Validate that the input is a list or tuple.""" if self.required and not value: raise ValidationError(self.error_messages["required"], code="required") # Validate that each value in the value list is in self.choices. for val in value: if not self.valid_value(val): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": val}, ) def has_changed(self, initial, data): if self.disabled: return False if initial is None: initial = [] if data is None: data = [] if len(initial) != len(data): return True initial_set = {str(value) for value in initial} data_set = {str(value) for value in data} return data_set != initial_set class TypedMultipleChoiceField(MultipleChoiceField): def __init__(self, *, coerce=lambda val: val, **kwargs): self.coerce = coerce self.empty_value = kwargs.pop("empty_value", []) super().__init__(**kwargs) def _coerce(self, value): """ Validate that the values are in self.choices and can be coerced to the right type. """ if value == self.empty_value or value in self.empty_values: return self.empty_value new_value = [] for choice in value: try: new_value.append(self.coerce(choice)) except (ValueError, TypeError, ValidationError): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": choice}, ) return new_value def clean(self, value): value = super().clean(value) return self._coerce(value) def validate(self, value): if value != self.empty_value: super().validate(value) elif self.required: raise ValidationError(self.error_messages["required"], code="required") class ComboField(Field): """ A Field whose clean() method calls multiple Field clean() methods. """ def __init__(self, fields, **kwargs): super().__init__(**kwargs) # Set 'required' to False on the individual fields, because the # required validation will be handled by ComboField, not by those # individual fields. for f in fields: f.required = False self.fields = fields def clean(self, value): """ Validate the given value against all of self.fields, which is a list of Field instances. """ super().clean(value) for field in self.fields: value = field.clean(value) return value class MultiValueField(Field): """ Aggregate the logic of multiple Fields. Its clean() method takes a "decompressed" list of values, which are then cleaned into a single value according to self.fields. Each value in this list is cleaned by the corresponding field -- the first value is cleaned by the first field, the second value is cleaned by the second field, etc. Once all fields are cleaned, the list of clean values is "compressed" into a single value. Subclasses should not have to implement clean(). Instead, they must implement compress(), which takes a list of valid values and returns a "compressed" version of those values -- a single value. You'll probably want to use this with MultiWidget. """ default_error_messages = { "invalid": _("Enter a list of values."), "incomplete": _("Enter a complete value."), } def __init__(self, fields, *, require_all_fields=True, **kwargs): self.require_all_fields = require_all_fields super().__init__(**kwargs) for f in fields: f.error_messages.setdefault("incomplete", self.error_messages["incomplete"]) if self.disabled: f.disabled = True if self.require_all_fields: # Set 'required' to False on the individual fields, because the # required validation will be handled by MultiValueField, not # by those individual fields. f.required = False self.fields = fields def __deepcopy__(self, memo): result = super().__deepcopy__(memo) result.fields = tuple(x.__deepcopy__(memo) for x in self.fields) return result def validate(self, value): pass def clean(self, value): """ Validate every value in the given list. A value is validated against the corresponding Field in self.fields. For example, if this MultiValueField was instantiated with fields=(DateField(), TimeField()), clean() would call DateField.clean(value[0]) and TimeField.clean(value[1]). """ clean_data = [] errors = [] if self.disabled and not isinstance(value, list): value = self.widget.decompress(value) if not value or isinstance(value, (list, tuple)): if not value or not [v for v in value if v not in self.empty_values]: if self.required: raise ValidationError( self.error_messages["required"], code="required" ) else: return self.compress([]) else: raise ValidationError(self.error_messages["invalid"], code="invalid") for i, field in enumerate(self.fields): try: field_value = value[i] except IndexError: field_value = None if field_value in self.empty_values: if self.require_all_fields: # Raise a 'required' error if the MultiValueField is # required and any field is empty. if self.required: raise ValidationError( self.error_messages["required"], code="required" ) elif field.required: # Otherwise, add an 'incomplete' error to the list of # collected errors and skip field cleaning, if a required # field is empty. if field.error_messages["incomplete"] not in errors: errors.append(field.error_messages["incomplete"]) continue try: clean_data.append(field.clean(field_value)) except ValidationError as e: # Collect all validation errors in a single list, which we'll # raise at the end of clean(), rather than raising a single # exception for the first error we encounter. Skip duplicates. errors.extend(m for m in e.error_list if m not in errors) if errors: raise ValidationError(errors) out = self.compress(clean_data) self.validate(out) self.run_validators(out) return out def compress(self, data_list): """ Return a single value for the given list of values. The values can be assumed to be valid. For example, if this MultiValueField was instantiated with fields=(DateField(), TimeField()), this might return a datetime object created by combining the date and time in data_list. """ raise NotImplementedError("Subclasses must implement this method.") def has_changed(self, initial, data): if self.disabled: return False if initial is None: initial = ["" for x in range(0, len(data))] else: if not isinstance(initial, list): initial = self.widget.decompress(initial) for field, initial, data in zip(self.fields, initial, data): try: initial = field.to_python(initial) except ValidationError: return True if field.has_changed(initial, data): return True return False class FilePathField(ChoiceField): def __init__( self, path, *, match=None, recursive=False, allow_files=True, allow_folders=False, **kwargs, ): self.path, self.match, self.recursive = path, match, recursive self.allow_files, self.allow_folders = allow_files, allow_folders super().__init__(choices=(), **kwargs) if self.required: self.choices = [] else: self.choices = [("", "---------")] if self.match is not None: self.match_re = re.compile(self.match) if recursive: for root, dirs, files in sorted(os.walk(self.path)): if self.allow_files: for f in sorted(files): if self.match is None or self.match_re.search(f): f = os.path.join(root, f) self.choices.append((f, f.replace(path, "", 1))) if self.allow_folders: for f in sorted(dirs): if f == "__pycache__": continue if self.match is None or self.match_re.search(f): f = os.path.join(root, f) self.choices.append((f, f.replace(path, "", 1))) else: choices = [] with os.scandir(self.path) as entries: for f in entries: if f.name == "__pycache__": continue if ( (self.allow_files and f.is_file()) or (self.allow_folders and f.is_dir()) ) and (self.match is None or self.match_re.search(f.name)): choices.append((f.path, f.name)) choices.sort(key=operator.itemgetter(1)) self.choices.extend(choices) self.widget.choices = self.choices class SplitDateTimeField(MultiValueField): widget = SplitDateTimeWidget hidden_widget = SplitHiddenDateTimeWidget default_error_messages = { "invalid_date": _("Enter a valid date."), "invalid_time": _("Enter a valid time."), } def __init__(self, *, input_date_formats=None, input_time_formats=None, **kwargs): errors = self.default_error_messages.copy() if "error_messages" in kwargs: errors.update(kwargs["error_messages"]) localize = kwargs.get("localize", False) fields = ( DateField( input_formats=input_date_formats, error_messages={"invalid": errors["invalid_date"]}, localize=localize, ), TimeField( input_formats=input_time_formats, error_messages={"invalid": errors["invalid_time"]}, localize=localize, ), ) super().__init__(fields, **kwargs) def compress(self, data_list): if data_list: # Raise a validation error if time or date is empty # (possible if SplitDateTimeField has required=False). if data_list[0] in self.empty_values: raise ValidationError( self.error_messages["invalid_date"], code="invalid_date" ) if data_list[1] in self.empty_values: raise ValidationError( self.error_messages["invalid_time"], code="invalid_time" ) result = datetime.datetime.combine(*data_list) return from_current_timezone(result) return None class GenericIPAddressField(CharField): def __init__(self, *, protocol="both", unpack_ipv4=False, **kwargs): self.unpack_ipv4 = unpack_ipv4 self.default_validators = validators.ip_address_validators( protocol, unpack_ipv4 )[0] super().__init__(**kwargs) def to_python(self, value): if value in self.empty_values: return "" value = value.strip() if value and ":" in value: return clean_ipv6_address(value, self.unpack_ipv4) return value class SlugField(CharField): default_validators = [validators.validate_slug] def __init__(self, *, allow_unicode=False, **kwargs): self.allow_unicode = allow_unicode if self.allow_unicode: self.default_validators = [validators.validate_unicode_slug] super().__init__(**kwargs) class UUIDField(CharField): default_error_messages = { "invalid": _("Enter a valid UUID."), } def prepare_value(self, value): if isinstance(value, uuid.UUID): return str(value) return value def to_python(self, value): value = super().to_python(value) if value in self.empty_values: return None if not isinstance(value, uuid.UUID): try: value = uuid.UUID(value) except ValueError: raise ValidationError(self.error_messages["invalid"], code="invalid") return value class InvalidJSONInput(str): pass class JSONString(str): pass class JSONField(CharField): default_error_messages = { "invalid": _("Enter a valid JSON."), } widget = Textarea def __init__(self, encoder=None, decoder=None, **kwargs): self.encoder = encoder self.decoder = decoder super().__init__(**kwargs) def to_python(self, value): if self.disabled: return value if value in self.empty_values: return None elif isinstance(value, (list, dict, int, float, JSONString)): return value try: converted = json.loads(value, cls=self.decoder) except json.JSONDecodeError: raise ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) if isinstance(converted, str): return JSONString(converted) else: return converted def bound_data(self, data, initial): if self.disabled: return initial if data is None: return None try: return json.loads(data, cls=self.decoder) except json.JSONDecodeError: return InvalidJSONInput(data) def prepare_value(self, value): if isinstance(value, InvalidJSONInput): return value return json.dumps(value, ensure_ascii=False, cls=self.encoder) def has_changed(self, initial, data): if super().has_changed(initial, data): return True # For purposes of seeing whether something has changed, True isn't the # same as 1 and the order of keys doesn't matter. return json.dumps(initial, sort_keys=True, cls=self.encoder) != json.dumps( self.to_python(data), sort_keys=True, cls=self.encoder )
eda20aaeb9c55b02215d6509a963e9bbf93c69519ef6a1a5b128e3d485c3c905
""" Create SQL statements for QuerySets. The code in here encapsulates all of the SQL construction so that QuerySets themselves do not have to (and could be backed by things other than SQL databases). The abstraction barrier only works one way: this module has to know all about the internals of models in order to get the information it needs. """ import copy import difflib import functools import sys from collections import Counter, namedtuple from collections.abc import Iterator, Mapping from itertools import chain, count, product from string import ascii_uppercase from django.core.exceptions import FieldDoesNotExist, FieldError from django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections from django.db.models.aggregates import Count from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import ( BaseExpression, Col, Exists, F, OuterRef, Ref, ResolvedOuterRef, Value, ) from django.db.models.fields import Field from django.db.models.fields.related_lookups import MultiColSource from django.db.models.lookups import Lookup from django.db.models.query_utils import ( Q, check_rel_lookup_compatibility, refs_expression, ) from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE from django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin from django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode from django.utils.functional import cached_property from django.utils.regex_helper import _lazy_re_compile from django.utils.tree import Node __all__ = ["Query", "RawQuery"] # Quotation marks ('"`[]), whitespace characters, semicolons, or inline # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/") # Inspired from # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS EXPLAIN_OPTIONS_PATTERN = _lazy_re_compile(r"[\w\-]+") def get_field_names_from_opts(opts): if opts is None: return set() return set( chain.from_iterable( (f.name, f.attname) if f.concrete else (f.name,) for f in opts.get_fields() ) ) def get_children_from_q(q): for child in q.children: if isinstance(child, Node): yield from get_children_from_q(child) else: yield child JoinInfo = namedtuple( "JoinInfo", ("final_field", "targets", "opts", "joins", "path", "transform_function"), ) class RawQuery: """A single raw SQL query.""" def __init__(self, sql, using, params=()): self.params = params self.sql = sql self.using = using self.cursor = None # Mirror some properties of a normal query so that # the compiler can be used to process results. self.low_mark, self.high_mark = 0, None # Used for offset/limit self.extra_select = {} self.annotation_select = {} def chain(self, using): return self.clone(using) def clone(self, using): return RawQuery(self.sql, using, params=self.params) def get_columns(self): if self.cursor is None: self._execute_query() converter = connections[self.using].introspection.identifier_converter return [converter(column_meta[0]) for column_meta in self.cursor.description] def __iter__(self): # Always execute a new query for a new iterator. # This could be optimized with a cache at the expense of RAM. self._execute_query() if not connections[self.using].features.can_use_chunked_reads: # If the database can't use chunked reads we need to make sure we # evaluate the entire query up front. result = list(self.cursor) else: result = self.cursor return iter(result) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) @property def params_type(self): if self.params is None: return None return dict if isinstance(self.params, Mapping) else tuple def __str__(self): if self.params_type is None: return self.sql return self.sql % self.params_type(self.params) def _execute_query(self): connection = connections[self.using] # Adapt parameters to the database, as much as possible considering # that the target type isn't known. See #17755. params_type = self.params_type adapter = connection.ops.adapt_unknown_value if params_type is tuple: params = tuple(adapter(val) for val in self.params) elif params_type is dict: params = {key: adapter(val) for key, val in self.params.items()} elif params_type is None: params = None else: raise RuntimeError("Unexpected params type: %s" % params_type) self.cursor = connection.cursor() self.cursor.execute(self.sql, params) ExplainInfo = namedtuple("ExplainInfo", ("format", "options")) class Query(BaseExpression): """A single SQL query.""" alias_prefix = "T" empty_result_set_value = None subq_aliases = frozenset([alias_prefix]) compiler = "SQLCompiler" base_table_class = BaseTable join_class = Join default_cols = True default_ordering = True standard_ordering = True filter_is_sticky = False subquery = False # SQL-related attributes. # Select and related select clauses are expressions to use in the SELECT # clause of the query. The select is used for cases where we want to set up # the select clause to contain other than default fields (values(), # subqueries...). Note that annotations go to annotations dictionary. select = () # The group_by attribute can have one of the following forms: # - None: no group by at all in the query # - A tuple of expressions: group by (at least) those expressions. # String refs are also allowed for now. # - True: group by all select fields of the model # See compiler.get_group_by() for details. group_by = None order_by = () low_mark = 0 # Used for offset/limit. high_mark = None # Used for offset/limit. distinct = False distinct_fields = () select_for_update = False select_for_update_nowait = False select_for_update_skip_locked = False select_for_update_of = () select_for_no_key_update = False select_related = False has_select_fields = False # Arbitrary limit for select_related to prevents infinite recursion. max_depth = 5 # Holds the selects defined by a call to values() or values_list() # excluding annotation_select and extra_select. values_select = () # SQL annotation-related attributes. annotation_select_mask = None _annotation_select_cache = None # Set combination attributes. combinator = None combinator_all = False combined_queries = () # These are for extensions. The contents are more or less appended verbatim # to the appropriate clause. extra_select_mask = None _extra_select_cache = None extra_tables = () extra_order_by = () # A tuple that is a set of model field names and either True, if these are # the fields to defer, or False if these are the only fields to load. deferred_loading = (frozenset(), True) explain_info = None def __init__(self, model, alias_cols=True): self.model = model self.alias_refcount = {} # alias_map is the most important data structure regarding joins. # It's used for recording which joins exist in the query and what # types they are. The key is the alias of the joined table (possibly # the table name) and the value is a Join-like object (see # sql.datastructures.Join for more information). self.alias_map = {} # Whether to provide alias to columns during reference resolving. self.alias_cols = alias_cols # Sometimes the query contains references to aliases in outer queries (as # a result of split_exclude). Correct alias quoting needs to know these # aliases too. # Map external tables to whether they are aliased. self.external_aliases = {} self.table_map = {} # Maps table names to list of aliases. self.used_aliases = set() self.where = WhereNode() # Maps alias -> Annotation Expression. self.annotations = {} # These are for extensions. The contents are more or less appended # verbatim to the appropriate clause. self.extra = {} # Maps col_alias -> (col_sql, params). self._filtered_relations = {} @property def output_field(self): if len(self.select) == 1: select = self.select[0] return getattr(select, "target", None) or select.field elif len(self.annotation_select) == 1: return next(iter(self.annotation_select.values())).output_field @cached_property def base_table(self): for alias in self.alias_map: return alias def __str__(self): """ Return the query as a string of SQL with the parameter values substituted in (use sql_with_params() to see the unsubstituted string). Parameter values won't necessarily be quoted correctly, since that is done by the database interface at execution time. """ sql, params = self.sql_with_params() return sql % params def sql_with_params(self): """ Return the query as an SQL string and the parameters that will be substituted into the query. """ return self.get_compiler(DEFAULT_DB_ALIAS).as_sql() def __deepcopy__(self, memo): """Limit the amount of work when a Query is deepcopied.""" result = self.clone() memo[id(self)] = result return result def get_compiler(self, using=None, connection=None, elide_empty=True): if using is None and connection is None: raise ValueError("Need either using or connection") if using: connection = connections[using] return connection.ops.compiler(self.compiler)( self, connection, using, elide_empty ) def get_meta(self): """ Return the Options instance (the model._meta) from which to start processing. Normally, this is self.model._meta, but it can be changed by subclasses. """ if self.model: return self.model._meta def clone(self): """ Return a copy of the current Query. A lightweight alternative to deepcopy(). """ obj = Empty() obj.__class__ = self.__class__ # Copy references to everything. obj.__dict__ = self.__dict__.copy() # Clone attributes that can't use shallow copy. obj.alias_refcount = self.alias_refcount.copy() obj.alias_map = self.alias_map.copy() obj.external_aliases = self.external_aliases.copy() obj.table_map = self.table_map.copy() obj.where = self.where.clone() obj.annotations = self.annotations.copy() if self.annotation_select_mask is not None: obj.annotation_select_mask = self.annotation_select_mask.copy() if self.combined_queries: obj.combined_queries = tuple( [query.clone() for query in self.combined_queries] ) # _annotation_select_cache cannot be copied, as doing so breaks the # (necessary) state in which both annotations and # _annotation_select_cache point to the same underlying objects. # It will get re-populated in the cloned queryset the next time it's # used. obj._annotation_select_cache = None obj.extra = self.extra.copy() if self.extra_select_mask is not None: obj.extra_select_mask = self.extra_select_mask.copy() if self._extra_select_cache is not None: obj._extra_select_cache = self._extra_select_cache.copy() if self.select_related is not False: # Use deepcopy because select_related stores fields in nested # dicts. obj.select_related = copy.deepcopy(obj.select_related) if "subq_aliases" in self.__dict__: obj.subq_aliases = self.subq_aliases.copy() obj.used_aliases = self.used_aliases.copy() obj._filtered_relations = self._filtered_relations.copy() # Clear the cached_property, if it exists. obj.__dict__.pop("base_table", None) return obj def chain(self, klass=None): """ Return a copy of the current Query that's ready for another operation. The klass argument changes the type of the Query, e.g. UpdateQuery. """ obj = self.clone() if klass and obj.__class__ != klass: obj.__class__ = klass if not obj.filter_is_sticky: obj.used_aliases = set() obj.filter_is_sticky = False if hasattr(obj, "_setup_query"): obj._setup_query() return obj def relabeled_clone(self, change_map): clone = self.clone() clone.change_aliases(change_map) return clone def _get_col(self, target, field, alias): if not self.alias_cols: alias = None return target.get_col(alias, field) def get_aggregation(self, using, aggregate_exprs): """ Return the dictionary with the values of the existing aggregations. """ if not aggregate_exprs: return {} aggregates = {} for alias, aggregate_expr in aggregate_exprs.items(): self.check_alias(alias) aggregate = aggregate_expr.resolve_expression( self, allow_joins=True, reuse=None, summarize=True ) if not aggregate.contains_aggregate: raise TypeError("%s is not an aggregate expression" % alias) aggregates[alias] = aggregate # Existing usage of aggregation can be determined by the presence of # selected aggregates but also by filters against aliased aggregates. _, having, qualify = self.where.split_having_qualify() has_existing_aggregation = ( any( getattr(annotation, "contains_aggregate", True) for annotation in self.annotations.values() ) or having ) # Decide if we need to use a subquery. # # Existing aggregations would cause incorrect results as # get_aggregation() must produce just one result and thus must not use # GROUP BY. # # If the query has limit or distinct, or uses set operations, then # those operations must be done in a subquery so that the query # aggregates on the limit and/or distinct results instead of applying # the distinct and limit after the aggregation. if ( isinstance(self.group_by, tuple) or self.is_sliced or has_existing_aggregation or qualify or self.distinct or self.combinator ): from django.db.models.sql.subqueries import AggregateQuery inner_query = self.clone() inner_query.subquery = True outer_query = AggregateQuery(self.model, inner_query) inner_query.select_for_update = False inner_query.select_related = False inner_query.set_annotation_mask(self.annotation_select) # Queries with distinct_fields need ordering and when a limit is # applied we must take the slice from the ordered query. Otherwise # no need for ordering. inner_query.clear_ordering(force=False) if not inner_query.distinct: # If the inner query uses default select and it has some # aggregate annotations, then we must make sure the inner # query is grouped by the main model's primary key. However, # clearing the select clause can alter results if distinct is # used. if inner_query.default_cols and has_existing_aggregation: inner_query.group_by = ( self.model._meta.pk.get_col(inner_query.get_initial_alias()), ) inner_query.default_cols = False if not qualify: # Mask existing annotations that are not referenced by # aggregates to be pushed to the outer query unless # filtering against window functions is involved as it # requires complex realising. annotation_mask = set() for aggregate in aggregates.values(): annotation_mask |= aggregate.get_refs() inner_query.set_annotation_mask(annotation_mask) # Add aggregates to the outer AggregateQuery. This requires making # sure all columns referenced by the aggregates are selected in the # inner query. It is achieved by retrieving all column references # by the aggregates, explicitly selecting them in the inner query, # and making sure the aggregates are repointed to them. col_refs = {} for alias, aggregate in aggregates.items(): replacements = {} for col in self._gen_cols([aggregate], resolve_refs=False): if not (col_ref := col_refs.get(col)): index = len(col_refs) + 1 col_alias = f"__col{index}" col_ref = Ref(col_alias, col) col_refs[col] = col_ref inner_query.annotations[col_alias] = col inner_query.append_annotation_mask([col_alias]) replacements[col] = col_ref outer_query.annotations[alias] = aggregate.replace_expressions( replacements ) if ( inner_query.select == () and not inner_query.default_cols and not inner_query.annotation_select_mask ): # In case of Model.objects[0:3].count(), there would be no # field selected in the inner query, yet we must use a subquery. # So, make sure at least one field is selected. inner_query.select = ( self.model._meta.pk.get_col(inner_query.get_initial_alias()), ) else: outer_query = self self.select = () self.default_cols = False self.extra = {} if self.annotations: # Inline reference to existing annotations and mask them as # they are unnecessary given only the summarized aggregations # are requested. replacements = { Ref(alias, annotation): annotation for alias, annotation in self.annotations.items() } self.annotations = { alias: aggregate.replace_expressions(replacements) for alias, aggregate in aggregates.items() } else: self.annotations = aggregates self.set_annotation_mask(aggregates) empty_set_result = [ expression.empty_result_set_value for expression in outer_query.annotation_select.values() ] elide_empty = not any(result is NotImplemented for result in empty_set_result) outer_query.clear_ordering(force=True) outer_query.clear_limits() outer_query.select_for_update = False outer_query.select_related = False compiler = outer_query.get_compiler(using, elide_empty=elide_empty) result = compiler.execute_sql(SINGLE) if result is None: result = empty_set_result else: converters = compiler.get_converters(outer_query.annotation_select.values()) result = next(compiler.apply_converters((result,), converters)) return dict(zip(outer_query.annotation_select, result)) def get_count(self, using): """ Perform a COUNT() query using the current filter constraints. """ obj = self.clone() return obj.get_aggregation(using, {"__count": Count("*")})["__count"] def has_filters(self): return self.where def exists(self, limit=True): q = self.clone() if not (q.distinct and q.is_sliced): if q.group_by is True: q.add_fields( (f.attname for f in self.model._meta.concrete_fields), False ) # Disable GROUP BY aliases to avoid orphaning references to the # SELECT clause which is about to be cleared. q.set_group_by(allow_aliases=False) q.clear_select_clause() if q.combined_queries and q.combinator == "union": q.combined_queries = tuple( combined_query.exists(limit=False) for combined_query in q.combined_queries ) q.clear_ordering(force=True) if limit: q.set_limits(high=1) q.add_annotation(Value(1), "a") return q def has_results(self, using): q = self.exists(using) compiler = q.get_compiler(using=using) return compiler.has_results() def explain(self, using, format=None, **options): q = self.clone() for option_name in options: if ( not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name) or "--" in option_name ): raise ValueError(f"Invalid option name: {option_name!r}.") q.explain_info = ExplainInfo(format, options) compiler = q.get_compiler(using=using) return "\n".join(compiler.explain_query()) def combine(self, rhs, connector): """ Merge the 'rhs' query into the current one (with any 'rhs' effects being applied *after* (that is, "to the right of") anything in the current query. 'rhs' is not modified during a call to this function. The 'connector' parameter describes how to connect filters from the 'rhs' query. """ if self.model != rhs.model: raise TypeError("Cannot combine queries on two different base models.") if self.is_sliced: raise TypeError("Cannot combine queries once a slice has been taken.") if self.distinct != rhs.distinct: raise TypeError("Cannot combine a unique query with a non-unique query.") if self.distinct_fields != rhs.distinct_fields: raise TypeError("Cannot combine queries with different distinct fields.") # If lhs and rhs shares the same alias prefix, it is possible to have # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up # as T4 -> T6 while combining two querysets. To prevent this, change an # alias prefix of the rhs and update current aliases accordingly, # except if the alias is the base table since it must be present in the # query on both sides. initial_alias = self.get_initial_alias() rhs.bump_prefix(self, exclude={initial_alias}) # Work out how to relabel the rhs aliases, if necessary. change_map = {} conjunction = connector == AND # Determine which existing joins can be reused. When combining the # query with AND we must recreate all joins for m2m filters. When # combining with OR we can reuse joins. The reason is that in AND # case a single row can't fulfill a condition like: # revrel__col=1 & revrel__col=2 # But, there might be two different related rows matching this # condition. In OR case a single True is enough, so single row is # enough, too. # # Note that we will be creating duplicate joins for non-m2m joins in # the AND case. The results will be correct but this creates too many # joins. This is something that could be fixed later on. reuse = set() if conjunction else set(self.alias_map) joinpromoter = JoinPromoter(connector, 2, False) joinpromoter.add_votes( j for j in self.alias_map if self.alias_map[j].join_type == INNER ) rhs_votes = set() # Now, add the joins from rhs query into the new query (skipping base # table). rhs_tables = list(rhs.alias_map)[1:] for alias in rhs_tables: join = rhs.alias_map[alias] # If the left side of the join was already relabeled, use the # updated alias. join = join.relabeled_clone(change_map) new_alias = self.join(join, reuse=reuse) if join.join_type == INNER: rhs_votes.add(new_alias) # We can't reuse the same join again in the query. If we have two # distinct joins for the same connection in rhs query, then the # combined query must have two joins, too. reuse.discard(new_alias) if alias != new_alias: change_map[alias] = new_alias if not rhs.alias_refcount[alias]: # The alias was unused in the rhs query. Unref it so that it # will be unused in the new query, too. We have to add and # unref the alias so that join promotion has information of # the join type for the unused alias. self.unref_alias(new_alias) joinpromoter.add_votes(rhs_votes) joinpromoter.update_join_types(self) # Combine subqueries aliases to ensure aliases relabelling properly # handle subqueries when combining where and select clauses. self.subq_aliases |= rhs.subq_aliases # Now relabel a copy of the rhs where-clause and add it to the current # one. w = rhs.where.clone() w.relabel_aliases(change_map) self.where.add(w, connector) # Selection columns and extra extensions are those provided by 'rhs'. if rhs.select: self.set_select([col.relabeled_clone(change_map) for col in rhs.select]) else: self.select = () if connector == OR: # It would be nice to be able to handle this, but the queries don't # really make sense (or return consistent value sets). Not worth # the extra complexity when you can write a real query instead. if self.extra and rhs.extra: raise ValueError( "When merging querysets using 'or', you cannot have " "extra(select=...) on both sides." ) self.extra.update(rhs.extra) extra_select_mask = set() if self.extra_select_mask is not None: extra_select_mask.update(self.extra_select_mask) if rhs.extra_select_mask is not None: extra_select_mask.update(rhs.extra_select_mask) if extra_select_mask: self.set_extra_mask(extra_select_mask) self.extra_tables += rhs.extra_tables # Ordering uses the 'rhs' ordering, unless it has none, in which case # the current ordering is used. self.order_by = rhs.order_by or self.order_by self.extra_order_by = rhs.extra_order_by or self.extra_order_by def _get_defer_select_mask(self, opts, mask, select_mask=None): if select_mask is None: select_mask = {} select_mask[opts.pk] = {} # All concrete fields that are not part of the defer mask must be # loaded. If a relational field is encountered it gets added to the # mask for it be considered if `select_related` and the cycle continues # by recursively calling this function. for field in opts.concrete_fields: field_mask = mask.pop(field.name, None) if field_mask is None: select_mask.setdefault(field, {}) elif field_mask: if not field.is_relation: raise FieldError(next(iter(field_mask))) field_select_mask = select_mask.setdefault(field, {}) related_model = field.remote_field.model._meta.concrete_model self._get_defer_select_mask( related_model._meta, field_mask, field_select_mask ) # Remaining defer entries must be references to reverse relationships. # The following code is expected to raise FieldError if it encounters # a malformed defer entry. for field_name, field_mask in mask.items(): if filtered_relation := self._filtered_relations.get(field_name): relation = opts.get_field(filtered_relation.relation_name) field_select_mask = select_mask.setdefault((field_name, relation), {}) field = relation.field else: field = opts.get_field(field_name).field field_select_mask = select_mask.setdefault(field, {}) related_model = field.model._meta.concrete_model self._get_defer_select_mask( related_model._meta, field_mask, field_select_mask ) return select_mask def _get_only_select_mask(self, opts, mask, select_mask=None): if select_mask is None: select_mask = {} select_mask[opts.pk] = {} # Only include fields mentioned in the mask. for field_name, field_mask in mask.items(): field = opts.get_field(field_name) field_select_mask = select_mask.setdefault(field, {}) if field_mask: if not field.is_relation: raise FieldError(next(iter(field_mask))) related_model = field.remote_field.model._meta.concrete_model self._get_only_select_mask( related_model._meta, field_mask, field_select_mask ) return select_mask def get_select_mask(self): """ Convert the self.deferred_loading data structure to an alternate data structure, describing the field that *will* be loaded. This is used to compute the columns to select from the database and also by the QuerySet class to work out which fields are being initialized on each model. Models that have all their fields included aren't mentioned in the result, only those that have field restrictions in place. """ field_names, defer = self.deferred_loading if not field_names: return {} mask = {} for field_name in field_names: part_mask = mask for part in field_name.split(LOOKUP_SEP): part_mask = part_mask.setdefault(part, {}) opts = self.get_meta() if defer: return self._get_defer_select_mask(opts, mask) return self._get_only_select_mask(opts, mask) def table_alias(self, table_name, create=False, filtered_relation=None): """ Return a table alias for the given table_name and whether this is a new alias or not. If 'create' is true, a new alias is always created. Otherwise, the most recently created alias for the table (if one exists) is reused. """ alias_list = self.table_map.get(table_name) if not create and alias_list: alias = alias_list[0] self.alias_refcount[alias] += 1 return alias, False # Create a new alias for this table. if alias_list: alias = "%s%d" % (self.alias_prefix, len(self.alias_map) + 1) alias_list.append(alias) else: # The first occurrence of a table uses the table name directly. alias = ( filtered_relation.alias if filtered_relation is not None else table_name ) self.table_map[table_name] = [alias] self.alias_refcount[alias] = 1 return alias, True def ref_alias(self, alias): """Increases the reference count for this alias.""" self.alias_refcount[alias] += 1 def unref_alias(self, alias, amount=1): """Decreases the reference count for this alias.""" self.alias_refcount[alias] -= amount def promote_joins(self, aliases): """ Promote recursively the join type of given aliases and its children to an outer join. If 'unconditional' is False, only promote the join if it is nullable or the parent join is an outer join. The children promotion is done to avoid join chains that contain a LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b is promoted, then we must also promote b->c automatically, or otherwise the promotion of a->b doesn't actually change anything in the query results. """ aliases = list(aliases) while aliases: alias = aliases.pop(0) if self.alias_map[alias].join_type is None: # This is the base table (first FROM entry) - this table # isn't really joined at all in the query, so we should not # alter its join type. continue # Only the first alias (skipped above) should have None join_type assert self.alias_map[alias].join_type is not None parent_alias = self.alias_map[alias].parent_alias parent_louter = ( parent_alias and self.alias_map[parent_alias].join_type == LOUTER ) already_louter = self.alias_map[alias].join_type == LOUTER if (self.alias_map[alias].nullable or parent_louter) and not already_louter: self.alias_map[alias] = self.alias_map[alias].promote() # Join type of 'alias' changed, so re-examine all aliases that # refer to this one. aliases.extend( join for join in self.alias_map if self.alias_map[join].parent_alias == alias and join not in aliases ) def demote_joins(self, aliases): """ Change join type from LOUTER to INNER for all joins in aliases. Similarly to promote_joins(), this method must ensure no join chains containing first an outer, then an inner join are generated. If we are demoting b->c join in chain a LOUTER b LOUTER c then we must demote a->b automatically, or otherwise the demotion of b->c doesn't actually change anything in the query results. . """ aliases = list(aliases) while aliases: alias = aliases.pop(0) if self.alias_map[alias].join_type == LOUTER: self.alias_map[alias] = self.alias_map[alias].demote() parent_alias = self.alias_map[alias].parent_alias if self.alias_map[parent_alias].join_type == INNER: aliases.append(parent_alias) def reset_refcounts(self, to_counts): """ Reset reference counts for aliases so that they match the value passed in `to_counts`. """ for alias, cur_refcount in self.alias_refcount.copy().items(): unref_amount = cur_refcount - to_counts.get(alias, 0) self.unref_alias(alias, unref_amount) def change_aliases(self, change_map): """ Change the aliases in change_map (which maps old-alias -> new-alias), relabelling any references to them in select columns and the where clause. """ # If keys and values of change_map were to intersect, an alias might be # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending # on their order in change_map. assert set(change_map).isdisjoint(change_map.values()) # 1. Update references in "select" (normal columns plus aliases), # "group by" and "where". self.where.relabel_aliases(change_map) if isinstance(self.group_by, tuple): self.group_by = tuple( [col.relabeled_clone(change_map) for col in self.group_by] ) self.select = tuple([col.relabeled_clone(change_map) for col in self.select]) self.annotations = self.annotations and { key: col.relabeled_clone(change_map) for key, col in self.annotations.items() } # 2. Rename the alias in the internal table/alias datastructures. for old_alias, new_alias in change_map.items(): if old_alias not in self.alias_map: continue alias_data = self.alias_map[old_alias].relabeled_clone(change_map) self.alias_map[new_alias] = alias_data self.alias_refcount[new_alias] = self.alias_refcount[old_alias] del self.alias_refcount[old_alias] del self.alias_map[old_alias] table_aliases = self.table_map[alias_data.table_name] for pos, alias in enumerate(table_aliases): if alias == old_alias: table_aliases[pos] = new_alias break self.external_aliases = { # Table is aliased or it's being changed and thus is aliased. change_map.get(alias, alias): (aliased or alias in change_map) for alias, aliased in self.external_aliases.items() } def bump_prefix(self, other_query, exclude=None): """ Change the alias prefix to the next letter in the alphabet in a way that the other query's aliases and this query's aliases will not conflict. Even tables that previously had no alias will get an alias after this call. To prevent changing aliases use the exclude parameter. """ def prefix_gen(): """ Generate a sequence of characters in alphabetical order: -> 'A', 'B', 'C', ... When the alphabet is finished, the sequence will continue with the Cartesian product: -> 'AA', 'AB', 'AC', ... """ alphabet = ascii_uppercase prefix = chr(ord(self.alias_prefix) + 1) yield prefix for n in count(1): seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet for s in product(seq, repeat=n): yield "".join(s) prefix = None if self.alias_prefix != other_query.alias_prefix: # No clashes between self and outer query should be possible. return # Explicitly avoid infinite loop. The constant divider is based on how # much depth recursive subquery references add to the stack. This value # might need to be adjusted when adding or removing function calls from # the code path in charge of performing these operations. local_recursion_limit = sys.getrecursionlimit() // 16 for pos, prefix in enumerate(prefix_gen()): if prefix not in self.subq_aliases: self.alias_prefix = prefix break if pos > local_recursion_limit: raise RecursionError( "Maximum recursion depth exceeded: too many subqueries." ) self.subq_aliases = self.subq_aliases.union([self.alias_prefix]) other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases) if exclude is None: exclude = {} self.change_aliases( { alias: "%s%d" % (self.alias_prefix, pos) for pos, alias in enumerate(self.alias_map) if alias not in exclude } ) def get_initial_alias(self): """ Return the first alias for this query, after increasing its reference count. """ if self.alias_map: alias = self.base_table self.ref_alias(alias) elif self.model: alias = self.join(self.base_table_class(self.get_meta().db_table, None)) else: alias = None return alias def count_active_tables(self): """ Return the number of tables in this query with a non-zero reference count. After execution, the reference counts are zeroed, so tables added in compiler will not be seen by this method. """ return len([1 for count in self.alias_refcount.values() if count]) def join(self, join, reuse=None, reuse_with_filtered_relation=False): """ Return an alias for the 'join', either reusing an existing alias for that join or creating a new one. 'join' is either a base_table_class or join_class. The 'reuse' parameter can be either None which means all joins are reusable, or it can be a set containing the aliases that can be reused. The 'reuse_with_filtered_relation' parameter is used when computing FilteredRelation instances. A join is always created as LOUTER if the lhs alias is LOUTER to make sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new joins are created as LOUTER if the join is nullable. """ if reuse_with_filtered_relation and reuse: reuse_aliases = [ a for a, j in self.alias_map.items() if a in reuse and j.equals(join) ] else: reuse_aliases = [ a for a, j in self.alias_map.items() if (reuse is None or a in reuse) and j == join ] if reuse_aliases: if join.table_alias in reuse_aliases: reuse_alias = join.table_alias else: # Reuse the most recent alias of the joined table # (a many-to-many relation may be joined multiple times). reuse_alias = reuse_aliases[-1] self.ref_alias(reuse_alias) return reuse_alias # No reuse is possible, so we need a new alias. alias, _ = self.table_alias( join.table_name, create=True, filtered_relation=join.filtered_relation ) if join.join_type: if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable: join_type = LOUTER else: join_type = INNER join.join_type = join_type join.table_alias = alias self.alias_map[alias] = join return alias def join_parent_model(self, opts, model, alias, seen): """ Make sure the given 'model' is joined in the query. If 'model' isn't a parent of 'opts' or if it is None this method is a no-op. The 'alias' is the root alias for starting the join, 'seen' is a dict of model -> alias of existing joins. It must also contain a mapping of None -> some alias. This will be returned in the no-op case. """ if model in seen: return seen[model] chain = opts.get_base_chain(model) if not chain: return alias curr_opts = opts for int_model in chain: if int_model in seen: curr_opts = int_model._meta alias = seen[int_model] continue # Proxy model have elements in base chain # with no parents, assign the new options # object and skip to the next base in that # case if not curr_opts.parents[int_model]: curr_opts = int_model._meta continue link_field = curr_opts.get_ancestor_link(int_model) join_info = self.setup_joins([link_field.name], curr_opts, alias) curr_opts = int_model._meta alias = seen[int_model] = join_info.joins[-1] return alias or seen[None] def check_alias(self, alias): if FORBIDDEN_ALIAS_PATTERN.search(alias): raise ValueError( "Column aliases cannot contain whitespace characters, quotation marks, " "semicolons, or SQL comments." ) def add_annotation(self, annotation, alias, select=True): """Add a single annotation expression to the Query.""" self.check_alias(alias) annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None) if select: self.append_annotation_mask([alias]) else: self.set_annotation_mask(set(self.annotation_select).difference({alias})) self.annotations[alias] = annotation def resolve_expression(self, query, *args, **kwargs): clone = self.clone() # Subqueries need to use a different set of aliases than the outer query. clone.bump_prefix(query) clone.subquery = True clone.where.resolve_expression(query, *args, **kwargs) # Resolve combined queries. if clone.combinator: clone.combined_queries = tuple( [ combined_query.resolve_expression(query, *args, **kwargs) for combined_query in clone.combined_queries ] ) for key, value in clone.annotations.items(): resolved = value.resolve_expression(query, *args, **kwargs) if hasattr(resolved, "external_aliases"): resolved.external_aliases.update(clone.external_aliases) clone.annotations[key] = resolved # Outer query's aliases are considered external. for alias, table in query.alias_map.items(): clone.external_aliases[alias] = ( isinstance(table, Join) and table.join_field.related_model._meta.db_table != alias ) or ( isinstance(table, BaseTable) and table.table_name != table.table_alias ) return clone def get_external_cols(self): exprs = chain(self.annotations.values(), self.where.children) return [ col for col in self._gen_cols(exprs, include_external=True) if col.alias in self.external_aliases ] def get_group_by_cols(self, wrapper=None): # If wrapper is referenced by an alias for an explicit GROUP BY through # values() a reference to this expression and not the self must be # returned to ensure external column references are not grouped against # as well. external_cols = self.get_external_cols() if any(col.possibly_multivalued for col in external_cols): return [wrapper or self] return external_cols def as_sql(self, compiler, connection): # Some backends (e.g. Oracle) raise an error when a subquery contains # unnecessary ORDER BY clause. if ( self.subquery and not connection.features.ignores_unnecessary_order_by_in_subqueries ): self.clear_ordering(force=False) for query in self.combined_queries: query.clear_ordering(force=False) sql, params = self.get_compiler(connection=connection).as_sql() if self.subquery: sql = "(%s)" % sql return sql, params def resolve_lookup_value(self, value, can_reuse, allow_joins): if hasattr(value, "resolve_expression"): value = value.resolve_expression( self, reuse=can_reuse, allow_joins=allow_joins, ) elif isinstance(value, (list, tuple)): # The items of the iterable may be expressions and therefore need # to be resolved independently. values = ( self.resolve_lookup_value(sub_value, can_reuse, allow_joins) for sub_value in value ) type_ = type(value) if hasattr(type_, "_make"): # namedtuple return type_(*values) return type_(values) return value def solve_lookup_type(self, lookup, summarize=False): """ Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains'). """ lookup_splitted = lookup.split(LOOKUP_SEP) if self.annotations: annotation, expression_lookups = refs_expression( lookup_splitted, self.annotations ) if annotation: expression = self.annotations[annotation] if summarize: expression = Ref(annotation, expression) return expression_lookups, (), expression _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)] if len(lookup_parts) > 1 and not field_parts: raise FieldError( 'Invalid lookup "%s" for model %s".' % (lookup, self.get_meta().model.__name__) ) return lookup_parts, field_parts, False def check_query_object_type(self, value, opts, field): """ Check whether the object passed while querying is of the correct type. If not, raise a ValueError specifying the wrong object. """ if hasattr(value, "_meta"): if not check_rel_lookup_compatibility(value._meta.model, opts, field): raise ValueError( 'Cannot query "%s": Must be "%s" instance.' % (value, opts.object_name) ) def check_related_objects(self, field, value, opts): """Check the type of object passed to query relations.""" if field.is_relation: # Check that the field and the queryset use the same model in a # query like .filter(author=Author.objects.all()). For example, the # opts would be Author's (from the author field) and value.model # would be Author.objects.all() queryset's .model (Author also). # The field is the related field on the lhs side. if ( isinstance(value, Query) and not value.has_select_fields and not check_rel_lookup_compatibility(value.model, opts, field) ): raise ValueError( 'Cannot use QuerySet for "%s": Use a QuerySet for "%s".' % (value.model._meta.object_name, opts.object_name) ) elif hasattr(value, "_meta"): self.check_query_object_type(value, opts, field) elif hasattr(value, "__iter__"): for v in value: self.check_query_object_type(v, opts, field) def check_filterable(self, expression): """Raise an error if expression cannot be used in a WHERE clause.""" if hasattr(expression, "resolve_expression") and not getattr( expression, "filterable", True ): raise NotSupportedError( expression.__class__.__name__ + " is disallowed in the filter " "clause." ) if hasattr(expression, "get_source_expressions"): for expr in expression.get_source_expressions(): self.check_filterable(expr) def build_lookup(self, lookups, lhs, rhs): """ Try to extract transforms and lookup from given lhs. The lhs value is something that works like SQLExpression. The rhs value is what the lookup is going to compare against. The lookups is a list of names to extract using get_lookup() and get_transform(). """ # __exact is the default lookup if one isn't given. *transforms, lookup_name = lookups or ["exact"] for name in transforms: lhs = self.try_transform(lhs, name) # First try get_lookup() so that the lookup takes precedence if the lhs # supports both transform and lookup for the name. lookup_class = lhs.get_lookup(lookup_name) if not lookup_class: # A lookup wasn't found. Try to interpret the name as a transform # and do an Exact lookup against it. lhs = self.try_transform(lhs, lookup_name) lookup_name = "exact" lookup_class = lhs.get_lookup(lookup_name) if not lookup_class: return lookup = lookup_class(lhs, rhs) # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all # uses of None as a query value unless the lookup supports it. if lookup.rhs is None and not lookup.can_use_none_as_rhs: if lookup_name not in ("exact", "iexact"): raise ValueError("Cannot use None as a query value") return lhs.get_lookup("isnull")(lhs, True) # For Oracle '' is equivalent to null. The check must be done at this # stage because join promotion can't be done in the compiler. Using # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here. # A similar thing is done in is_nullable(), too. if ( lookup_name == "exact" and lookup.rhs == "" and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls ): return lhs.get_lookup("isnull")(lhs, True) return lookup def try_transform(self, lhs, name): """ Helper method for build_lookup(). Try to fetch and initialize a transform for name parameter from lhs. """ transform_class = lhs.get_transform(name) if transform_class: return transform_class(lhs) else: output_field = lhs.output_field.__class__ suggested_lookups = difflib.get_close_matches( name, output_field.get_lookups() ) if suggested_lookups: suggestion = ", perhaps you meant %s?" % " or ".join(suggested_lookups) else: suggestion = "." raise FieldError( "Unsupported lookup '%s' for %s or join on the field not " "permitted%s" % (name, output_field.__name__, suggestion) ) def build_filter( self, filter_expr, branch_negated=False, current_negated=False, can_reuse=None, allow_joins=True, split_subq=True, reuse_with_filtered_relation=False, check_filterable=True, summarize=False, ): """ Build a WhereNode for a single filter clause but don't add it to this Query. Query.add_q() will then add this filter to the where Node. The 'branch_negated' tells us if the current branch contains any negations. This will be used to determine if subqueries are needed. The 'current_negated' is used to determine if the current filter is negated or not and this will be used to determine if IS NULL filtering is needed. The difference between current_negated and branch_negated is that branch_negated is set on first negation, but current_negated is flipped for each negation. Note that add_filter will not do any negating itself, that is done upper in the code by add_q(). The 'can_reuse' is a set of reusable joins for multijoins. If 'reuse_with_filtered_relation' is True, then only joins in can_reuse will be reused. The method will create a filter clause that can be added to the current query. However, if the filter isn't added to the query then the caller is responsible for unreffing the joins used. """ if isinstance(filter_expr, dict): raise FieldError("Cannot parse keyword query as dict") if isinstance(filter_expr, Q): return self._add_q( filter_expr, branch_negated=branch_negated, current_negated=current_negated, used_aliases=can_reuse, allow_joins=allow_joins, split_subq=split_subq, check_filterable=check_filterable, summarize=summarize, ) if hasattr(filter_expr, "resolve_expression"): if not getattr(filter_expr, "conditional", False): raise TypeError("Cannot filter against a non-conditional expression.") condition = filter_expr.resolve_expression( self, allow_joins=allow_joins, summarize=summarize ) if not isinstance(condition, Lookup): condition = self.build_lookup(["exact"], condition, True) return WhereNode([condition], connector=AND), [] arg, value = filter_expr if not arg: raise FieldError("Cannot parse keyword query %r" % arg) lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize) if check_filterable: self.check_filterable(reffed_expression) if not allow_joins and len(parts) > 1: raise FieldError("Joined field references are not permitted in this query") pre_joins = self.alias_refcount.copy() value = self.resolve_lookup_value(value, can_reuse, allow_joins) used_joins = { k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0) } if check_filterable: self.check_filterable(value) if reffed_expression: condition = self.build_lookup(lookups, reffed_expression, value) return WhereNode([condition], connector=AND), [] opts = self.get_meta() alias = self.get_initial_alias() allow_many = not branch_negated or not split_subq try: join_info = self.setup_joins( parts, opts, alias, can_reuse=can_reuse, allow_many=allow_many, reuse_with_filtered_relation=reuse_with_filtered_relation, ) # Prevent iterator from being consumed by check_related_objects() if isinstance(value, Iterator): value = list(value) self.check_related_objects(join_info.final_field, value, join_info.opts) # split_exclude() needs to know which joins were generated for the # lookup parts self._lookup_joins = join_info.joins except MultiJoin as e: return self.split_exclude(filter_expr, can_reuse, e.names_with_path) # Update used_joins before trimming since they are reused to determine # which joins could be later promoted to INNER. used_joins.update(join_info.joins) targets, alias, join_list = self.trim_joins( join_info.targets, join_info.joins, join_info.path ) if can_reuse is not None: can_reuse.update(join_list) if join_info.final_field.is_relation: if len(targets) == 1: col = self._get_col(targets[0], join_info.final_field, alias) else: col = MultiColSource( alias, targets, join_info.targets, join_info.final_field ) else: col = self._get_col(targets[0], join_info.final_field, alias) condition = self.build_lookup(lookups, col, value) lookup_type = condition.lookup_name clause = WhereNode([condition], connector=AND) require_outer = ( lookup_type == "isnull" and condition.rhs is True and not current_negated ) if ( current_negated and (lookup_type != "isnull" or condition.rhs is False) and condition.rhs is not None ): require_outer = True if lookup_type != "isnull": # The condition added here will be SQL like this: # NOT (col IS NOT NULL), where the first NOT is added in # upper layers of code. The reason for addition is that if col # is null, then col != someval will result in SQL "unknown" # which isn't the same as in Python. The Python None handling # is wanted, and it can be gotten by # (col IS NULL OR col != someval) # <=> # NOT (col IS NOT NULL AND col = someval). if ( self.is_nullable(targets[0]) or self.alias_map[join_list[-1]].join_type == LOUTER ): lookup_class = targets[0].get_lookup("isnull") col = self._get_col(targets[0], join_info.targets[0], alias) clause.add(lookup_class(col, False), AND) # If someval is a nullable column, someval IS NOT NULL is # added. if isinstance(value, Col) and self.is_nullable(value.target): lookup_class = value.target.get_lookup("isnull") clause.add(lookup_class(value, False), AND) return clause, used_joins if not require_outer else () def add_filter(self, filter_lhs, filter_rhs): self.add_q(Q((filter_lhs, filter_rhs))) def add_q(self, q_object): """ A preprocessor for the internal _add_q(). Responsible for doing final join promotion. """ # For join promotion this case is doing an AND for the added q_object # and existing conditions. So, any existing inner join forces the join # type to remain inner. Existing outer joins can however be demoted. # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if # rel_a doesn't produce any rows, then the whole condition must fail. # So, demotion is OK. existing_inner = { a for a in self.alias_map if self.alias_map[a].join_type == INNER } clause, _ = self._add_q(q_object, self.used_aliases) if clause: self.where.add(clause, AND) self.demote_joins(existing_inner) def build_where(self, filter_expr): return self.build_filter(filter_expr, allow_joins=False)[0] def clear_where(self): self.where = WhereNode() def _add_q( self, q_object, used_aliases, branch_negated=False, current_negated=False, allow_joins=True, split_subq=True, check_filterable=True, summarize=False, ): """Add a Q-object to the current filter.""" connector = q_object.connector current_negated ^= q_object.negated branch_negated = branch_negated or q_object.negated target_clause = WhereNode(connector=connector, negated=q_object.negated) joinpromoter = JoinPromoter( q_object.connector, len(q_object.children), current_negated ) for child in q_object.children: child_clause, needed_inner = self.build_filter( child, can_reuse=used_aliases, branch_negated=branch_negated, current_negated=current_negated, allow_joins=allow_joins, split_subq=split_subq, check_filterable=check_filterable, summarize=summarize, ) joinpromoter.add_votes(needed_inner) if child_clause: target_clause.add(child_clause, connector) needed_inner = joinpromoter.update_join_types(self) return target_clause, needed_inner def build_filtered_relation_q( self, q_object, reuse, branch_negated=False, current_negated=False ): """Add a FilteredRelation object to the current filter.""" connector = q_object.connector current_negated ^= q_object.negated branch_negated = branch_negated or q_object.negated target_clause = WhereNode(connector=connector, negated=q_object.negated) for child in q_object.children: if isinstance(child, Node): child_clause = self.build_filtered_relation_q( child, reuse=reuse, branch_negated=branch_negated, current_negated=current_negated, ) else: child_clause, _ = self.build_filter( child, can_reuse=reuse, branch_negated=branch_negated, current_negated=current_negated, allow_joins=True, split_subq=False, reuse_with_filtered_relation=True, ) target_clause.add(child_clause, connector) return target_clause def add_filtered_relation(self, filtered_relation, alias): filtered_relation.alias = alias lookups = dict(get_children_from_q(filtered_relation.condition)) relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type( filtered_relation.relation_name ) if relation_lookup_parts: raise ValueError( "FilteredRelation's relation_name cannot contain lookups " "(got %r)." % filtered_relation.relation_name ) for lookup in chain(lookups): lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup) shift = 2 if not lookup_parts else 1 lookup_field_path = lookup_field_parts[:-shift] for idx, lookup_field_part in enumerate(lookup_field_path): if len(relation_field_parts) > idx: if relation_field_parts[idx] != lookup_field_part: raise ValueError( "FilteredRelation's condition doesn't support " "relations outside the %r (got %r)." % (filtered_relation.relation_name, lookup) ) else: raise ValueError( "FilteredRelation's condition doesn't support nested " "relations deeper than the relation_name (got %r for " "%r)." % (lookup, filtered_relation.relation_name) ) self._filtered_relations[filtered_relation.alias] = filtered_relation def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False): """ Walk the list of names and turns them into PathInfo tuples. A single name in 'names' can generate multiple PathInfos (m2m, for example). 'names' is the path of names to travel, 'opts' is the model Options we start the name resolving from, 'allow_many' is as for setup_joins(). If fail_on_missing is set to True, then a name that can't be resolved will generate a FieldError. Return a list of PathInfo tuples. In addition return the final field (the last used join field) and target (which is a field guaranteed to contain the same value as the final field). Finally, return those names that weren't found (which are likely transforms and the final lookup). """ path, names_with_path = [], [] for pos, name in enumerate(names): cur_names_with_path = (name, []) if name == "pk": name = opts.pk.name field = None filtered_relation = None try: if opts is None: raise FieldDoesNotExist field = opts.get_field(name) except FieldDoesNotExist: if name in self.annotation_select: field = self.annotation_select[name].output_field elif name in self._filtered_relations and pos == 0: filtered_relation = self._filtered_relations[name] if LOOKUP_SEP in filtered_relation.relation_name: parts = filtered_relation.relation_name.split(LOOKUP_SEP) filtered_relation_path, field, _, _ = self.names_to_path( parts, opts, allow_many, fail_on_missing, ) path.extend(filtered_relation_path[:-1]) else: field = opts.get_field(filtered_relation.relation_name) if field is not None: # Fields that contain one-to-many relations with a generic # model (like a GenericForeignKey) cannot generate reverse # relations and therefore cannot be used for reverse querying. if field.is_relation and not field.related_model: raise FieldError( "Field %r does not generate an automatic reverse " "relation and therefore cannot be used for reverse " "querying. If it is a GenericForeignKey, consider " "adding a GenericRelation." % name ) try: model = field.model._meta.concrete_model except AttributeError: # QuerySet.annotate() may introduce fields that aren't # attached to a model. model = None else: # We didn't find the current field, so move position back # one step. pos -= 1 if pos == -1 or fail_on_missing: available = sorted( [ *get_field_names_from_opts(opts), *self.annotation_select, *self._filtered_relations, ] ) raise FieldError( "Cannot resolve keyword '%s' into field. " "Choices are: %s" % (name, ", ".join(available)) ) break # Check if we need any joins for concrete inheritance cases (the # field lives in parent, but we are currently in one of its # children) if opts is not None and model is not opts.model: path_to_parent = opts.get_path_to_parent(model) if path_to_parent: path.extend(path_to_parent) cur_names_with_path[1].extend(path_to_parent) opts = path_to_parent[-1].to_opts if hasattr(field, "path_infos"): if filtered_relation: pathinfos = field.get_path_info(filtered_relation) else: pathinfos = field.path_infos if not allow_many: for inner_pos, p in enumerate(pathinfos): if p.m2m: cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1]) names_with_path.append(cur_names_with_path) raise MultiJoin(pos + 1, names_with_path) last = pathinfos[-1] path.extend(pathinfos) final_field = last.join_field opts = last.to_opts targets = last.target_fields cur_names_with_path[1].extend(pathinfos) names_with_path.append(cur_names_with_path) else: # Local non-relational field. final_field = field targets = (field,) if fail_on_missing and pos + 1 != len(names): raise FieldError( "Cannot resolve keyword %r into field. Join on '%s'" " not permitted." % (names[pos + 1], name) ) break return path, final_field, targets, names[pos + 1 :] def setup_joins( self, names, opts, alias, can_reuse=None, allow_many=True, reuse_with_filtered_relation=False, ): """ Compute the necessary table joins for the passage through the fields given in 'names'. 'opts' is the Options class for the current model (which gives the table we are starting from), 'alias' is the alias for the table to start the joining from. The 'can_reuse' defines the reverse foreign key joins we can reuse. It can be None in which case all joins are reusable or a set of aliases that can be reused. Note that non-reverse foreign keys are always reusable when using setup_joins(). The 'reuse_with_filtered_relation' can be used to force 'can_reuse' parameter and force the relation on the given connections. If 'allow_many' is False, then any reverse foreign key seen will generate a MultiJoin exception. Return the final field involved in the joins, the target field (used for any 'where' constraint), the final 'opts' value, the joins, the field path traveled to generate the joins, and a transform function that takes a field and alias and is equivalent to `field.get_col(alias)` in the simple case but wraps field transforms if they were included in names. The target field is the field containing the concrete value. Final field can be something different, for example foreign key pointing to that value. Final field is needed for example in some value conversions (convert 'obj' in fk__id=obj to pk val using the foreign key field for example). """ joins = [alias] # The transform can't be applied yet, as joins must be trimmed later. # To avoid making every caller of this method look up transforms # directly, compute transforms here and create a partial that converts # fields to the appropriate wrapped version. def final_transformer(field, alias): if not self.alias_cols: alias = None return field.get_col(alias) # Try resolving all the names as fields first. If there's an error, # treat trailing names as lookups until a field can be resolved. last_field_exception = None for pivot in range(len(names), 0, -1): try: path, final_field, targets, rest = self.names_to_path( names[:pivot], opts, allow_many, fail_on_missing=True, ) except FieldError as exc: if pivot == 1: # The first item cannot be a lookup, so it's safe # to raise the field error here. raise else: last_field_exception = exc else: # The transforms are the remaining items that couldn't be # resolved into fields. transforms = names[pivot:] break for name in transforms: def transform(field, alias, *, name, previous): try: wrapped = previous(field, alias) return self.try_transform(wrapped, name) except FieldError: # FieldError is raised if the transform doesn't exist. if isinstance(final_field, Field) and last_field_exception: raise last_field_exception else: raise final_transformer = functools.partial( transform, name=name, previous=final_transformer ) final_transformer.has_transforms = True # Then, add the path to the query's joins. Note that we can't trim # joins at this stage - we will need the information about join type # of the trimmed joins. for join in path: if join.filtered_relation: filtered_relation = join.filtered_relation.clone() table_alias = filtered_relation.alias else: filtered_relation = None table_alias = None opts = join.to_opts if join.direct: nullable = self.is_nullable(join.join_field) else: nullable = True connection = self.join_class( opts.db_table, alias, table_alias, INNER, join.join_field, nullable, filtered_relation=filtered_relation, ) reuse = can_reuse if join.m2m or reuse_with_filtered_relation else None alias = self.join( connection, reuse=reuse, reuse_with_filtered_relation=reuse_with_filtered_relation, ) joins.append(alias) if filtered_relation: filtered_relation.path = joins[:] return JoinInfo(final_field, targets, opts, joins, path, final_transformer) def trim_joins(self, targets, joins, path): """ The 'target' parameter is the final field being joined to, 'joins' is the full list of join aliases. The 'path' contain the PathInfos used to create the joins. Return the final target field and table alias and the new active joins. Always trim any direct join if the target column is already in the previous table. Can't trim reverse joins as it's unknown if there's anything on the other side of the join. """ joins = joins[:] for pos, info in enumerate(reversed(path)): if len(joins) == 1 or not info.direct: break if info.filtered_relation: break join_targets = {t.column for t in info.join_field.foreign_related_fields} cur_targets = {t.column for t in targets} if not cur_targets.issubset(join_targets): break targets_dict = { r[1].column: r[0] for r in info.join_field.related_fields if r[1].column in cur_targets } targets = tuple(targets_dict[t.column] for t in targets) self.unref_alias(joins.pop()) return targets, joins[-1], joins @classmethod def _gen_cols(cls, exprs, include_external=False, resolve_refs=True): for expr in exprs: if isinstance(expr, Col): yield expr elif include_external and callable( getattr(expr, "get_external_cols", None) ): yield from expr.get_external_cols() elif hasattr(expr, "get_source_expressions"): if not resolve_refs and isinstance(expr, Ref): continue yield from cls._gen_cols( expr.get_source_expressions(), include_external=include_external, resolve_refs=resolve_refs, ) @classmethod def _gen_col_aliases(cls, exprs): yield from (expr.alias for expr in cls._gen_cols(exprs)) def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False): annotation = self.annotations.get(name) if annotation is not None: if not allow_joins: for alias in self._gen_col_aliases([annotation]): if isinstance(self.alias_map[alias], Join): raise FieldError( "Joined field references are not permitted in this query" ) if summarize: # Summarize currently means we are doing an aggregate() query # which is executed as a wrapped subquery if any of the # aggregate() elements reference an existing annotation. In # that case we need to return a Ref to the subquery's annotation. if name not in self.annotation_select: raise FieldError( "Cannot aggregate over the '%s' alias. Use annotate() " "to promote it." % name ) return Ref(name, self.annotation_select[name]) else: return annotation else: field_list = name.split(LOOKUP_SEP) annotation = self.annotations.get(field_list[0]) if annotation is not None: for transform in field_list[1:]: annotation = self.try_transform(annotation, transform) return annotation join_info = self.setup_joins( field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse ) targets, final_alias, join_list = self.trim_joins( join_info.targets, join_info.joins, join_info.path ) if not allow_joins and len(join_list) > 1: raise FieldError( "Joined field references are not permitted in this query" ) if len(targets) > 1: raise FieldError( "Referencing multicolumn fields with F() objects isn't supported" ) # Verify that the last lookup in name is a field or a transform: # transform_function() raises FieldError if not. transform = join_info.transform_function(targets[0], final_alias) if reuse is not None: reuse.update(join_list) return transform def split_exclude(self, filter_expr, can_reuse, names_with_path): """ When doing an exclude against any kind of N-to-many relation, we need to use a subquery. This method constructs the nested query, given the original exclude filter (filter_expr) and the portion up to the first N-to-many relation field. For example, if the origin filter is ~Q(child__name='foo'), filter_expr is ('child__name', 'foo') and can_reuse is a set of joins usable for filters in the original query. We will turn this into equivalent of: WHERE NOT EXISTS( SELECT 1 FROM child WHERE name = 'foo' AND child.parent_id = parent.id LIMIT 1 ) """ # Generate the inner query. query = self.__class__(self.model) query._filtered_relations = self._filtered_relations filter_lhs, filter_rhs = filter_expr if isinstance(filter_rhs, OuterRef): filter_rhs = OuterRef(filter_rhs) elif isinstance(filter_rhs, F): filter_rhs = OuterRef(filter_rhs.name) query.add_filter(filter_lhs, filter_rhs) query.clear_ordering(force=True) # Try to have as simple as possible subquery -> trim leading joins from # the subquery. trimmed_prefix, contains_louter = query.trim_start(names_with_path) col = query.select[0] select_field = col.target alias = col.alias if alias in can_reuse: pk = select_field.model._meta.pk # Need to add a restriction so that outer query's filters are in effect for # the subquery, too. query.bump_prefix(self) lookup_class = select_field.get_lookup("exact") # Note that the query.select[0].alias is different from alias # due to bump_prefix above. lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias)) query.where.add(lookup, AND) query.external_aliases[alias] = True lookup_class = select_field.get_lookup("exact") lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix)) query.where.add(lookup, AND) condition, needed_inner = self.build_filter(Exists(query)) if contains_louter: or_null_condition, _ = self.build_filter( ("%s__isnull" % trimmed_prefix, True), current_negated=True, branch_negated=True, can_reuse=can_reuse, ) condition.add(or_null_condition, OR) # Note that the end result will be: # (outercol NOT IN innerq AND outercol IS NOT NULL) OR outercol IS NULL. # This might look crazy but due to how IN works, this seems to be # correct. If the IS NOT NULL check is removed then outercol NOT # IN will return UNKNOWN. If the IS NULL check is removed, then if # outercol IS NULL we will not match the row. return condition, needed_inner def set_empty(self): self.where.add(NothingNode(), AND) for query in self.combined_queries: query.set_empty() def is_empty(self): return any(isinstance(c, NothingNode) for c in self.where.children) def set_limits(self, low=None, high=None): """ Adjust the limits on the rows retrieved. Use low/high to set these, as it makes it more Pythonic to read and write. When the SQL query is created, convert them to the appropriate offset and limit values. Apply any limits passed in here to the existing constraints. Add low to the current low value and clamp both to any existing high value. """ if high is not None: if self.high_mark is not None: self.high_mark = min(self.high_mark, self.low_mark + high) else: self.high_mark = self.low_mark + high if low is not None: if self.high_mark is not None: self.low_mark = min(self.high_mark, self.low_mark + low) else: self.low_mark = self.low_mark + low if self.low_mark == self.high_mark: self.set_empty() def clear_limits(self): """Clear any existing limits.""" self.low_mark, self.high_mark = 0, None @property def is_sliced(self): return self.low_mark != 0 or self.high_mark is not None def has_limit_one(self): return self.high_mark is not None and (self.high_mark - self.low_mark) == 1 def can_filter(self): """ Return True if adding filters to this instance is still possible. Typically, this means no limits or offsets have been put on the results. """ return not self.is_sliced def clear_select_clause(self): """Remove all fields from SELECT clause.""" self.select = () self.default_cols = False self.select_related = False self.set_extra_mask(()) self.set_annotation_mask(()) def clear_select_fields(self): """ Clear the list of fields to select (but not extra_select columns). Some queryset types completely replace any existing list of select columns. """ self.select = () self.values_select = () def add_select_col(self, col, name): self.select += (col,) self.values_select += (name,) def set_select(self, cols): self.default_cols = False self.select = tuple(cols) def add_distinct_fields(self, *field_names): """ Add and resolve the given fields to the query's "distinct on" clause. """ self.distinct_fields = field_names self.distinct = True def add_fields(self, field_names, allow_m2m=True): """ Add the given (model) fields to the select set. Add the field names in the order specified. """ alias = self.get_initial_alias() opts = self.get_meta() try: cols = [] for name in field_names: # Join promotion note - we must not remove any rows here, so # if there is no existing joins, use outer join. join_info = self.setup_joins( name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m ) targets, final_alias, joins = self.trim_joins( join_info.targets, join_info.joins, join_info.path, ) for target in targets: cols.append(join_info.transform_function(target, final_alias)) if cols: self.set_select(cols) except MultiJoin: raise FieldError("Invalid field name: '%s'" % name) except FieldError: if LOOKUP_SEP in name: # For lookups spanning over relationships, show the error # from the model on which the lookup failed. raise elif name in self.annotations: raise FieldError( "Cannot select the '%s' alias. Use annotate() to promote " "it." % name ) else: names = sorted( [ *get_field_names_from_opts(opts), *self.extra, *self.annotation_select, *self._filtered_relations, ] ) raise FieldError( "Cannot resolve keyword %r into field. " "Choices are: %s" % (name, ", ".join(names)) ) def add_ordering(self, *ordering): """ Add items from the 'ordering' sequence to the query's "order by" clause. These items are either field names (not column names) -- possibly with a direction prefix ('-' or '?') -- or OrderBy expressions. If 'ordering' is empty, clear all ordering from the query. """ errors = [] for item in ordering: if isinstance(item, str): if item == "?": continue item = item.removeprefix("-") if item in self.annotations: continue if self.extra and item in self.extra: continue # names_to_path() validates the lookup. A descriptive # FieldError will be raise if it's not. self.names_to_path(item.split(LOOKUP_SEP), self.model._meta) elif not hasattr(item, "resolve_expression"): errors.append(item) if getattr(item, "contains_aggregate", False): raise FieldError( "Using an aggregate in order_by() without also including " "it in annotate() is not allowed: %s" % item ) if errors: raise FieldError("Invalid order_by arguments: %s" % errors) if ordering: self.order_by += ordering else: self.default_ordering = False def clear_ordering(self, force=False, clear_default=True): """ Remove any ordering settings if the current query allows it without side effects, set 'force' to True to clear the ordering regardless. If 'clear_default' is True, there will be no ordering in the resulting query (not even the model's default). """ if not force and ( self.is_sliced or self.distinct_fields or self.select_for_update ): return self.order_by = () self.extra_order_by = () if clear_default: self.default_ordering = False def set_group_by(self, allow_aliases=True): """ Expand the GROUP BY clause required by the query. This will usually be the set of all non-aggregate fields in the return data. If the database backend supports grouping by the primary key, and the query would be equivalent, the optimization will be made automatically. """ if allow_aliases and self.values_select: # If grouping by aliases is allowed assign selected value aliases # by moving them to annotations. group_by_annotations = {} values_select = {} for alias, expr in zip(self.values_select, self.select): if isinstance(expr, Col): values_select[alias] = expr else: group_by_annotations[alias] = expr self.annotations = {**group_by_annotations, **self.annotations} self.append_annotation_mask(group_by_annotations) self.select = tuple(values_select.values()) self.values_select = tuple(values_select) group_by = list(self.select) for alias, annotation in self.annotation_select.items(): if not (group_by_cols := annotation.get_group_by_cols()): continue if allow_aliases and not annotation.contains_aggregate: group_by.append(Ref(alias, annotation)) else: group_by.extend(group_by_cols) self.group_by = tuple(group_by) def add_select_related(self, fields): """ Set up the select_related data structure so that we only select certain related models (as opposed to all models, when self.select_related=True). """ if isinstance(self.select_related, bool): field_dict = {} else: field_dict = self.select_related for field in fields: d = field_dict for part in field.split(LOOKUP_SEP): d = d.setdefault(part, {}) self.select_related = field_dict def add_extra(self, select, select_params, where, params, tables, order_by): """ Add data to the various extra_* attributes for user-created additions to the query. """ if select: # We need to pair any placeholder markers in the 'select' # dictionary with their parameters in 'select_params' so that # subsequent updates to the select dictionary also adjust the # parameters appropriately. select_pairs = {} if select_params: param_iter = iter(select_params) else: param_iter = iter([]) for name, entry in select.items(): self.check_alias(name) entry = str(entry) entry_params = [] pos = entry.find("%s") while pos != -1: if pos == 0 or entry[pos - 1] != "%": entry_params.append(next(param_iter)) pos = entry.find("%s", pos + 2) select_pairs[name] = (entry, entry_params) self.extra.update(select_pairs) if where or params: self.where.add(ExtraWhere(where, params), AND) if tables: self.extra_tables += tuple(tables) if order_by: self.extra_order_by = order_by def clear_deferred_loading(self): """Remove any fields from the deferred loading set.""" self.deferred_loading = (frozenset(), True) def add_deferred_loading(self, field_names): """ Add the given list of model field names to the set of fields to exclude from loading from the database when automatic column selection is done. Add the new field names to any existing field names that are deferred (or removed from any existing field names that are marked as the only ones for immediate loading). """ # Fields on related models are stored in the literal double-underscore # format, so that we can use a set datastructure. We do the foo__bar # splitting and handling when computing the SQL column names (as part of # get_columns()). existing, defer = self.deferred_loading if defer: # Add to existing deferred names. self.deferred_loading = existing.union(field_names), True else: # Remove names from the set of any existing "immediate load" names. if new_existing := existing.difference(field_names): self.deferred_loading = new_existing, False else: self.clear_deferred_loading() if new_only := set(field_names).difference(existing): self.deferred_loading = new_only, True def add_immediate_loading(self, field_names): """ Add the given list of model field names to the set of fields to retrieve when the SQL is executed ("immediate loading" fields). The field names replace any existing immediate loading field names. If there are field names already specified for deferred loading, remove those names from the new field_names before storing the new names for immediate loading. (That is, immediate loading overrides any existing immediate values, but respects existing deferrals.) """ existing, defer = self.deferred_loading field_names = set(field_names) if "pk" in field_names: field_names.remove("pk") field_names.add(self.get_meta().pk.name) if defer: # Remove any existing deferred names from the current set before # setting the new names. self.deferred_loading = field_names.difference(existing), False else: # Replace any existing "immediate load" field names. self.deferred_loading = frozenset(field_names), False def set_annotation_mask(self, names): """Set the mask of annotations that will be returned by the SELECT.""" if names is None: self.annotation_select_mask = None else: self.annotation_select_mask = set(names) self._annotation_select_cache = None def append_annotation_mask(self, names): if self.annotation_select_mask is not None: self.set_annotation_mask(self.annotation_select_mask.union(names)) def set_extra_mask(self, names): """ Set the mask of extra select items that will be returned by SELECT. Don't remove them from the Query since they might be used later. """ if names is None: self.extra_select_mask = None else: self.extra_select_mask = set(names) self._extra_select_cache = None def set_values(self, fields): self.select_related = False self.clear_deferred_loading() self.clear_select_fields() self.has_select_fields = True if fields: field_names = [] extra_names = [] annotation_names = [] if not self.extra and not self.annotations: # Shortcut - if there are no extra or annotations, then # the values() clause must be just field names. field_names = list(fields) else: self.default_cols = False for f in fields: if f in self.extra_select: extra_names.append(f) elif f in self.annotation_select: annotation_names.append(f) else: field_names.append(f) self.set_extra_mask(extra_names) self.set_annotation_mask(annotation_names) selected = frozenset(field_names + extra_names + annotation_names) else: field_names = [f.attname for f in self.model._meta.concrete_fields] selected = frozenset(field_names) # Selected annotations must be known before setting the GROUP BY # clause. if self.group_by is True: self.add_fields( (f.attname for f in self.model._meta.concrete_fields), False ) # Disable GROUP BY aliases to avoid orphaning references to the # SELECT clause which is about to be cleared. self.set_group_by(allow_aliases=False) self.clear_select_fields() elif self.group_by: # Resolve GROUP BY annotation references if they are not part of # the selected fields anymore. group_by = [] for expr in self.group_by: if isinstance(expr, Ref) and expr.refs not in selected: expr = self.annotations[expr.refs] group_by.append(expr) self.group_by = tuple(group_by) self.values_select = tuple(field_names) self.add_fields(field_names, True) @property def annotation_select(self): """ Return the dictionary of aggregate columns that are not masked and should be used in the SELECT clause. Cache this result for performance. """ if self._annotation_select_cache is not None: return self._annotation_select_cache elif not self.annotations: return {} elif self.annotation_select_mask is not None: self._annotation_select_cache = { k: v for k, v in self.annotations.items() if k in self.annotation_select_mask } return self._annotation_select_cache else: return self.annotations @property def extra_select(self): if self._extra_select_cache is not None: return self._extra_select_cache if not self.extra: return {} elif self.extra_select_mask is not None: self._extra_select_cache = { k: v for k, v in self.extra.items() if k in self.extra_select_mask } return self._extra_select_cache else: return self.extra def trim_start(self, names_with_path): """ Trim joins from the start of the join path. The candidates for trim are the PathInfos in names_with_path structure that are m2m joins. Also set the select column so the start matches the join. This method is meant to be used for generating the subquery joins & cols in split_exclude(). Return a lookup usable for doing outerq.filter(lookup=self) and a boolean indicating if the joins in the prefix contain a LEFT OUTER join. _""" all_paths = [] for _, paths in names_with_path: all_paths.extend(paths) contains_louter = False # Trim and operate only on tables that were generated for # the lookup part of the query. That is, avoid trimming # joins generated for F() expressions. lookup_tables = [ t for t in self.alias_map if t in self._lookup_joins or t == self.base_table ] for trimmed_paths, path in enumerate(all_paths): if path.m2m: break if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER: contains_louter = True alias = lookup_tables[trimmed_paths] self.unref_alias(alias) # The path.join_field is a Rel, lets get the other side's field join_field = path.join_field.field # Build the filter prefix. paths_in_prefix = trimmed_paths trimmed_prefix = [] for name, path in names_with_path: if paths_in_prefix - len(path) < 0: break trimmed_prefix.append(name) paths_in_prefix -= len(path) trimmed_prefix.append(join_field.foreign_related_fields[0].name) trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix) # Lets still see if we can trim the first join from the inner query # (that is, self). We can't do this for: # - LEFT JOINs because we would miss those rows that have nothing on # the outer side, # - INNER JOINs from filtered relations because we would miss their # filters. first_join = self.alias_map[lookup_tables[trimmed_paths + 1]] if first_join.join_type != LOUTER and not first_join.filtered_relation: select_fields = [r[0] for r in join_field.related_fields] select_alias = lookup_tables[trimmed_paths + 1] self.unref_alias(lookup_tables[trimmed_paths]) extra_restriction = join_field.get_extra_restriction( None, lookup_tables[trimmed_paths + 1] ) if extra_restriction: self.where.add(extra_restriction, AND) else: # TODO: It might be possible to trim more joins from the start of the # inner query if it happens to have a longer join chain containing the # values in select_fields. Lets punt this one for now. select_fields = [r[1] for r in join_field.related_fields] select_alias = lookup_tables[trimmed_paths] # The found starting point is likely a join_class instead of a # base_table_class reference. But the first entry in the query's FROM # clause must not be a JOIN. for table in self.alias_map: if self.alias_refcount[table] > 0: self.alias_map[table] = self.base_table_class( self.alias_map[table].table_name, table, ) break self.set_select([f.get_col(select_alias) for f in select_fields]) return trimmed_prefix, contains_louter def is_nullable(self, field): """ Check if the given field should be treated as nullable. Some backends treat '' as null and Django treats such fields as nullable for those backends. In such situations field.null can be False even if we should treat the field as nullable. """ # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have # (nor should it have) knowledge of which connection is going to be # used. The proper fix would be to defer all decisions where # is_nullable() is needed to the compiler stage, but that is not easy # to do currently. return field.null or ( field.empty_strings_allowed and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls ) def get_order_dir(field, default="ASC"): """ Return the field name and direction for an order specification. For example, '-foo' is returned as ('foo', 'DESC'). The 'default' param is used to indicate which way no prefix (or a '+' prefix) should sort. The '-' prefix always sorts the opposite way. """ dirn = ORDER_DIR[default] if field[0] == "-": return field[1:], dirn[1] return field, dirn[0] class JoinPromoter: """ A class to abstract away join promotion problems for complex filter conditions. """ def __init__(self, connector, num_children, negated): self.connector = connector self.negated = negated if self.negated: if connector == AND: self.effective_connector = OR else: self.effective_connector = AND else: self.effective_connector = self.connector self.num_children = num_children # Maps of table alias to how many times it is seen as required for # inner and/or outer joins. self.votes = Counter() def __repr__(self): return ( f"{self.__class__.__qualname__}(connector={self.connector!r}, " f"num_children={self.num_children!r}, negated={self.negated!r})" ) def add_votes(self, votes): """ Add single vote per item to self.votes. Parameter can be any iterable. """ self.votes.update(votes) def update_join_types(self, query): """ Change join types so that the generated query is as efficient as possible, but still correct. So, change as many joins as possible to INNER, but don't make OUTER joins INNER if that could remove results from the query. """ to_promote = set() to_demote = set() # The effective_connector is used so that NOT (a AND b) is treated # similarly to (a OR b) for join promotion. for table, votes in self.votes.items(): # We must use outer joins in OR case when the join isn't contained # in all of the joins. Otherwise the INNER JOIN itself could remove # valid results. Consider the case where a model with rel_a and # rel_b relations is queried with rel_a__col=1 | rel_b__col=2. Now, # if rel_a join doesn't produce any results is null (for example # reverse foreign key or null value in direct foreign key), and # there is a matching row in rel_b with col=2, then an INNER join # to rel_a would remove a valid match from the query. So, we need # to promote any existing INNER to LOUTER (it is possible this # promotion in turn will be demoted later on). if self.effective_connector == OR and votes < self.num_children: to_promote.add(table) # If connector is AND and there is a filter that can match only # when there is a joinable row, then use INNER. For example, in # rel_a__col=1 & rel_b__col=2, if either of the rels produce NULL # as join output, then the col=1 or col=2 can't match (as # NULL=anything is always false). # For the OR case, if all children voted for a join to be inner, # then we can use INNER for the join. For example: # (rel_a__col__icontains=Alex | rel_a__col__icontains=Russell) # then if rel_a doesn't produce any rows, the whole condition # can't match. Hence we can safely use INNER join. if self.effective_connector == AND or ( self.effective_connector == OR and votes == self.num_children ): to_demote.add(table) # Finally, what happens in cases where we have: # (rel_a__col=1|rel_b__col=2) & rel_a__col__gte=0 # Now, we first generate the OR clause, and promote joins for it # in the first if branch above. Both rel_a and rel_b are promoted # to LOUTER joins. After that we do the AND case. The OR case # voted no inner joins but the rel_a__col__gte=0 votes inner join # for rel_a. We demote it back to INNER join (in AND case a single # vote is enough). The demotion is OK, if rel_a doesn't produce # rows, then the rel_a__col__gte=0 clause can't be true, and thus # the whole clause must be false. So, it is safe to use INNER # join. # Note that in this example we could just as well have the __gte # clause and the OR clause swapped. Or we could replace the __gte # clause with an OR clause containing rel_a__col=1|rel_a__col=2, # and again we could safely demote to INNER. query.promote_joins(to_promote) query.demote_joins(to_demote) return to_demote
6f69117a49e6541b3bae1b3b7722cb59224d4a07974b5d2566adebf1f0287034
# Django documentation build configuration file, created by # sphinx-quickstart on Thu Mar 27 09:06:53 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't picklable (module imports are okay, they're removed automatically). # # All configuration values have a default; values that are commented out # serve to show the default. import sys from os.path import abspath, dirname, join # Workaround for sphinx-build recursion limit overflow: # pickle.dump(doctree, f, pickle.HIGHEST_PROTOCOL) # RuntimeError: maximum recursion depth exceeded while pickling an object # # Python's default allowed recursion depth is 1000 but this isn't enough for # building docs/ref/settings.txt sometimes. # https://groups.google.com/g/sphinx-dev/c/MtRf64eGtv4/discussion sys.setrecursionlimit(2000) # Make sure we get the version of this copy of Django sys.path.insert(1, dirname(dirname(abspath(__file__)))) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.append(abspath(join(dirname(__file__), "_ext"))) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = "4.5.0" # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "djangodocs", "sphinx.ext.extlinks", "sphinx.ext.intersphinx", "sphinx.ext.viewcode", "sphinx.ext.autosectionlabel", ] # AutosectionLabel settings. # Uses a <page>:<label> schema which doesn't work for duplicate sub-section # labels, so set max depth. autosectionlabel_prefix_document = True autosectionlabel_maxdepth = 2 # Linkcheck settings. linkcheck_ignore = [ # Special-use addresses and domain names. (RFC 6761/6890) r"^https?://(?:127\.0\.0\.1|\[::1\])(?::\d+)?/", r"^https?://(?:[^/\.]+\.)*example\.(?:com|net|org)(?::\d+)?/", r"^https?://(?:[^/\.]+\.)*(?:example|invalid|localhost|test)(?::\d+)?/", # Pages that are inaccessible because they require authentication. r"^https://github\.com/[^/]+/[^/]+/fork", r"^https://code\.djangoproject\.com/github/login", r"^https://code\.djangoproject\.com/newticket", r"^https://(?:code|www)\.djangoproject\.com/admin/", r"^https://www\.djangoproject\.com/community/add/blogs/", r"^https://www\.google\.com/webmasters/tools/ping", r"^https://search\.google\.com/search-console/welcome", # Fragments used to dynamically switch content or populate fields. r"^https://web\.libera\.chat/#", r"^https://github\.com/[^#]+#L\d+-L\d+$", r"^https://help\.apple\.com/itc/podcasts_connect/#/itc", # Anchors on certain pages with missing a[name] attributes. r"^https://tools\.ietf\.org/html/rfc1123\.html#section-", ] # Spelling check needs an additional module that is not installed by default. # Add it only if spelling check is requested so docs can be generated without it. if "spelling" in sys.argv: extensions.append("sphinxcontrib.spelling") # Spelling language. spelling_lang = "en_US" # Location of word list. spelling_word_list_filename = "spelling_wordlist" spelling_warning = True # Add any paths that contain templates here, relative to this directory. # templates_path = [] # The suffix of source filenames. source_suffix = ".txt" # The encoding of source files. # source_encoding = 'utf-8-sig' # The root toctree document. root_doc = "contents" # Disable auto-created table of contents entries for all domain objects (e.g. # functions, classes, attributes, etc.) in Sphinx 5.2+. toc_object_entries = False # General substitutions. project = "Django" copyright = "Django Software Foundation and contributors" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "5.0" # The full version, including alpha/beta/rc tags. try: from django import VERSION, get_version except ImportError: release = version else: def django_release(): pep440ver = get_version() if VERSION[3:5] == ("alpha", 0) and "dev" not in pep440ver: return pep440ver + ".dev" return pep440ver release = django_release() # The "development version" of Django django_next_version = "5.0" extlinks = { "bpo": ("https://bugs.python.org/issue?@action=redirect&bpo=%s", "bpo-%s"), "commit": ("https://github.com/django/django/commit/%s", "%s"), "cve": ("https://nvd.nist.gov/vuln/detail/CVE-%s", "CVE-%s"), "pypi": ("https://pypi.org/project/%s/", "%s"), # A file or directory. GitHub redirects from blob to tree if needed. "source": ("https://github.com/django/django/blob/main/%s", "%s"), "ticket": ("https://code.djangoproject.com/ticket/%s", "#%s"), } # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # Location for .po/.mo translation files used when language is set locale_dirs = ["locale/"] # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = "%B %d, %Y" # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build", "_theme", "requirements.txt"] # The reST default role (used for this markup: `text`) to use for all documents. default_role = "default-role-error" # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = False # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "trac" # Links to Python's docs should reference the most recent version of the 3.x # branch, which is located at this URL. intersphinx_mapping = { "python": ("https://docs.python.org/3/", None), "sphinx": ("https://www.sphinx-doc.org/en/master/", None), "psycopg": ("https://www.psycopg.org/psycopg3/docs/", None), } # Python's docs don't change every week. intersphinx_cache_limit = 90 # days # The 'versionadded' and 'versionchanged' directives are overridden. suppress_warnings = ["app.add_directive"] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "djangodocs" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ["_theme"] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = "%b %d, %Y" # Content template for the index page. # html_index = '' # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "Djangodoc" modindex_common_prefix = ["django."] # Appended to every page rst_epilog = """ .. |django-users| replace:: :ref:`django-users <django-users-mailing-list>` .. |django-developers| replace:: :ref:`django-developers <django-developers-mailing-list>` .. |django-announce| replace:: :ref:`django-announce <django-announce-mailing-list>` .. |django-updates| replace:: :ref:`django-updates <django-updates-mailing-list>` """ # NOQA # -- Options for LaTeX output -------------------------------------------------- # Use XeLaTeX for Unicode support. latex_engine = "xelatex" latex_use_xindy = False # Set font for CJK and fallbacks for unicode characters. latex_elements = { "fontpkg": r""" \setmainfont{Symbola} """, "preamble": r""" \usepackage{newunicodechar} \usepackage[UTF8]{ctex} \newunicodechar{π}{\ensuremath{\pi}} \newunicodechar{≤}{\ensuremath{\le}} \newunicodechar{≥}{\ensuremath{\ge}} \newunicodechar{♥}{\ensuremath{\heartsuit}} \newunicodechar{…}{\ensuremath{\ldots}} """, } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). # latex_documents = [] latex_documents = [ ( "contents", "django.tex", "Django Documentation", "Django Software Foundation", "manual", ), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ( "ref/django-admin", "django-admin", "Utility script for the Django web framework", ["Django Software Foundation"], 1, ) ] # -- Options for Texinfo output ------------------------------------------------ # List of tuples (startdocname, targetname, title, author, dir_entry, # description, category, toctree_only) texinfo_documents = [ ( root_doc, "django", "", "", "Django", "Documentation of the Django framework", "Web development", False, ) ] # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = "Django Software Foundation" epub_publisher = "Django Software Foundation" epub_copyright = copyright # The basename for the epub file. It defaults to the project name. # epub_basename = 'Django' # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. epub_theme = "djangodocs-epub" # The language of the text. It defaults to the language option # or en if the language is not set. # epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. # epub_scheme = '' # The unique identifier of the text. This can be an ISBN number # or the project homepage. # epub_identifier = '' # A unique identification for the text. # epub_uid = '' # A tuple containing the cover image and cover page html template filenames. epub_cover = ("", "epub-cover.html") # A sequence of (type, uri, title) tuples for the guide element of content.opf. # epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_pre_files = [] # HTML files that should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_post_files = [] # A list of files that should not be packed into the epub file. # epub_exclude_files = [] # The depth of the table of contents in toc.ncx. # epub_tocdepth = 3 # Allow duplicate toc entries. # epub_tocdup = True # Choose between 'default' and 'includehidden'. # epub_tocscope = 'default' # Fix unsupported image types using the PIL. # epub_fix_images = False # Scale large images. # epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. # epub_show_urls = 'inline' # If false, no index is generated. # epub_use_index = True
33be223da3349cf1b695ba04e9fb474b8f758ec2badb66d6e7a2ee418d5e8a00
import datetime import functools import os import subprocess import sys from django.utils.regex_helper import _lazy_re_compile # Private, stable API for detecting the Python version. PYXY means "Python X.Y # or later". So that third-party apps can use these values, each constant # should remain as long as the oldest supported Django version supports that # Python version. PY36 = sys.version_info >= (3, 6) PY37 = sys.version_info >= (3, 7) PY38 = sys.version_info >= (3, 8) PY39 = sys.version_info >= (3, 9) PY310 = sys.version_info >= (3, 10) PY311 = sys.version_info >= (3, 11) PY312 = sys.version_info >= (3, 12) def get_version(version=None): """Return a PEP 440-compliant version number from VERSION.""" version = get_complete_version(version) # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|rc}N - for alpha, beta, and rc releases main = get_main_version(version) sub = "" if version[3] == "alpha" and version[4] == 0: git_changeset = get_git_changeset() if git_changeset: sub = ".dev%s" % git_changeset elif version[3] != "final": mapping = {"alpha": "a", "beta": "b", "rc": "rc"} sub = mapping[version[3]] + str(version[4]) return main + sub def get_main_version(version=None): """Return main version (X.Y[.Z]) from VERSION.""" version = get_complete_version(version) parts = 2 if version[2] == 0 else 3 return ".".join(str(x) for x in version[:parts]) def get_complete_version(version=None): """ Return a tuple of the django version. If version argument is non-empty, check for correctness of the tuple provided. """ if version is None: from django import VERSION as version else: assert len(version) == 5 assert version[3] in ("alpha", "beta", "rc", "final") return version def get_docs_version(version=None): version = get_complete_version(version) if version[3] != "final": return "dev" else: return "%d.%d" % version[:2] @functools.lru_cache def get_git_changeset(): """Return a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers. """ # Repository may not be found if __file__ is undefined, e.g. in a frozen # module. if "__file__" not in globals(): return None repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) git_log = subprocess.run( "git log --pretty=format:%ct --quiet -1 HEAD", capture_output=True, shell=True, cwd=repo_dir, text=True, ) timestamp = git_log.stdout tz = datetime.timezone.utc try: timestamp = datetime.datetime.fromtimestamp(int(timestamp), tz=tz) except ValueError: return None return timestamp.strftime("%Y%m%d%H%M%S") version_component_re = _lazy_re_compile(r"(\d+|[a-z]+|\.)") def get_version_tuple(version): """ Return a tuple of version numbers (e.g. (1, 2, 3)) from the version string (e.g. '1.2.3'). """ version_numbers = [] for item in version_component_re.split(version): if item and item != ".": try: component = int(item) except ValueError: break else: version_numbers.append(component) return tuple(version_numbers)
8fd07fc129ec752dd95e7f69b7d18898e243a603bad5832bfe3b67529643c748
import datetime from django.utils.html import avoid_wrapping from django.utils.timezone import is_aware from django.utils.translation import gettext, ngettext_lazy TIME_STRINGS = { "year": ngettext_lazy("%(num)d year", "%(num)d years", "num"), "month": ngettext_lazy("%(num)d month", "%(num)d months", "num"), "week": ngettext_lazy("%(num)d week", "%(num)d weeks", "num"), "day": ngettext_lazy("%(num)d day", "%(num)d days", "num"), "hour": ngettext_lazy("%(num)d hour", "%(num)d hours", "num"), "minute": ngettext_lazy("%(num)d minute", "%(num)d minutes", "num"), } TIME_STRINGS_KEYS = list(TIME_STRINGS.keys()) TIME_CHUNKS = [ 60 * 60 * 24 * 7, # week 60 * 60 * 24, # day 60 * 60, # hour 60, # minute ] MONTHS_DAYS = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) def timesince(d, now=None, reversed=False, time_strings=None, depth=2): """ Take two datetime objects and return the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, return "0 minutes". Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. The algorithm takes into account the varying duration of years and months. There is exactly "1 year, 1 month" between 2013/02/10 and 2014/03/10, but also between 2007/08/10 and 2008/09/10 despite the delta being 393 days in the former case and 397 in the latter. Up to `depth` adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. `time_strings` is an optional dict of strings to replace the default TIME_STRINGS dict. `depth` is an optional integer to control the number of adjacent time units returned. Originally adapted from https://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since Modified to improve results for years and months. """ if time_strings is None: time_strings = TIME_STRINGS if depth <= 0: raise ValueError("depth must be greater than 0.") # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) # Compared datetimes must be in the same time zone. if not now: now = datetime.datetime.now(d.tzinfo if is_aware(d) else None) elif is_aware(now) and is_aware(d): now = now.astimezone(d.tzinfo) if reversed: d, now = now, d delta = now - d # Ignore microseconds. since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(time_strings["minute"] % {"num": 0}) # Get years and months. total_months = (now.year - d.year) * 12 + (now.month - d.month) if d.day > now.day or (d.day == now.day and d.time() > now.time()): total_months -= 1 years, months = divmod(total_months, 12) # Calculate the remaining time. # Create a "pivot" datetime shifted from d by years and months, then use # that to determine the other parts. if years or months: pivot_year = d.year + years pivot_month = d.month + months if pivot_month > 12: pivot_month -= 12 pivot_year += 1 pivot = datetime.datetime( pivot_year, pivot_month, min(MONTHS_DAYS[pivot_month - 1], d.day), d.hour, d.minute, d.second, tzinfo=d.tzinfo, ) else: pivot = d remaining_time = (now - pivot).total_seconds() partials = [years, months] for chunk in TIME_CHUNKS: count = int(remaining_time // chunk) partials.append(count) remaining_time -= chunk * count # Find the first non-zero part (if any) and then build the result, until # depth. i = 0 for i, value in enumerate(partials): if value != 0: break else: return avoid_wrapping(time_strings["minute"] % {"num": 0}) result = [] current_depth = 0 while i < len(TIME_STRINGS_KEYS) and current_depth < depth: value = partials[i] if value == 0: break name = TIME_STRINGS_KEYS[i] result.append(avoid_wrapping(time_strings[name] % {"num": value})) current_depth += 1 i += 1 return gettext(", ").join(result) def timeuntil(d, now=None, time_strings=None, depth=2): """ Like timesince, but return a string measuring the time until the given time. """ return timesince(d, now, reversed=True, time_strings=time_strings, depth=depth)
847455d1bd30449a04f30733b3117de59d0d0e2491491e3fdb7046f6531f914a
import copy import itertools import operator from functools import total_ordering, wraps class cached_property: """ Decorator that converts a method with a single self argument into a property cached on the instance. A cached property can be made out of an existing method: (e.g. ``url = cached_property(get_absolute_url)``). """ name = None @staticmethod def func(instance): raise TypeError( "Cannot use cached_property instance without calling " "__set_name__() on it." ) def __init__(self, func): self.real_func = func self.__doc__ = getattr(func, "__doc__") def __set_name__(self, owner, name): if self.name is None: self.name = name self.func = self.real_func elif name != self.name: raise TypeError( "Cannot assign the same cached_property to two different names " "(%r and %r)." % (self.name, name) ) def __get__(self, instance, cls=None): """ Call the function and put the return value in instance.__dict__ so that subsequent attribute access on the instance returns the cached value instead of calling cached_property.__get__(). """ if instance is None: return self res = instance.__dict__[self.name] = self.func(instance) return res class classproperty: """ Decorator that converts a method with a single cls argument into a property that can be accessed directly from the class. """ def __init__(self, method=None): self.fget = method def __get__(self, instance, cls=None): return self.fget(cls) def getter(self, method): self.fget = method return self class Promise: """ Base class for the proxy class created in the closure of the lazy function. It's used to recognize promises in code. """ pass def lazy(func, *resultclasses): """ Turn any callable into a lazy evaluated callable. result classes or types is required -- at least one is needed so that the automatic forcing of the lazy evaluation code is triggered. Results are not memoized; the function is evaluated on every access. """ @total_ordering class __proxy__(Promise): """ Encapsulate a function call and act as a proxy for methods that are called on the result of that function. The function is not evaluated until one of the methods on the result is called. """ __prepared = False def __init__(self, args, kw): self.__args = args self.__kw = kw if not self.__prepared: self.__prepare_class__() self.__class__.__prepared = True def __reduce__(self): return ( _lazy_proxy_unpickle, (func, self.__args, self.__kw) + resultclasses, ) def __repr__(self): return repr(self.__cast()) @classmethod def __prepare_class__(cls): for resultclass in resultclasses: for type_ in resultclass.mro(): for method_name in type_.__dict__: # All __promise__ return the same wrapper method, they # look up the correct implementation when called. if hasattr(cls, method_name): continue meth = cls.__promise__(method_name) setattr(cls, method_name, meth) cls._delegate_bytes = bytes in resultclasses cls._delegate_text = str in resultclasses if cls._delegate_bytes and cls._delegate_text: raise ValueError( "Cannot call lazy() with both bytes and text return types." ) if cls._delegate_bytes: cls.__bytes__ = cls.__bytes_cast @classmethod def __promise__(cls, method_name): # Builds a wrapper around some magic method def __wrapper__(self, *args, **kw): # Automatically triggers the evaluation of a lazy value and # applies the given magic method of the result type. res = func(*self.__args, **self.__kw) return getattr(res, method_name)(*args, **kw) return __wrapper__ def __bytes_cast(self): return bytes(func(*self.__args, **self.__kw)) def __cast(self): if self._delegate_bytes: return self.__bytes_cast() else: return func(*self.__args, **self.__kw) def __str__(self): # object defines __str__(), so __prepare_class__() won't overload # a __str__() method from the proxied class. return str(self.__cast()) def __eq__(self, other): if isinstance(other, Promise): other = other.__cast() return self.__cast() == other def __lt__(self, other): if isinstance(other, Promise): other = other.__cast() return self.__cast() < other def __hash__(self): return hash(self.__cast()) def __mod__(self, rhs): if self._delegate_text: return str(self) % rhs return self.__cast() % rhs def __add__(self, other): return self.__cast() + other def __radd__(self, other): return other + self.__cast() def __deepcopy__(self, memo): # Instances of this class are effectively immutable. It's just a # collection of functions. So we don't need to do anything # complicated for copying. memo[id(self)] = self return self @wraps(func) def __wrapper__(*args, **kw): # Creates the proxy object, instead of the actual value. return __proxy__(args, kw) return __wrapper__ def _lazy_proxy_unpickle(func, args, kwargs, *resultclasses): return lazy(func, *resultclasses)(*args, **kwargs) def lazystr(text): """ Shortcut for the common case of a lazy callable that returns str. """ return lazy(str, str)(text) def keep_lazy(*resultclasses): """ A decorator that allows a function to be called with one or more lazy arguments. If none of the args are lazy, the function is evaluated immediately, otherwise a __proxy__ is returned that will evaluate the function when needed. """ if not resultclasses: raise TypeError("You must pass at least one argument to keep_lazy().") def decorator(func): lazy_func = lazy(func, *resultclasses) @wraps(func) def wrapper(*args, **kwargs): if any( isinstance(arg, Promise) for arg in itertools.chain(args, kwargs.values()) ): return lazy_func(*args, **kwargs) return func(*args, **kwargs) return wrapper return decorator def keep_lazy_text(func): """ A decorator for functions that accept lazy arguments and return text. """ return keep_lazy(str)(func) empty = object() def new_method_proxy(func): def inner(self, *args): if (_wrapped := self._wrapped) is empty: self._setup() _wrapped = self._wrapped return func(_wrapped, *args) inner._mask_wrapped = False return inner class LazyObject: """ A wrapper for another class that can be used to delay instantiation of the wrapped class. By subclassing, you have the opportunity to intercept and alter the instantiation. If you don't need to do that, use SimpleLazyObject. """ # Avoid infinite recursion when tracing __init__ (#19456). _wrapped = None def __init__(self): # Note: if a subclass overrides __init__(), it will likely need to # override __copy__() and __deepcopy__() as well. self._wrapped = empty def __getattribute__(self, name): if name == "_wrapped": # Avoid recursion when getting wrapped object. return super().__getattribute__(name) value = super().__getattribute__(name) # If attribute is a proxy method, raise an AttributeError to call # __getattr__() and use the wrapped object method. if not getattr(value, "_mask_wrapped", True): raise AttributeError return value __getattr__ = new_method_proxy(getattr) def __setattr__(self, name, value): if name == "_wrapped": # Assign to __dict__ to avoid infinite __setattr__ loops. self.__dict__["_wrapped"] = value else: if self._wrapped is empty: self._setup() setattr(self._wrapped, name, value) def __delattr__(self, name): if name == "_wrapped": raise TypeError("can't delete _wrapped.") if self._wrapped is empty: self._setup() delattr(self._wrapped, name) def _setup(self): """ Must be implemented by subclasses to initialize the wrapped object. """ raise NotImplementedError( "subclasses of LazyObject must provide a _setup() method" ) # Because we have messed with __class__ below, we confuse pickle as to what # class we are pickling. We're going to have to initialize the wrapped # object to successfully pickle it, so we might as well just pickle the # wrapped object since they're supposed to act the same way. # # Unfortunately, if we try to simply act like the wrapped object, the ruse # will break down when pickle gets our id(). Thus we end up with pickle # thinking, in effect, that we are a distinct object from the wrapped # object, but with the same __dict__. This can cause problems (see #25389). # # So instead, we define our own __reduce__ method and custom unpickler. We # pickle the wrapped object as the unpickler's argument, so that pickle # will pickle it normally, and then the unpickler simply returns its # argument. def __reduce__(self): if self._wrapped is empty: self._setup() return (unpickle_lazyobject, (self._wrapped,)) def __copy__(self): if self._wrapped is empty: # If uninitialized, copy the wrapper. Use type(self), not # self.__class__, because the latter is proxied. return type(self)() else: # If initialized, return a copy of the wrapped object. return copy.copy(self._wrapped) def __deepcopy__(self, memo): if self._wrapped is empty: # We have to use type(self), not self.__class__, because the # latter is proxied. result = type(self)() memo[id(self)] = result return result return copy.deepcopy(self._wrapped, memo) __bytes__ = new_method_proxy(bytes) __str__ = new_method_proxy(str) __bool__ = new_method_proxy(bool) # Introspection support __dir__ = new_method_proxy(dir) # Need to pretend to be the wrapped class, for the sake of objects that # care about this (especially in equality tests) __class__ = property(new_method_proxy(operator.attrgetter("__class__"))) __eq__ = new_method_proxy(operator.eq) __lt__ = new_method_proxy(operator.lt) __gt__ = new_method_proxy(operator.gt) __ne__ = new_method_proxy(operator.ne) __hash__ = new_method_proxy(hash) # List/Tuple/Dictionary methods support __getitem__ = new_method_proxy(operator.getitem) __setitem__ = new_method_proxy(operator.setitem) __delitem__ = new_method_proxy(operator.delitem) __iter__ = new_method_proxy(iter) __len__ = new_method_proxy(len) __contains__ = new_method_proxy(operator.contains) def unpickle_lazyobject(wrapped): """ Used to unpickle lazy objects. Just return its argument, which will be the wrapped object. """ return wrapped class SimpleLazyObject(LazyObject): """ A lazy object initialized from any function. Designed for compound objects of unknown type. For builtins or objects of known type, use django.utils.functional.lazy. """ def __init__(self, func): """ Pass in a callable that returns the object to be wrapped. If copies are made of the resulting SimpleLazyObject, which can happen in various circumstances within Django, then you must ensure that the callable can be safely run more than once and will return the same value. """ self.__dict__["_setupfunc"] = func super().__init__() def _setup(self): self._wrapped = self._setupfunc() # Return a meaningful representation of the lazy object for debugging # without evaluating the wrapped object. def __repr__(self): if self._wrapped is empty: repr_attr = self._setupfunc else: repr_attr = self._wrapped return "<%s: %r>" % (type(self).__name__, repr_attr) def __copy__(self): if self._wrapped is empty: # If uninitialized, copy the wrapper. Use SimpleLazyObject, not # self.__class__, because the latter is proxied. return SimpleLazyObject(self._setupfunc) else: # If initialized, return a copy of the wrapped object. return copy.copy(self._wrapped) def __deepcopy__(self, memo): if self._wrapped is empty: # We have to use SimpleLazyObject, not self.__class__, because the # latter is proxied. result = SimpleLazyObject(self._setupfunc) memo[id(self)] = result return result return copy.deepcopy(self._wrapped, memo) __add__ = new_method_proxy(operator.add) @new_method_proxy def __radd__(self, other): return other + self def partition(predicate, values): """ Split the values into two sets, based on the return value of the function (True/False). e.g.: >>> partition(lambda x: x > 3, range(5)) [0, 1, 2, 3], [4] """ results = ([], []) for item in values: results[predicate(item)].append(item) return results
43477de91585690afa62a1b4d06ba51aa43d3363a78b95888dfff2e099c45a7f
import os import tempfile from os.path import abspath, dirname, join, normcase, sep from pathlib import Path from django.core.exceptions import SuspiciousFileOperation def safe_join(base, *paths): """ Join one or more path components to the base path component intelligently. Return a normalized, absolute version of the final path. Raise SuspiciousFileOperation if the final path isn't located inside of the base path component. """ final_path = abspath(join(base, *paths)) base_path = abspath(base) # Ensure final_path starts with base_path (using normcase to ensure we # don't false-negative on case insensitive operating systems like Windows), # further, one of the following conditions must be true: # a) The next character is the path separator (to prevent conditions like # safe_join("/dir", "/../d")) # b) The final path must be the same as the base path. # c) The base path must be the most root path (meaning either "/" or "C:\\") if ( not normcase(final_path).startswith(normcase(base_path + sep)) and normcase(final_path) != normcase(base_path) and dirname(normcase(base_path)) != normcase(base_path) ): raise SuspiciousFileOperation( "The joined path ({}) is located outside of the base path " "component ({})".format(final_path, base_path) ) return final_path def symlinks_supported(): """ Return whether or not creating symlinks are supported in the host platform and/or if they are allowed to be created (e.g. on Windows it requires admin permissions). """ with tempfile.TemporaryDirectory() as temp_dir: original_path = os.path.join(temp_dir, "original") symlink_path = os.path.join(temp_dir, "symlink") os.makedirs(original_path) try: os.symlink(original_path, symlink_path) supported = True except (OSError, NotImplementedError): supported = False return supported def to_path(value): """Convert value to a pathlib.Path instance, if not already a Path.""" if isinstance(value, Path): return value elif not isinstance(value, str): raise TypeError("Invalid path type: %s" % type(value).__name__) return Path(value)
abc15807c3725e70467a2a0879f55079b334469defc6e44b5037384219f4ac60
from contextlib import contextmanager from copy import copy # Hard-coded processor for easier use of CSRF protection. _builtin_context_processors = ("django.template.context_processors.csrf",) class ContextPopException(Exception): "pop() has been called more times than push()" pass class ContextDict(dict): def __init__(self, context, *args, **kwargs): super().__init__(*args, **kwargs) context.dicts.append(self) self.context = context def __enter__(self): return self def __exit__(self, *args, **kwargs): self.context.pop() class BaseContext: def __init__(self, dict_=None): self._reset_dicts(dict_) def _reset_dicts(self, value=None): builtins = {"True": True, "False": False, "None": None} self.dicts = [builtins] if value is not None: self.dicts.append(value) def __copy__(self): duplicate = copy(super()) duplicate.dicts = self.dicts[:] return duplicate def __repr__(self): return repr(self.dicts) def __iter__(self): return reversed(self.dicts) def push(self, *args, **kwargs): dicts = [] for d in args: if isinstance(d, BaseContext): dicts += d.dicts[1:] else: dicts.append(d) return ContextDict(self, *dicts, **kwargs) def pop(self): if len(self.dicts) == 1: raise ContextPopException return self.dicts.pop() def __setitem__(self, key, value): "Set a variable in the current context" self.dicts[-1][key] = value def set_upward(self, key, value): """ Set a variable in one of the higher contexts if it exists there, otherwise in the current context. """ context = self.dicts[-1] for d in reversed(self.dicts): if key in d: context = d break context[key] = value def __getitem__(self, key): "Get a variable's value, starting at the current context and going upward" for d in reversed(self.dicts): if key in d: return d[key] raise KeyError(key) def __delitem__(self, key): "Delete a variable from the current context" del self.dicts[-1][key] def __contains__(self, key): return any(key in d for d in self.dicts) def get(self, key, otherwise=None): for d in reversed(self.dicts): if key in d: return d[key] return otherwise def setdefault(self, key, default=None): try: return self[key] except KeyError: self[key] = default return default def new(self, values=None): """ Return a new context with the same properties, but with only the values given in 'values' stored. """ new_context = copy(self) new_context._reset_dicts(values) return new_context def flatten(self): """ Return self.dicts as one dictionary. """ flat = {} for d in self.dicts: flat.update(d) return flat def __eq__(self, other): """ Compare two contexts by comparing theirs 'dicts' attributes. """ if not isinstance(other, BaseContext): return NotImplemented # flatten dictionaries because they can be put in a different order. return self.flatten() == other.flatten() class Context(BaseContext): "A stack container for variable context" def __init__(self, dict_=None, autoescape=True, use_l10n=None, use_tz=None): self.autoescape = autoescape self.use_l10n = use_l10n self.use_tz = use_tz self.template_name = "unknown" self.render_context = RenderContext() # Set to the original template -- as opposed to extended or included # templates -- during rendering, see bind_template. self.template = None super().__init__(dict_) @contextmanager def bind_template(self, template): if self.template is not None: raise RuntimeError("Context is already bound to a template") self.template = template try: yield finally: self.template = None def __copy__(self): duplicate = super().__copy__() duplicate.render_context = copy(self.render_context) return duplicate def update(self, other_dict): "Push other_dict to the stack of dictionaries in the Context" if not hasattr(other_dict, "__getitem__"): raise TypeError("other_dict must be a mapping (dictionary-like) object.") if isinstance(other_dict, BaseContext): other_dict = other_dict.dicts[1:].pop() return ContextDict(self, other_dict) class RenderContext(BaseContext): """ A stack container for storing Template state. RenderContext simplifies the implementation of template Nodes by providing a safe place to store state between invocations of a node's `render` method. The RenderContext also provides scoping rules that are more sensible for 'template local' variables. The render context stack is pushed before each template is rendered, creating a fresh scope with nothing in it. Name resolution fails if a variable is not found at the top of the RequestContext stack. Thus, variables are local to a specific template and don't affect the rendering of other templates as they would if they were stored in the normal template context. """ template = None def __iter__(self): yield from self.dicts[-1] def __contains__(self, key): return key in self.dicts[-1] def get(self, key, otherwise=None): return self.dicts[-1].get(key, otherwise) def __getitem__(self, key): return self.dicts[-1][key] @contextmanager def push_state(self, template, isolated_context=True): initial = self.template self.template = template if isolated_context: self.push() try: yield finally: self.template = initial if isolated_context: self.pop() class RequestContext(Context): """ This subclass of template.Context automatically populates itself using the processors defined in the engine's configuration. Additional processors can be specified as a list of callables using the "processors" keyword argument. """ def __init__( self, request, dict_=None, processors=None, use_l10n=None, use_tz=None, autoescape=True, ): super().__init__(dict_, use_l10n=use_l10n, use_tz=use_tz, autoescape=autoescape) self.request = request self._processors = () if processors is None else tuple(processors) self._processors_index = len(self.dicts) # placeholder for context processors output self.update({}) # empty dict for any new modifications # (so that context processors don't overwrite them) self.update({}) @contextmanager def bind_template(self, template): if self.template is not None: raise RuntimeError("Context is already bound to a template") self.template = template # Set context processors according to the template engine's settings. processors = template.engine.template_context_processors + self._processors updates = {} for processor in processors: context = processor(self.request) try: updates.update(context) except TypeError as e: raise TypeError( f"Context processor {processor.__qualname__} didn't return a " "dictionary." ) from e self.dicts[self._processors_index] = updates try: yield finally: self.template = None # Unset context processors. self.dicts[self._processors_index] = {} def new(self, values=None): new_context = super().new(values) # This is for backwards-compatibility: RequestContexts created via # Context.new don't include values from context processors. if hasattr(new_context, "_processors_index"): del new_context._processors_index return new_context def make_context(context, request=None, **kwargs): """ Create a suitable Context from a plain dict and optionally an HttpRequest. """ if context is not None and not isinstance(context, dict): raise TypeError( "context must be a dict rather than %s." % context.__class__.__name__ ) if request is None: context = Context(context, **kwargs) else: # The following pattern is required to ensure values from # context override those from template context processors. original_context = context context = RequestContext(request, **kwargs) if original_context: context.push(original_context) return context
38d6a2d3c6d6a486027d30df2f4ef508387b71f2d8dd8cb646f6bfbe5e189f32
"""Default variable filters.""" import random as random_module import re import types import warnings from decimal import ROUND_HALF_UP, Context, Decimal, InvalidOperation, getcontext from functools import wraps from inspect import unwrap from operator import itemgetter from pprint import pformat from urllib.parse import quote from django.utils import formats from django.utils.dateformat import format, time_format from django.utils.deprecation import RemovedInDjango51Warning from django.utils.encoding import iri_to_uri from django.utils.html import avoid_wrapping, conditional_escape, escape, escapejs from django.utils.html import json_script as _json_script from django.utils.html import linebreaks, strip_tags from django.utils.html import urlize as _urlize from django.utils.safestring import SafeData, mark_safe from django.utils.text import Truncator, normalize_newlines, phone2numeric from django.utils.text import slugify as _slugify from django.utils.text import wrap from django.utils.timesince import timesince, timeuntil from django.utils.translation import gettext, ngettext from .base import VARIABLE_ATTRIBUTE_SEPARATOR from .library import Library register = Library() ####################### # STRING DECORATOR # ####################### def stringfilter(func): """ Decorator for filters which should only receive strings. The object passed as the first positional argument will be converted to a string. """ @wraps(func) def _dec(first, *args, **kwargs): first = str(first) result = func(first, *args, **kwargs) if isinstance(first, SafeData) and getattr(unwrap(func), "is_safe", False): result = mark_safe(result) return result return _dec ################### # STRINGS # ################### @register.filter(is_safe=True) @stringfilter def addslashes(value): """ Add slashes before quotes. Useful for escaping strings in CSV, for example. Less useful for escaping JavaScript; use the ``escapejs`` filter instead. """ return value.replace("\\", "\\\\").replace('"', '\\"').replace("'", "\\'") @register.filter(is_safe=True) @stringfilter def capfirst(value): """Capitalize the first character of the value.""" return value and value[0].upper() + value[1:] @register.filter("escapejs") @stringfilter def escapejs_filter(value): """Hex encode characters for use in JavaScript strings.""" return escapejs(value) @register.filter(is_safe=True) def json_script(value, element_id=None): """ Output value JSON-encoded, wrapped in a <script type="application/json"> tag (with an optional id). """ return _json_script(value, element_id) @register.filter(is_safe=True) def floatformat(text, arg=-1): """ Display a float to a specified number of decimal places. If called without an argument, display the floating point number with one decimal place -- but only if there's a decimal place to be displayed: * num1 = 34.23234 * num2 = 34.00000 * num3 = 34.26000 * {{ num1|floatformat }} displays "34.2" * {{ num2|floatformat }} displays "34" * {{ num3|floatformat }} displays "34.3" If arg is positive, always display exactly arg number of decimal places: * {{ num1|floatformat:3 }} displays "34.232" * {{ num2|floatformat:3 }} displays "34.000" * {{ num3|floatformat:3 }} displays "34.260" If arg is negative, display arg number of decimal places -- but only if there are places to be displayed: * {{ num1|floatformat:"-3" }} displays "34.232" * {{ num2|floatformat:"-3" }} displays "34" * {{ num3|floatformat:"-3" }} displays "34.260" If arg has the 'g' suffix, force the result to be grouped by the THOUSAND_SEPARATOR for the active locale. When the active locale is en (English): * {{ 6666.6666|floatformat:"2g" }} displays "6,666.67" * {{ 10000|floatformat:"g" }} displays "10,000" If arg has the 'u' suffix, force the result to be unlocalized. When the active locale is pl (Polish): * {{ 66666.6666|floatformat:"2" }} displays "66666,67" * {{ 66666.6666|floatformat:"2u" }} displays "66666.67" If the input float is infinity or NaN, display the string representation of that value. """ force_grouping = False use_l10n = True if isinstance(arg, str): last_char = arg[-1] if arg[-2:] in {"gu", "ug"}: force_grouping = True use_l10n = False arg = arg[:-2] or -1 elif last_char == "g": force_grouping = True arg = arg[:-1] or -1 elif last_char == "u": use_l10n = False arg = arg[:-1] or -1 try: input_val = str(text) d = Decimal(input_val) except InvalidOperation: try: d = Decimal(str(float(text))) except (ValueError, InvalidOperation, TypeError): return "" try: p = int(arg) except ValueError: return input_val try: m = int(d) - d except (ValueError, OverflowError, InvalidOperation): return input_val if not m and p <= 0: return mark_safe( formats.number_format( "%d" % (int(d)), 0, use_l10n=use_l10n, force_grouping=force_grouping, ) ) exp = Decimal(1).scaleb(-abs(p)) # Set the precision high enough to avoid an exception (#15789). tupl = d.as_tuple() units = len(tupl[1]) units += -tupl[2] if m else tupl[2] prec = abs(p) + units + 1 prec = max(getcontext().prec, prec) # Avoid conversion to scientific notation by accessing `sign`, `digits`, # and `exponent` from Decimal.as_tuple() directly. rounded_d = d.quantize(exp, ROUND_HALF_UP, Context(prec=prec)) sign, digits, exponent = rounded_d.as_tuple() digits = [str(digit) for digit in reversed(digits)] while len(digits) <= abs(exponent): digits.append("0") digits.insert(-exponent, ".") if sign and rounded_d: digits.append("-") number = "".join(reversed(digits)) return mark_safe( formats.number_format( number, abs(p), use_l10n=use_l10n, force_grouping=force_grouping, ) ) @register.filter(is_safe=True) @stringfilter def iriencode(value): """Escape an IRI value for use in a URL.""" return iri_to_uri(value) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def linenumbers(value, autoescape=True): """Display text with line numbers.""" lines = value.split("\n") # Find the maximum width of the line count, for use with zero padding # string format command width = str(len(str(len(lines)))) if not autoescape or isinstance(value, SafeData): for i, line in enumerate(lines): lines[i] = ("%0" + width + "d. %s") % (i + 1, line) else: for i, line in enumerate(lines): lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line)) return mark_safe("\n".join(lines)) @register.filter(is_safe=True) @stringfilter def lower(value): """Convert a string into all lowercase.""" return value.lower() @register.filter(is_safe=False) @stringfilter def make_list(value): """ Return the value turned into a list. For an integer, it's a list of digits. For a string, it's a list of characters. """ return list(value) @register.filter(is_safe=True) @stringfilter def slugify(value): """ Convert to ASCII. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace. """ return _slugify(value) @register.filter(is_safe=True) def stringformat(value, arg): """ Format the variable according to the arg, a string formatting specifier. This specifier uses Python string formatting syntax, with the exception that the leading "%" is dropped. See https://docs.python.org/library/stdtypes.html#printf-style-string-formatting for documentation of Python string formatting. """ if isinstance(value, tuple): value = str(value) try: return ("%" + str(arg)) % value except (ValueError, TypeError): return "" @register.filter(is_safe=True) @stringfilter def title(value): """Convert a string into titlecase.""" t = re.sub("([a-z])'([A-Z])", lambda m: m[0].lower(), value.title()) return re.sub(r"\d([A-Z])", lambda m: m[0].lower(), t) @register.filter(is_safe=True) @stringfilter def truncatechars(value, arg): """Truncate a string after `arg` number of characters.""" try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. return Truncator(value).chars(length) @register.filter(is_safe=True) @stringfilter def truncatechars_html(value, arg): """ Truncate HTML after `arg` number of chars. Preserve newlines in the HTML. """ try: length = int(arg) except ValueError: # invalid literal for int() return value # Fail silently. return Truncator(value).chars(length, html=True) @register.filter(is_safe=True) @stringfilter def truncatewords(value, arg): """ Truncate a string after `arg` number of words. Remove newlines within the string. """ try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. return Truncator(value).words(length, truncate=" …") @register.filter(is_safe=True) @stringfilter def truncatewords_html(value, arg): """ Truncate HTML after `arg` number of words. Preserve newlines in the HTML. """ try: length = int(arg) except ValueError: # invalid literal for int() return value # Fail silently. return Truncator(value).words(length, html=True, truncate=" …") @register.filter(is_safe=False) @stringfilter def upper(value): """Convert a string into all uppercase.""" return value.upper() @register.filter(is_safe=False) @stringfilter def urlencode(value, safe=None): """ Escape a value for use in a URL. The ``safe`` parameter determines the characters which should not be escaped by Python's quote() function. If not provided, use the default safe characters (but an empty string can be provided when *all* characters should be escaped). """ kwargs = {} if safe is not None: kwargs["safe"] = safe return quote(value, **kwargs) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def urlize(value, autoescape=True): """Convert URLs in plain text into clickable links.""" return mark_safe(_urlize(value, nofollow=True, autoescape=autoescape)) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def urlizetrunc(value, limit, autoescape=True): """ Convert URLs into clickable links, truncating URLs to the given character limit, and adding 'rel=nofollow' attribute to discourage spamming. Argument: Length to truncate URLs to. """ return mark_safe( _urlize(value, trim_url_limit=int(limit), nofollow=True, autoescape=autoescape) ) @register.filter(is_safe=False) @stringfilter def wordcount(value): """Return the number of words.""" return len(value.split()) @register.filter(is_safe=True) @stringfilter def wordwrap(value, arg): """Wrap words at `arg` line length.""" return wrap(value, int(arg)) @register.filter(is_safe=True) @stringfilter def ljust(value, arg): """Left-align the value in a field of a given width.""" return value.ljust(int(arg)) @register.filter(is_safe=True) @stringfilter def rjust(value, arg): """Right-align the value in a field of a given width.""" return value.rjust(int(arg)) @register.filter(is_safe=True) @stringfilter def center(value, arg): """Center the value in a field of a given width.""" return value.center(int(arg)) @register.filter @stringfilter def cut(value, arg): """Remove all values of arg from the given string.""" safe = isinstance(value, SafeData) value = value.replace(arg, "") if safe and arg != ";": return mark_safe(value) return value ################### # HTML STRINGS # ################### @register.filter("escape", is_safe=True) @stringfilter def escape_filter(value): """Mark the value as a string that should be auto-escaped.""" return conditional_escape(value) @register.filter(is_safe=True) @stringfilter def force_escape(value): """ Escape a string's HTML. Return a new string containing the escaped characters (as opposed to "escape", which marks the content for later possible escaping). """ return escape(value) @register.filter("linebreaks", is_safe=True, needs_autoescape=True) @stringfilter def linebreaks_filter(value, autoescape=True): """ Replace line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (``<br>``) and a new line followed by a blank line becomes a paragraph break (``</p>``). """ autoescape = autoescape and not isinstance(value, SafeData) return mark_safe(linebreaks(value, autoescape)) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def linebreaksbr(value, autoescape=True): """ Convert all newlines in a piece of plain text to HTML line breaks (``<br>``). """ autoescape = autoescape and not isinstance(value, SafeData) value = normalize_newlines(value) if autoescape: value = escape(value) return mark_safe(value.replace("\n", "<br>")) @register.filter(is_safe=True) @stringfilter def safe(value): """Mark the value as a string that should not be auto-escaped.""" return mark_safe(value) @register.filter(is_safe=True) def safeseq(value): """ A "safe" filter for sequences. Mark each element in the sequence, individually, as safe, after converting them to strings. Return a list with the results. """ return [mark_safe(obj) for obj in value] @register.filter(is_safe=True) @stringfilter def striptags(value): """Strip all [X]HTML tags.""" return strip_tags(value) ################### # LISTS # ################### def _property_resolver(arg): """ When arg is convertible to float, behave like operator.itemgetter(arg) Otherwise, chain __getitem__() and getattr(). >>> _property_resolver(1)('abc') 'b' >>> _property_resolver('1')('abc') Traceback (most recent call last): ... TypeError: string indices must be integers >>> class Foo: ... a = 42 ... b = 3.14 ... c = 'Hey!' >>> _property_resolver('b')(Foo()) 3.14 """ try: float(arg) except ValueError: if VARIABLE_ATTRIBUTE_SEPARATOR + "_" in arg or arg[0] == "_": raise AttributeError("Access to private variables is forbidden.") parts = arg.split(VARIABLE_ATTRIBUTE_SEPARATOR) def resolve(value): for part in parts: try: value = value[part] except (AttributeError, IndexError, KeyError, TypeError, ValueError): value = getattr(value, part) return value return resolve else: return itemgetter(arg) @register.filter(is_safe=False) def dictsort(value, arg): """ Given a list of dicts, return that list sorted by the property given in the argument. """ try: return sorted(value, key=_property_resolver(arg)) except (AttributeError, TypeError): return "" @register.filter(is_safe=False) def dictsortreversed(value, arg): """ Given a list of dicts, return that list sorted in reverse order by the property given in the argument. """ try: return sorted(value, key=_property_resolver(arg), reverse=True) except (AttributeError, TypeError): return "" @register.filter(is_safe=False) def first(value): """Return the first item in a list.""" try: return value[0] except IndexError: return "" @register.filter(is_safe=True, needs_autoescape=True) def join(value, arg, autoescape=True): """Join a list with a string, like Python's ``str.join(list)``.""" try: if autoescape: value = [conditional_escape(v) for v in value] data = conditional_escape(arg).join(value) except TypeError: # Fail silently if arg isn't iterable. return value return mark_safe(data) @register.filter(is_safe=True) def last(value): """Return the last item in a list.""" try: return value[-1] except IndexError: return "" @register.filter(is_safe=False) def length(value): """Return the length of the value - useful for lists.""" try: return len(value) except (ValueError, TypeError): return 0 @register.filter(is_safe=False) def length_is(value, arg): """Return a boolean of whether the value's length is the argument.""" warnings.warn( "The length_is template filter is deprecated in favor of the length template " "filter and the == operator within an {% if %} tag.", RemovedInDjango51Warning, ) try: return len(value) == int(arg) except (ValueError, TypeError): return "" @register.filter(is_safe=True) def random(value): """Return a random item from the list.""" try: return random_module.choice(value) except IndexError: return "" @register.filter("slice", is_safe=True) def slice_filter(value, arg): """ Return a slice of the list using the same syntax as Python's list slicing. """ try: bits = [] for x in str(arg).split(":"): if not x: bits.append(None) else: bits.append(int(x)) return value[slice(*bits)] except (ValueError, TypeError): return value # Fail silently. @register.filter(is_safe=True, needs_autoescape=True) def unordered_list(value, autoescape=True): """ Recursively take a self-nested list and return an HTML unordered list -- WITHOUT opening and closing <ul> tags. Assume the list is in the proper format. For example, if ``var`` contains: ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then ``{{ var|unordered_list }}`` returns:: <li>States <ul> <li>Kansas <ul> <li>Lawrence</li> <li>Topeka</li> </ul> </li> <li>Illinois</li> </ul> </li> """ if autoescape: escaper = conditional_escape else: def escaper(x): return x def walk_items(item_list): item_iterator = iter(item_list) try: item = next(item_iterator) while True: try: next_item = next(item_iterator) except StopIteration: yield item, None break if isinstance(next_item, (list, tuple, types.GeneratorType)): try: iter(next_item) except TypeError: pass else: yield item, next_item item = next(item_iterator) continue yield item, None item = next_item except StopIteration: pass def list_formatter(item_list, tabs=1): indent = "\t" * tabs output = [] for item, children in walk_items(item_list): sublist = "" if children: sublist = "\n%s<ul>\n%s\n%s</ul>\n%s" % ( indent, list_formatter(children, tabs + 1), indent, indent, ) output.append("%s<li>%s%s</li>" % (indent, escaper(item), sublist)) return "\n".join(output) return mark_safe(list_formatter(value)) ################### # INTEGERS # ################### @register.filter(is_safe=False) def add(value, arg): """Add the arg to the value.""" try: return int(value) + int(arg) except (ValueError, TypeError): try: return value + arg except Exception: return "" @register.filter(is_safe=False) def get_digit(value, arg): """ Given a whole number, return the requested digit of it, where 1 is the right-most digit, 2 is the second-right-most digit, etc. Return the original value for invalid input (if input or argument is not an integer, or if argument is less than 1). Otherwise, output is always an integer. """ try: arg = int(arg) value = int(value) except ValueError: return value # Fail silently for an invalid argument if arg < 1: return value try: return int(str(value)[-arg]) except IndexError: return 0 ################### # DATES # ################### @register.filter(expects_localtime=True, is_safe=False) def date(value, arg=None): """Format a date according to the given format.""" if value in (None, ""): return "" try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return "" @register.filter(expects_localtime=True, is_safe=False) def time(value, arg=None): """Format a time according to the given format.""" if value in (None, ""): return "" try: return formats.time_format(value, arg) except (AttributeError, TypeError): try: return time_format(value, arg) except (AttributeError, TypeError): return "" @register.filter("timesince", is_safe=False) def timesince_filter(value, arg=None): """Format a date as the time since that date (i.e. "4 days, 6 hours").""" if not value: return "" try: if arg: return timesince(value, arg) return timesince(value) except (ValueError, TypeError): return "" @register.filter("timeuntil", is_safe=False) def timeuntil_filter(value, arg=None): """Format a date as the time until that date (i.e. "4 days, 6 hours").""" if not value: return "" try: return timeuntil(value, arg) except (ValueError, TypeError): return "" ################### # LOGIC # ################### @register.filter(is_safe=False) def default(value, arg): """If value is unavailable, use given default.""" return value or arg @register.filter(is_safe=False) def default_if_none(value, arg): """If value is None, use given default.""" if value is None: return arg return value @register.filter(is_safe=False) def divisibleby(value, arg): """Return True if the value is divisible by the argument.""" return int(value) % int(arg) == 0 @register.filter(is_safe=False) def yesno(value, arg=None): """ Given a string mapping values for true, false, and (optionally) None, return one of those strings according to the value: ========== ====================== ================================== Value Argument Outputs ========== ====================== ================================== ``True`` ``"yeah,no,maybe"`` ``yeah`` ``False`` ``"yeah,no,maybe"`` ``no`` ``None`` ``"yeah,no,maybe"`` ``maybe`` ``None`` ``"yeah,no"`` ``"no"`` (converts None to False if no mapping for None is given. ========== ====================== ================================== """ if arg is None: # Translators: Please do not add spaces around commas. arg = gettext("yes,no,maybe") bits = arg.split(",") if len(bits) < 2: return value # Invalid arg. try: yes, no, maybe = bits except ValueError: # Unpack list of wrong size (no "maybe" value provided). yes, no, maybe = bits[0], bits[1], bits[1] if value is None: return maybe if value: return yes return no ################### # MISC # ################### @register.filter(is_safe=True) def filesizeformat(bytes_): """ Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.). """ try: bytes_ = int(bytes_) except (TypeError, ValueError, UnicodeDecodeError): value = ngettext("%(size)d byte", "%(size)d bytes", 0) % {"size": 0} return avoid_wrapping(value) def filesize_number_format(value): return formats.number_format(round(value, 1), 1) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 negative = bytes_ < 0 if negative: bytes_ = -bytes_ # Allow formatting of negative numbers. if bytes_ < KB: value = ngettext("%(size)d byte", "%(size)d bytes", bytes_) % {"size": bytes_} elif bytes_ < MB: value = gettext("%s KB") % filesize_number_format(bytes_ / KB) elif bytes_ < GB: value = gettext("%s MB") % filesize_number_format(bytes_ / MB) elif bytes_ < TB: value = gettext("%s GB") % filesize_number_format(bytes_ / GB) elif bytes_ < PB: value = gettext("%s TB") % filesize_number_format(bytes_ / TB) else: value = gettext("%s PB") % filesize_number_format(bytes_ / PB) if negative: value = "-%s" % value return avoid_wrapping(value) @register.filter(is_safe=False) def pluralize(value, arg="s"): """ Return a plural suffix if the value is not 1, '1', or an object of length 1. By default, use 's' as the suffix: * If value is 0, vote{{ value|pluralize }} display "votes". * If value is 1, vote{{ value|pluralize }} display "vote". * If value is 2, vote{{ value|pluralize }} display "votes". If an argument is provided, use that string instead: * If value is 0, class{{ value|pluralize:"es" }} display "classes". * If value is 1, class{{ value|pluralize:"es" }} display "class". * If value is 2, class{{ value|pluralize:"es" }} display "classes". If the provided argument contains a comma, use the text before the comma for the singular case and the text after the comma for the plural case: * If value is 0, cand{{ value|pluralize:"y,ies" }} display "candies". * If value is 1, cand{{ value|pluralize:"y,ies" }} display "candy". * If value is 2, cand{{ value|pluralize:"y,ies" }} display "candies". """ if "," not in arg: arg = "," + arg bits = arg.split(",") if len(bits) > 2: return "" singular_suffix, plural_suffix = bits[:2] try: return singular_suffix if float(value) == 1 else plural_suffix except ValueError: # Invalid string that's not a number. pass except TypeError: # Value isn't a string or a number; maybe it's a list? try: return singular_suffix if len(value) == 1 else plural_suffix except TypeError: # len() of unsized object. pass return "" @register.filter("phone2numeric", is_safe=True) def phone2numeric_filter(value): """Take a phone number and converts it in to its numerical equivalent.""" return phone2numeric(value) @register.filter(is_safe=True) def pprint(value): """A wrapper around pprint.pprint -- for debugging, really.""" try: return pformat(value) except Exception as e: return "Error in formatting: %s: %s" % (e.__class__.__name__, e)
84005b477b21398c078598cd57a3c3c83f0e65273d8571cfd14a71791fdb4dee
""" Helper functions for creating Form classes from Django models and database field objects. """ from itertools import chain from django.core.exceptions import ( NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError, ) from django.db.models.utils import AltersData from django.forms.fields import ChoiceField, Field from django.forms.forms import BaseForm, DeclarativeFieldsMetaclass from django.forms.formsets import BaseFormSet, formset_factory from django.forms.utils import ErrorList from django.forms.widgets import ( HiddenInput, MultipleHiddenInput, RadioSelect, SelectMultiple, ) from django.utils.text import capfirst, get_text_list from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ __all__ = ( "ModelForm", "BaseModelForm", "model_to_dict", "fields_for_model", "ModelChoiceField", "ModelMultipleChoiceField", "ALL_FIELDS", "BaseModelFormSet", "modelformset_factory", "BaseInlineFormSet", "inlineformset_factory", "modelform_factory", ) ALL_FIELDS = "__all__" def construct_instance(form, instance, fields=None, exclude=None): """ Construct and return a model instance from the bound ``form``'s ``cleaned_data``, but do not save the returned instance to the database. """ from django.db import models opts = instance._meta cleaned_data = form.cleaned_data file_field_list = [] for f in opts.fields: if ( not f.editable or isinstance(f, models.AutoField) or f.name not in cleaned_data ): continue if fields is not None and f.name not in fields: continue if exclude and f.name in exclude: continue # Leave defaults for fields that aren't in POST data, except for # checkbox inputs because they don't appear in POST data if not checked. if ( f.has_default() and form[f.name].field.widget.value_omitted_from_data( form.data, form.files, form.add_prefix(f.name) ) and cleaned_data.get(f.name) in form[f.name].field.empty_values ): continue # Defer saving file-type fields until after the other fields, so a # callable upload_to can use the values from other fields. if isinstance(f, models.FileField): file_field_list.append(f) else: f.save_form_data(instance, cleaned_data[f.name]) for f in file_field_list: f.save_form_data(instance, cleaned_data[f.name]) return instance # ModelForms ################################################################# def model_to_dict(instance, fields=None, exclude=None): """ Return a dict containing the data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument. ``fields`` is an optional list of field names. If provided, return only the named. ``exclude`` is an optional list of field names. If provided, exclude the named from the returned dict, even if they are listed in the ``fields`` argument. """ opts = instance._meta data = {} for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many): if not getattr(f, "editable", False): continue if fields is not None and f.name not in fields: continue if exclude and f.name in exclude: continue data[f.name] = f.value_from_object(instance) return data def apply_limit_choices_to_to_formfield(formfield): """Apply limit_choices_to to the formfield's queryset if needed.""" from django.db.models import Exists, OuterRef, Q if hasattr(formfield, "queryset") and hasattr(formfield, "get_limit_choices_to"): limit_choices_to = formfield.get_limit_choices_to() if limit_choices_to: complex_filter = limit_choices_to if not isinstance(complex_filter, Q): complex_filter = Q(**limit_choices_to) complex_filter &= Q(pk=OuterRef("pk")) # Use Exists() to avoid potential duplicates. formfield.queryset = formfield.queryset.filter( Exists(formfield.queryset.model._base_manager.filter(complex_filter)), ) def fields_for_model( model, fields=None, exclude=None, widgets=None, formfield_callback=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None, *, apply_limit_choices_to=True, form_declared_fields=None, ): """ Return a dictionary containing form fields for the given model. ``fields`` is an optional list of field names. If provided, return only the named fields. ``exclude`` is an optional list of field names. If provided, exclude the named fields from the returned fields, even if they are listed in the ``fields`` argument. ``widgets`` is a dictionary of model field names mapped to a widget. ``formfield_callback`` is a callable that takes a model field and returns a form field. ``localized_fields`` is a list of names of fields which should be localized. ``labels`` is a dictionary of model field names mapped to a label. ``help_texts`` is a dictionary of model field names mapped to a help text. ``error_messages`` is a dictionary of model field names mapped to a dictionary of error messages. ``field_classes`` is a dictionary of model field names mapped to a form field class. ``apply_limit_choices_to`` is a boolean indicating if limit_choices_to should be applied to a field's queryset. ``form_declared_fields`` is a dictionary of form fields created directly on a form. """ form_declared_fields = form_declared_fields or {} field_dict = {} ignored = [] opts = model._meta # Avoid circular import from django.db.models import Field as ModelField sortable_private_fields = [ f for f in opts.private_fields if isinstance(f, ModelField) ] for f in sorted( chain(opts.concrete_fields, sortable_private_fields, opts.many_to_many) ): if not getattr(f, "editable", False): if ( fields is not None and f.name in fields and (exclude is None or f.name not in exclude) ): raise FieldError( "'%s' cannot be specified for %s model form as it is a " "non-editable field" % (f.name, model.__name__) ) continue if fields is not None and f.name not in fields: continue if exclude and f.name in exclude: continue if f.name in form_declared_fields: field_dict[f.name] = form_declared_fields[f.name] continue kwargs = {} if widgets and f.name in widgets: kwargs["widget"] = widgets[f.name] if localized_fields == ALL_FIELDS or ( localized_fields and f.name in localized_fields ): kwargs["localize"] = True if labels and f.name in labels: kwargs["label"] = labels[f.name] if help_texts and f.name in help_texts: kwargs["help_text"] = help_texts[f.name] if error_messages and f.name in error_messages: kwargs["error_messages"] = error_messages[f.name] if field_classes and f.name in field_classes: kwargs["form_class"] = field_classes[f.name] if formfield_callback is None: formfield = f.formfield(**kwargs) elif not callable(formfield_callback): raise TypeError("formfield_callback must be a function or callable") else: formfield = formfield_callback(f, **kwargs) if formfield: if apply_limit_choices_to: apply_limit_choices_to_to_formfield(formfield) field_dict[f.name] = formfield else: ignored.append(f.name) if fields: field_dict = { f: field_dict.get(f) for f in fields if (not exclude or f not in exclude) and f not in ignored } return field_dict class ModelFormOptions: def __init__(self, options=None): self.model = getattr(options, "model", None) self.fields = getattr(options, "fields", None) self.exclude = getattr(options, "exclude", None) self.widgets = getattr(options, "widgets", None) self.localized_fields = getattr(options, "localized_fields", None) self.labels = getattr(options, "labels", None) self.help_texts = getattr(options, "help_texts", None) self.error_messages = getattr(options, "error_messages", None) self.field_classes = getattr(options, "field_classes", None) self.formfield_callback = getattr(options, "formfield_callback", None) class ModelFormMetaclass(DeclarativeFieldsMetaclass): def __new__(mcs, name, bases, attrs): new_class = super().__new__(mcs, name, bases, attrs) if bases == (BaseModelForm,): return new_class opts = new_class._meta = ModelFormOptions(getattr(new_class, "Meta", None)) # We check if a string was passed to `fields` or `exclude`, # which is likely to be a mistake where the user typed ('foo') instead # of ('foo',) for opt in ["fields", "exclude", "localized_fields"]: value = getattr(opts, opt) if isinstance(value, str) and value != ALL_FIELDS: msg = ( "%(model)s.Meta.%(opt)s cannot be a string. " "Did you mean to type: ('%(value)s',)?" % { "model": new_class.__name__, "opt": opt, "value": value, } ) raise TypeError(msg) if opts.model: # If a model is defined, extract form fields from it. if opts.fields is None and opts.exclude is None: raise ImproperlyConfigured( "Creating a ModelForm without either the 'fields' attribute " "or the 'exclude' attribute is prohibited; form %s " "needs updating." % name ) if opts.fields == ALL_FIELDS: # Sentinel for fields_for_model to indicate "get the list of # fields from the model" opts.fields = None fields = fields_for_model( opts.model, opts.fields, opts.exclude, opts.widgets, opts.formfield_callback, opts.localized_fields, opts.labels, opts.help_texts, opts.error_messages, opts.field_classes, # limit_choices_to will be applied during ModelForm.__init__(). apply_limit_choices_to=False, form_declared_fields=new_class.declared_fields, ) # make sure opts.fields doesn't specify an invalid field none_model_fields = {k for k, v in fields.items() if not v} missing_fields = none_model_fields.difference(new_class.declared_fields) if missing_fields: message = "Unknown field(s) (%s) specified for %s" message %= (", ".join(missing_fields), opts.model.__name__) raise FieldError(message) # Include all the other declared fields. fields.update(new_class.declared_fields) else: fields = new_class.declared_fields new_class.base_fields = fields return new_class class BaseModelForm(BaseForm, AltersData): def __init__( self, data=None, files=None, auto_id="id_%s", prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, instance=None, use_required_attribute=None, renderer=None, ): opts = self._meta if opts.model is None: raise ValueError("ModelForm has no model class specified.") if instance is None: # if we didn't get an instance, instantiate a new one self.instance = opts.model() object_data = {} else: self.instance = instance object_data = model_to_dict(instance, opts.fields, opts.exclude) # if initial was provided, it should override the values from instance if initial is not None: object_data.update(initial) # self._validate_unique will be set to True by BaseModelForm.clean(). # It is False by default so overriding self.clean() and failing to call # super will stop validate_unique from being called. self._validate_unique = False super().__init__( data, files, auto_id, prefix, object_data, error_class, label_suffix, empty_permitted, use_required_attribute=use_required_attribute, renderer=renderer, ) for formfield in self.fields.values(): apply_limit_choices_to_to_formfield(formfield) def _get_validation_exclusions(self): """ For backwards-compatibility, exclude several types of fields from model validation. See tickets #12507, #12521, #12553. """ exclude = set() # Build up a list of fields that should be excluded from model field # validation and unique checks. for f in self.instance._meta.fields: field = f.name # Exclude fields that aren't on the form. The developer may be # adding these values to the model after form validation. if field not in self.fields: exclude.add(f.name) # Don't perform model validation on fields that were defined # manually on the form and excluded via the ModelForm's Meta # class. See #12901. elif self._meta.fields and field not in self._meta.fields: exclude.add(f.name) elif self._meta.exclude and field in self._meta.exclude: exclude.add(f.name) # Exclude fields that failed form validation. There's no need for # the model fields to validate them as well. elif field in self._errors: exclude.add(f.name) # Exclude empty fields that are not required by the form, if the # underlying model field is required. This keeps the model field # from raising a required error. Note: don't exclude the field from # validation if the model field allows blanks. If it does, the blank # value may be included in a unique check, so cannot be excluded # from validation. else: form_field = self.fields[field] field_value = self.cleaned_data.get(field) if ( not f.blank and not form_field.required and field_value in form_field.empty_values ): exclude.add(f.name) return exclude def clean(self): self._validate_unique = True return self.cleaned_data def _update_errors(self, errors): # Override any validation error messages defined at the model level # with those defined at the form level. opts = self._meta # Allow the model generated by construct_instance() to raise # ValidationError and have them handled in the same way as others. if hasattr(errors, "error_dict"): error_dict = errors.error_dict else: error_dict = {NON_FIELD_ERRORS: errors} for field, messages in error_dict.items(): if ( field == NON_FIELD_ERRORS and opts.error_messages and NON_FIELD_ERRORS in opts.error_messages ): error_messages = opts.error_messages[NON_FIELD_ERRORS] elif field in self.fields: error_messages = self.fields[field].error_messages else: continue for message in messages: if ( isinstance(message, ValidationError) and message.code in error_messages ): message.message = error_messages[message.code] self.add_error(None, errors) def _post_clean(self): opts = self._meta exclude = self._get_validation_exclusions() # Foreign Keys being used to represent inline relationships # are excluded from basic field value validation. This is for two # reasons: firstly, the value may not be supplied (#12507; the # case of providing new values to the admin); secondly the # object being referred to may not yet fully exist (#12749). # However, these fields *must* be included in uniqueness checks, # so this can't be part of _get_validation_exclusions(). for name, field in self.fields.items(): if isinstance(field, InlineForeignKeyField): exclude.add(name) try: self.instance = construct_instance( self, self.instance, opts.fields, opts.exclude ) except ValidationError as e: self._update_errors(e) try: self.instance.full_clean(exclude=exclude, validate_unique=False) except ValidationError as e: self._update_errors(e) # Validate uniqueness if needed. if self._validate_unique: self.validate_unique() def validate_unique(self): """ Call the instance's validate_unique() method and update the form's validation errors if any were raised. """ exclude = self._get_validation_exclusions() try: self.instance.validate_unique(exclude=exclude) except ValidationError as e: self._update_errors(e) def _save_m2m(self): """ Save the many-to-many fields and generic relations for this form. """ cleaned_data = self.cleaned_data exclude = self._meta.exclude fields = self._meta.fields opts = self.instance._meta # Note that for historical reasons we want to include also # private_fields here. (GenericRelation was previously a fake # m2m field). for f in chain(opts.many_to_many, opts.private_fields): if not hasattr(f, "save_form_data"): continue if fields and f.name not in fields: continue if exclude and f.name in exclude: continue if f.name in cleaned_data: f.save_form_data(self.instance, cleaned_data[f.name]) def save(self, commit=True): """ Save this form's self.instance object if commit=True. Otherwise, add a save_m2m() method to the form which can be called after the instance is saved manually at a later time. Return the model instance. """ if self.errors: raise ValueError( "The %s could not be %s because the data didn't validate." % ( self.instance._meta.object_name, "created" if self.instance._state.adding else "changed", ) ) if commit: # If committing, save the instance and the m2m data immediately. self.instance.save() self._save_m2m() else: # If not committing, add a method to the form to allow deferred # saving of m2m data. self.save_m2m = self._save_m2m return self.instance save.alters_data = True class ModelForm(BaseModelForm, metaclass=ModelFormMetaclass): pass def modelform_factory( model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None, ): """ Return a ModelForm containing form fields for the given model. You can optionally pass a `form` argument to use as a starting point for constructing the ModelForm. ``fields`` is an optional list of field names. If provided, include only the named fields in the returned fields. If omitted or '__all__', use all fields. ``exclude`` is an optional list of field names. If provided, exclude the named fields from the returned fields, even if they are listed in the ``fields`` argument. ``widgets`` is a dictionary of model field names mapped to a widget. ``localized_fields`` is a list of names of fields which should be localized. ``formfield_callback`` is a callable that takes a model field and returns a form field. ``labels`` is a dictionary of model field names mapped to a label. ``help_texts`` is a dictionary of model field names mapped to a help text. ``error_messages`` is a dictionary of model field names mapped to a dictionary of error messages. ``field_classes`` is a dictionary of model field names mapped to a form field class. """ # Create the inner Meta class. FIXME: ideally, we should be able to # construct a ModelForm without creating and passing in a temporary # inner class. # Build up a list of attributes that the Meta object will have. attrs = {"model": model} if fields is not None: attrs["fields"] = fields if exclude is not None: attrs["exclude"] = exclude if widgets is not None: attrs["widgets"] = widgets if localized_fields is not None: attrs["localized_fields"] = localized_fields if labels is not None: attrs["labels"] = labels if help_texts is not None: attrs["help_texts"] = help_texts if error_messages is not None: attrs["error_messages"] = error_messages if field_classes is not None: attrs["field_classes"] = field_classes # If parent form class already has an inner Meta, the Meta we're # creating needs to inherit from the parent's inner meta. bases = (form.Meta,) if hasattr(form, "Meta") else () Meta = type("Meta", bases, attrs) if formfield_callback: Meta.formfield_callback = staticmethod(formfield_callback) # Give this new form class a reasonable name. class_name = model.__name__ + "Form" # Class attributes for the new form class. form_class_attrs = {"Meta": Meta} if getattr(Meta, "fields", None) is None and getattr(Meta, "exclude", None) is None: raise ImproperlyConfigured( "Calling modelform_factory without defining 'fields' or " "'exclude' explicitly is prohibited." ) # Instantiate type(form) in order to use the same metaclass as form. return type(form)(class_name, (form,), form_class_attrs) # ModelFormSets ############################################################## class BaseModelFormSet(BaseFormSet, AltersData): """ A ``FormSet`` for editing a queryset and/or adding new objects to it. """ model = None edit_only = False # Set of fields that must be unique among forms of this set. unique_fields = set() def __init__( self, data=None, files=None, auto_id="id_%s", prefix=None, queryset=None, *, initial=None, **kwargs, ): self.queryset = queryset self.initial_extra = initial super().__init__( **{ "data": data, "files": files, "auto_id": auto_id, "prefix": prefix, **kwargs, } ) def initial_form_count(self): """Return the number of forms that are required in this FormSet.""" if not self.is_bound: return len(self.get_queryset()) return super().initial_form_count() def _existing_object(self, pk): if not hasattr(self, "_object_dict"): self._object_dict = {o.pk: o for o in self.get_queryset()} return self._object_dict.get(pk) def _get_to_python(self, field): """ If the field is a related field, fetch the concrete field's (that is, the ultimate pointed-to field's) to_python. """ while field.remote_field is not None: field = field.remote_field.get_related_field() return field.to_python def _construct_form(self, i, **kwargs): pk_required = i < self.initial_form_count() if pk_required: if self.is_bound: pk_key = "%s-%s" % (self.add_prefix(i), self.model._meta.pk.name) try: pk = self.data[pk_key] except KeyError: # The primary key is missing. The user may have tampered # with POST data. pass else: to_python = self._get_to_python(self.model._meta.pk) try: pk = to_python(pk) except ValidationError: # The primary key exists but is an invalid value. The # user may have tampered with POST data. pass else: kwargs["instance"] = self._existing_object(pk) else: kwargs["instance"] = self.get_queryset()[i] elif self.initial_extra: # Set initial values for extra forms try: kwargs["initial"] = self.initial_extra[i - self.initial_form_count()] except IndexError: pass form = super()._construct_form(i, **kwargs) if pk_required: form.fields[self.model._meta.pk.name].required = True return form def get_queryset(self): if not hasattr(self, "_queryset"): if self.queryset is not None: qs = self.queryset else: qs = self.model._default_manager.get_queryset() # If the queryset isn't already ordered we need to add an # artificial ordering here to make sure that all formsets # constructed from this queryset have the same form order. if not qs.ordered: qs = qs.order_by(self.model._meta.pk.name) # Removed queryset limiting here. As per discussion re: #13023 # on django-dev, max_num should not prevent existing # related objects/inlines from being displayed. self._queryset = qs return self._queryset def save_new(self, form, commit=True): """Save and return a new model instance for the given form.""" return form.save(commit=commit) def save_existing(self, form, obj, commit=True): """Save and return an existing model instance for the given form.""" return form.save(commit=commit) def delete_existing(self, obj, commit=True): """Deletes an existing model instance.""" if commit: obj.delete() def save(self, commit=True): """ Save model instances for every form, adding and changing instances as necessary, and return the list of instances. """ if not commit: self.saved_forms = [] def save_m2m(): for form in self.saved_forms: form.save_m2m() self.save_m2m = save_m2m if self.edit_only: return self.save_existing_objects(commit) else: return self.save_existing_objects(commit) + self.save_new_objects(commit) save.alters_data = True def clean(self): self.validate_unique() def validate_unique(self): # Collect unique_checks and date_checks to run from all the forms. all_unique_checks = set() all_date_checks = set() forms_to_delete = self.deleted_forms valid_forms = [ form for form in self.forms if form.is_valid() and form not in forms_to_delete ] for form in valid_forms: exclude = form._get_validation_exclusions() unique_checks, date_checks = form.instance._get_unique_checks( exclude=exclude, include_meta_constraints=True, ) all_unique_checks.update(unique_checks) all_date_checks.update(date_checks) errors = [] # Do each of the unique checks (unique and unique_together) for uclass, unique_check in all_unique_checks: seen_data = set() for form in valid_forms: # Get the data for the set of fields that must be unique among # the forms. row_data = ( field if field in self.unique_fields else form.cleaned_data[field] for field in unique_check if field in form.cleaned_data ) # Reduce Model instances to their primary key values row_data = tuple( d._get_pk_val() if hasattr(d, "_get_pk_val") # Prevent "unhashable type: list" errors later on. else tuple(d) if isinstance(d, list) else d for d in row_data ) if row_data and None not in row_data: # if we've already seen it then we have a uniqueness failure if row_data in seen_data: # poke error messages into the right places and mark # the form as invalid errors.append(self.get_unique_error_message(unique_check)) form._errors[NON_FIELD_ERRORS] = self.error_class( [self.get_form_error()], renderer=self.renderer, ) # Remove the data from the cleaned_data dict since it # was invalid. for field in unique_check: if field in form.cleaned_data: del form.cleaned_data[field] # mark the data as seen seen_data.add(row_data) # iterate over each of the date checks now for date_check in all_date_checks: seen_data = set() uclass, lookup, field, unique_for = date_check for form in valid_forms: # see if we have data for both fields if ( form.cleaned_data and form.cleaned_data[field] is not None and form.cleaned_data[unique_for] is not None ): # if it's a date lookup we need to get the data for all the fields if lookup == "date": date = form.cleaned_data[unique_for] date_data = (date.year, date.month, date.day) # otherwise it's just the attribute on the date/datetime # object else: date_data = (getattr(form.cleaned_data[unique_for], lookup),) data = (form.cleaned_data[field],) + date_data # if we've already seen it then we have a uniqueness failure if data in seen_data: # poke error messages into the right places and mark # the form as invalid errors.append(self.get_date_error_message(date_check)) form._errors[NON_FIELD_ERRORS] = self.error_class( [self.get_form_error()], renderer=self.renderer, ) # Remove the data from the cleaned_data dict since it # was invalid. del form.cleaned_data[field] # mark the data as seen seen_data.add(data) if errors: raise ValidationError(errors) def get_unique_error_message(self, unique_check): if len(unique_check) == 1: return gettext("Please correct the duplicate data for %(field)s.") % { "field": unique_check[0], } else: return gettext( "Please correct the duplicate data for %(field)s, which must be unique." ) % { "field": get_text_list(unique_check, _("and")), } def get_date_error_message(self, date_check): return gettext( "Please correct the duplicate data for %(field_name)s " "which must be unique for the %(lookup)s in %(date_field)s." ) % { "field_name": date_check[2], "date_field": date_check[3], "lookup": str(date_check[1]), } def get_form_error(self): return gettext("Please correct the duplicate values below.") def save_existing_objects(self, commit=True): self.changed_objects = [] self.deleted_objects = [] if not self.initial_forms: return [] saved_instances = [] forms_to_delete = self.deleted_forms for form in self.initial_forms: obj = form.instance # If the pk is None, it means either: # 1. The object is an unexpected empty model, created by invalid # POST data such as an object outside the formset's queryset. # 2. The object was already deleted from the database. if obj.pk is None: continue if form in forms_to_delete: self.deleted_objects.append(obj) self.delete_existing(obj, commit=commit) elif form.has_changed(): self.changed_objects.append((obj, form.changed_data)) saved_instances.append(self.save_existing(form, obj, commit=commit)) if not commit: self.saved_forms.append(form) return saved_instances def save_new_objects(self, commit=True): self.new_objects = [] for form in self.extra_forms: if not form.has_changed(): continue # If someone has marked an add form for deletion, don't save the # object. if self.can_delete and self._should_delete_form(form): continue self.new_objects.append(self.save_new(form, commit=commit)) if not commit: self.saved_forms.append(form) return self.new_objects def add_fields(self, form, index): """Add a hidden field for the object's primary key.""" from django.db.models import AutoField, ForeignKey, OneToOneField self._pk_field = pk = self.model._meta.pk # If a pk isn't editable, then it won't be on the form, so we need to # add it here so we can tell which object is which when we get the # data back. Generally, pk.editable should be false, but for some # reason, auto_created pk fields and AutoField's editable attribute is # True, so check for that as well. def pk_is_not_editable(pk): return ( (not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)) or ( pk.remote_field and pk.remote_field.parent_link and pk_is_not_editable(pk.remote_field.model._meta.pk) ) ) if pk_is_not_editable(pk) or pk.name not in form.fields: if form.is_bound: # If we're adding the related instance, ignore its primary key # as it could be an auto-generated default which isn't actually # in the database. pk_value = None if form.instance._state.adding else form.instance.pk else: try: if index is not None: pk_value = self.get_queryset()[index].pk else: pk_value = None except IndexError: pk_value = None if isinstance(pk, (ForeignKey, OneToOneField)): qs = pk.remote_field.model._default_manager.get_queryset() else: qs = self.model._default_manager.get_queryset() qs = qs.using(form.instance._state.db) if form._meta.widgets: widget = form._meta.widgets.get(self._pk_field.name, HiddenInput) else: widget = HiddenInput form.fields[self._pk_field.name] = ModelChoiceField( qs, initial=pk_value, required=False, widget=widget ) super().add_fields(form, index) def modelformset_factory( model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None, absolute_max=None, can_delete_extra=True, renderer=None, edit_only=False, ): """Return a FormSet class for the given Django model class.""" meta = getattr(form, "Meta", None) if ( getattr(meta, "fields", fields) is None and getattr(meta, "exclude", exclude) is None ): raise ImproperlyConfigured( "Calling modelformset_factory without defining 'fields' or " "'exclude' explicitly is prohibited." ) form = modelform_factory( model, form=form, fields=fields, exclude=exclude, formfield_callback=formfield_callback, widgets=widgets, localized_fields=localized_fields, labels=labels, help_texts=help_texts, error_messages=error_messages, field_classes=field_classes, ) FormSet = formset_factory( form, formset, extra=extra, min_num=min_num, max_num=max_num, can_order=can_order, can_delete=can_delete, validate_min=validate_min, validate_max=validate_max, absolute_max=absolute_max, can_delete_extra=can_delete_extra, renderer=renderer, ) FormSet.model = model FormSet.edit_only = edit_only return FormSet # InlineFormSets ############################################################# class BaseInlineFormSet(BaseModelFormSet): """A formset for child objects related to a parent.""" def __init__( self, data=None, files=None, instance=None, save_as_new=False, prefix=None, queryset=None, **kwargs, ): if instance is None: self.instance = self.fk.remote_field.model() else: self.instance = instance self.save_as_new = save_as_new if queryset is None: queryset = self.model._default_manager if self.instance.pk is not None: qs = queryset.filter(**{self.fk.name: self.instance}) else: qs = queryset.none() self.unique_fields = {self.fk.name} super().__init__(data, files, prefix=prefix, queryset=qs, **kwargs) # Add the generated field to form._meta.fields if it's defined to make # sure validation isn't skipped on that field. if self.form._meta.fields and self.fk.name not in self.form._meta.fields: if isinstance(self.form._meta.fields, tuple): self.form._meta.fields = list(self.form._meta.fields) self.form._meta.fields.append(self.fk.name) def initial_form_count(self): if self.save_as_new: return 0 return super().initial_form_count() def _construct_form(self, i, **kwargs): form = super()._construct_form(i, **kwargs) if self.save_as_new: mutable = getattr(form.data, "_mutable", None) # Allow modifying an immutable QueryDict. if mutable is not None: form.data._mutable = True # Remove the primary key from the form's data, we are only # creating new instances form.data[form.add_prefix(self._pk_field.name)] = None # Remove the foreign key from the form's data form.data[form.add_prefix(self.fk.name)] = None if mutable is not None: form.data._mutable = mutable # Set the fk value here so that the form can do its validation. fk_value = self.instance.pk if self.fk.remote_field.field_name != self.fk.remote_field.model._meta.pk.name: fk_value = getattr(self.instance, self.fk.remote_field.field_name) fk_value = getattr(fk_value, "pk", fk_value) setattr(form.instance, self.fk.get_attname(), fk_value) return form @classmethod def get_default_prefix(cls): return cls.fk.remote_field.get_accessor_name(model=cls.model).replace("+", "") def save_new(self, form, commit=True): # Ensure the latest copy of the related instance is present on each # form (it may have been saved after the formset was originally # instantiated). setattr(form.instance, self.fk.name, self.instance) return super().save_new(form, commit=commit) def add_fields(self, form, index): super().add_fields(form, index) if self._pk_field == self.fk: name = self._pk_field.name kwargs = {"pk_field": True} else: # The foreign key field might not be on the form, so we poke at the # Model field to get the label, since we need that for error messages. name = self.fk.name kwargs = { "label": getattr( form.fields.get(name), "label", capfirst(self.fk.verbose_name) ) } # The InlineForeignKeyField assumes that the foreign key relation is # based on the parent model's pk. If this isn't the case, set to_field # to correctly resolve the initial form value. if self.fk.remote_field.field_name != self.fk.remote_field.model._meta.pk.name: kwargs["to_field"] = self.fk.remote_field.field_name # If we're adding a new object, ignore a parent's auto-generated key # as it will be regenerated on the save request. if self.instance._state.adding: if kwargs.get("to_field") is not None: to_field = self.instance._meta.get_field(kwargs["to_field"]) else: to_field = self.instance._meta.pk if to_field.has_default(): setattr(self.instance, to_field.attname, None) form.fields[name] = InlineForeignKeyField(self.instance, **kwargs) def get_unique_error_message(self, unique_check): unique_check = [field for field in unique_check if field != self.fk.name] return super().get_unique_error_message(unique_check) def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False): """ Find and return the ForeignKey from model to parent if there is one (return None if can_fail is True and no such field exists). If fk_name is provided, assume it is the name of the ForeignKey field. Unless can_fail is True, raise an exception if there isn't a ForeignKey from model to parent_model. """ # avoid circular import from django.db.models import ForeignKey opts = model._meta if fk_name: fks_to_parent = [f for f in opts.fields if f.name == fk_name] if len(fks_to_parent) == 1: fk = fks_to_parent[0] parent_list = parent_model._meta.get_parent_list() if ( not isinstance(fk, ForeignKey) or ( # ForeignKey to proxy models. fk.remote_field.model._meta.proxy and fk.remote_field.model._meta.proxy_for_model not in parent_list ) or ( # ForeignKey to concrete models. not fk.remote_field.model._meta.proxy and fk.remote_field.model != parent_model and fk.remote_field.model not in parent_list ) ): raise ValueError( "fk_name '%s' is not a ForeignKey to '%s'." % (fk_name, parent_model._meta.label) ) elif not fks_to_parent: raise ValueError( "'%s' has no field named '%s'." % (model._meta.label, fk_name) ) else: # Try to discover what the ForeignKey from model to parent_model is parent_list = parent_model._meta.get_parent_list() fks_to_parent = [ f for f in opts.fields if isinstance(f, ForeignKey) and ( f.remote_field.model == parent_model or f.remote_field.model in parent_list or ( f.remote_field.model._meta.proxy and f.remote_field.model._meta.proxy_for_model in parent_list ) ) ] if len(fks_to_parent) == 1: fk = fks_to_parent[0] elif not fks_to_parent: if can_fail: return raise ValueError( "'%s' has no ForeignKey to '%s'." % ( model._meta.label, parent_model._meta.label, ) ) else: raise ValueError( "'%s' has more than one ForeignKey to '%s'. You must specify " "a 'fk_name' attribute." % ( model._meta.label, parent_model._meta.label, ) ) return fk def inlineformset_factory( parent_model, model, form=ModelForm, formset=BaseInlineFormSet, fk_name=None, fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None, absolute_max=None, can_delete_extra=True, renderer=None, edit_only=False, ): """ Return an ``InlineFormSet`` for the given kwargs. ``fk_name`` must be provided if ``model`` has more than one ``ForeignKey`` to ``parent_model``. """ fk = _get_foreign_key(parent_model, model, fk_name=fk_name) # enforce a max_num=1 when the foreign key to the parent model is unique. if fk.unique: max_num = 1 kwargs = { "form": form, "formfield_callback": formfield_callback, "formset": formset, "extra": extra, "can_delete": can_delete, "can_order": can_order, "fields": fields, "exclude": exclude, "min_num": min_num, "max_num": max_num, "widgets": widgets, "validate_min": validate_min, "validate_max": validate_max, "localized_fields": localized_fields, "labels": labels, "help_texts": help_texts, "error_messages": error_messages, "field_classes": field_classes, "absolute_max": absolute_max, "can_delete_extra": can_delete_extra, "renderer": renderer, "edit_only": edit_only, } FormSet = modelformset_factory(model, **kwargs) FormSet.fk = fk return FormSet # Fields ##################################################################### class InlineForeignKeyField(Field): """ A basic integer field that deals with validating the given value to a given parent instance in an inline. """ widget = HiddenInput default_error_messages = { "invalid_choice": _("The inline value did not match the parent instance."), } def __init__(self, parent_instance, *args, pk_field=False, to_field=None, **kwargs): self.parent_instance = parent_instance self.pk_field = pk_field self.to_field = to_field if self.parent_instance is not None: if self.to_field: kwargs["initial"] = getattr(self.parent_instance, self.to_field) else: kwargs["initial"] = self.parent_instance.pk kwargs["required"] = False super().__init__(*args, **kwargs) def clean(self, value): if value in self.empty_values: if self.pk_field: return None # if there is no value act as we did before. return self.parent_instance # ensure the we compare the values as equal types. if self.to_field: orig = getattr(self.parent_instance, self.to_field) else: orig = self.parent_instance.pk if str(value) != str(orig): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice" ) return self.parent_instance def has_changed(self, initial, data): return False class ModelChoiceIteratorValue: def __init__(self, value, instance): self.value = value self.instance = instance def __str__(self): return str(self.value) def __hash__(self): return hash(self.value) def __eq__(self, other): if isinstance(other, ModelChoiceIteratorValue): other = other.value return self.value == other class ModelChoiceIterator: def __init__(self, field): self.field = field self.queryset = field.queryset def __iter__(self): if self.field.empty_label is not None: yield ("", self.field.empty_label) queryset = self.queryset # Can't use iterator() when queryset uses prefetch_related() if not queryset._prefetch_related_lookups: queryset = queryset.iterator() for obj in queryset: yield self.choice(obj) def __len__(self): # count() adds a query but uses less memory since the QuerySet results # won't be cached. In most cases, the choices will only be iterated on, # and __len__() won't be called. return self.queryset.count() + (1 if self.field.empty_label is not None else 0) def __bool__(self): return self.field.empty_label is not None or self.queryset.exists() def choice(self, obj): return ( ModelChoiceIteratorValue(self.field.prepare_value(obj), obj), self.field.label_from_instance(obj), ) class ModelChoiceField(ChoiceField): """A ChoiceField whose choices are a model QuerySet.""" # This class is a subclass of ChoiceField for purity, but it doesn't # actually use any of ChoiceField's implementation. default_error_messages = { "invalid_choice": _( "Select a valid choice. That choice is not one of the available choices." ), } iterator = ModelChoiceIterator def __init__( self, queryset, *, empty_label="---------", required=True, widget=None, label=None, initial=None, help_text="", to_field_name=None, limit_choices_to=None, blank=False, **kwargs, ): # Call Field instead of ChoiceField __init__() because we don't need # ChoiceField.__init__(). Field.__init__( self, required=required, widget=widget, label=label, initial=initial, help_text=help_text, **kwargs, ) if (required and initial is not None) or ( isinstance(self.widget, RadioSelect) and not blank ): self.empty_label = None else: self.empty_label = empty_label self.queryset = queryset self.limit_choices_to = limit_choices_to # limit the queryset later. self.to_field_name = to_field_name def get_limit_choices_to(self): """ Return ``limit_choices_to`` for this form field. If it is a callable, invoke it and return the result. """ if callable(self.limit_choices_to): return self.limit_choices_to() return self.limit_choices_to def __deepcopy__(self, memo): result = super(ChoiceField, self).__deepcopy__(memo) # Need to force a new ModelChoiceIterator to be created, bug #11183 if self.queryset is not None: result.queryset = self.queryset.all() return result def _get_queryset(self): return self._queryset def _set_queryset(self, queryset): self._queryset = None if queryset is None else queryset.all() self.widget.choices = self.choices queryset = property(_get_queryset, _set_queryset) # this method will be used to create object labels by the QuerySetIterator. # Override it to customize the label. def label_from_instance(self, obj): """ Convert objects into strings and generate the labels for the choices presented by this object. Subclasses can override this method to customize the display of the choices. """ return str(obj) def _get_choices(self): # If self._choices is set, then somebody must have manually set # the property self.choices. In this case, just return self._choices. if hasattr(self, "_choices"): return self._choices # Otherwise, execute the QuerySet in self.queryset to determine the # choices dynamically. Return a fresh ModelChoiceIterator that has not been # consumed. Note that we're instantiating a new ModelChoiceIterator *each* # time _get_choices() is called (and, thus, each time self.choices is # accessed) so that we can ensure the QuerySet has not been consumed. This # construct might look complicated but it allows for lazy evaluation of # the queryset. return self.iterator(self) choices = property(_get_choices, ChoiceField._set_choices) def prepare_value(self, value): if hasattr(value, "_meta"): if self.to_field_name: return value.serializable_value(self.to_field_name) else: return value.pk return super().prepare_value(value) def to_python(self, value): if value in self.empty_values: return None try: key = self.to_field_name or "pk" if isinstance(value, self.queryset.model): value = getattr(value, key) value = self.queryset.get(**{key: value}) except (ValueError, TypeError, self.queryset.model.DoesNotExist): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}, ) return value def validate(self, value): return Field.validate(self, value) def has_changed(self, initial, data): if self.disabled: return False initial_value = initial if initial is not None else "" data_value = data if data is not None else "" return str(self.prepare_value(initial_value)) != str(data_value) class ModelMultipleChoiceField(ModelChoiceField): """A MultipleChoiceField whose choices are a model QuerySet.""" widget = SelectMultiple hidden_widget = MultipleHiddenInput default_error_messages = { "invalid_list": _("Enter a list of values."), "invalid_choice": _( "Select a valid choice. %(value)s is not one of the available choices." ), "invalid_pk_value": _("“%(pk)s” is not a valid value."), } def __init__(self, queryset, **kwargs): super().__init__(queryset, empty_label=None, **kwargs) def to_python(self, value): if not value: return [] return list(self._check_values(value)) def clean(self, value): value = self.prepare_value(value) if self.required and not value: raise ValidationError(self.error_messages["required"], code="required") elif not self.required and not value: return self.queryset.none() if not isinstance(value, (list, tuple)): raise ValidationError( self.error_messages["invalid_list"], code="invalid_list", ) qs = self._check_values(value) # Since this overrides the inherited ModelChoiceField.clean # we run custom validators here self.run_validators(value) return qs def _check_values(self, value): """ Given a list of possible PK values, return a QuerySet of the corresponding objects. Raise a ValidationError if a given value is invalid (not a valid PK, not in the queryset, etc.) """ key = self.to_field_name or "pk" # deduplicate given values to avoid creating many querysets or # requiring the database backend deduplicate efficiently. try: value = frozenset(value) except TypeError: # list of lists isn't hashable, for example raise ValidationError( self.error_messages["invalid_list"], code="invalid_list", ) for pk in value: try: self.queryset.filter(**{key: pk}) except (ValueError, TypeError): raise ValidationError( self.error_messages["invalid_pk_value"], code="invalid_pk_value", params={"pk": pk}, ) qs = self.queryset.filter(**{"%s__in" % key: value}) pks = {str(getattr(o, key)) for o in qs} for val in value: if str(val) not in pks: raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": val}, ) return qs def prepare_value(self, value): if ( hasattr(value, "__iter__") and not isinstance(value, str) and not hasattr(value, "_meta") ): prepare_value = super().prepare_value return [prepare_value(v) for v in value] return super().prepare_value(value) def has_changed(self, initial, data): if self.disabled: return False if initial is None: initial = [] if data is None: data = [] if len(initial) != len(data): return True initial_set = {str(value) for value in self.prepare_value(initial)} data_set = {str(value) for value in data} return data_set != initial_set def modelform_defines_fields(form_class): return hasattr(form_class, "_meta") and ( form_class._meta.fields is not None or form_class._meta.exclude is not None )
695d5b38e00f552568774720ccc43363616bf512a269fc714bba268ea25b60b1
""" HTML Widget classes """ import copy import datetime import warnings from collections import defaultdict from graphlib import CycleError, TopologicalSorter from itertools import chain from django.forms.utils import to_current_timezone from django.templatetags.static import static from django.utils import formats 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.regex_helper import _lazy_re_compile from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ from .renderers import get_default_renderer __all__ = ( "Media", "MediaDefiningClass", "Widget", "TextInput", "NumberInput", "EmailInput", "URLInput", "PasswordInput", "HiddenInput", "MultipleHiddenInput", "FileInput", "ClearableFileInput", "Textarea", "DateInput", "DateTimeInput", "TimeInput", "CheckboxInput", "Select", "NullBooleanSelect", "SelectMultiple", "RadioSelect", "CheckboxSelectMultiple", "MultiWidget", "SplitDateTimeWidget", "SplitHiddenDateTimeWidget", "SelectDateWidget", ) MEDIA_TYPES = ("css", "js") class MediaOrderConflictWarning(RuntimeWarning): pass @html_safe class Media: def __init__(self, media=None, css=None, js=None): if media is not None: css = getattr(media, "css", {}) js = getattr(media, "js", []) else: if css is None: css = {} if js is None: js = [] self._css_lists = [css] self._js_lists = [js] def __repr__(self): return "Media(css=%r, js=%r)" % (self._css, self._js) def __str__(self): return self.render() @property def _css(self): 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): 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 ) ) ) def render_js(self): return [ path.__html__() if hasattr(path, "__html__") else format_html('<script src="{}"></script>', self.absolute_path(path)) for path in self._js ] def render_css(self): # To keep rendering order consistent, we can't just iterate over items(). # We need to sort the keys, and iterate over the sorted list. media = sorted(self._css) return chain.from_iterable( [ path.__html__() if hasattr(path, "__html__") else format_html( '<link href="{}" media="{}" rel="stylesheet">', self.absolute_path(path), medium, ) for path in self._css[medium] ] for medium in media ) def absolute_path(self, path): """ Given a relative or absolute path to a static asset, return an absolute path. An absolute path will be returned unchanged while a relative path will be passed to django.templatetags.static.static(). """ if path.startswith(("http://", "https://", "/")): return path return static(path) def __getitem__(self, name): """Return a Media object that only contains media of the given type.""" if name in MEDIA_TYPES: return Media(**{str(name): getattr(self, "_" + name)}) raise KeyError('Unknown media type "%s"' % name) @staticmethod def merge(*lists): """ 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. """ ts = TopologicalSorter() for head, *tail in filter(None, lists): ts.add(head) # Ensure that the first items are included. for item in tail: if head != item: # Avoid circular dependency to self. ts.add(item, head) head = item try: return list(ts.static_order()) except CycleError: warnings.warn( "Detected duplicate Media files in an opposite order: {}".format( ", ".join(repr(list_) for list_ in lists) ), MediaOrderConflictWarning, ) return list(dict.fromkeys(chain.from_iterable(filter(None, lists)))) def __add__(self, other): combined = Media() combined._css_lists = self._css_lists[:] combined._js_lists = self._js_lists[:] for item in other._css_lists: if item and item not in self._css_lists: combined._css_lists.append(item) for item in other._js_lists: if item and item not in self._js_lists: combined._js_lists.append(item) return combined def media_property(cls): def _media(self): # Get the media property of the superclass, if it exists sup_cls = super(cls, self) try: base = sup_cls.media except AttributeError: base = Media() # Get the media definition for this class definition = getattr(cls, "Media", None) if definition: extend = getattr(definition, "extend", True) if extend: if extend is True: m = base else: m = Media() for medium in extend: m += base[medium] return m + Media(definition) return Media(definition) return base return property(_media) class MediaDefiningClass(type): """ Metaclass for classes that can have media definitions. """ def __new__(mcs, name, bases, attrs): new_class = super().__new__(mcs, name, bases, attrs) if "media" not in attrs: new_class.media = media_property(new_class) return new_class class Widget(metaclass=MediaDefiningClass): needs_multipart_form = False # Determines does this widget need multipart form is_localized = False is_required = False supports_microseconds = True use_fieldset = False def __init__(self, attrs=None): self.attrs = {} if attrs is None else attrs.copy() def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() memo[id(self)] = obj return obj @property def is_hidden(self): return self.input_type == "hidden" if hasattr(self, "input_type") else False def subwidgets(self, name, value, attrs=None): context = self.get_context(name, value, attrs) yield context["widget"] def format_value(self, value): """ Return a value as it should appear when rendered in a template. """ if value == "" or value is None: return None if self.is_localized: return formats.localize_input(value) return str(value) def get_context(self, name, value, attrs): return { "widget": { "name": name, "is_hidden": self.is_hidden, "required": self.is_required, "value": self.format_value(value), "attrs": self.build_attrs(self.attrs, attrs), "template_name": self.template_name, }, } def render(self, name, value, attrs=None, renderer=None): """Render the widget as an HTML string.""" context = self.get_context(name, value, attrs) return self._render(self.template_name, context, renderer) def _render(self, template_name, context, renderer=None): if renderer is None: renderer = get_default_renderer() return mark_safe(renderer.render(template_name, context)) def build_attrs(self, base_attrs, extra_attrs=None): """Build an attribute dictionary.""" return {**base_attrs, **(extra_attrs or {})} def value_from_datadict(self, data, files, name): """ Given a dictionary of data and this widget's name, return the value of this widget or None if it's not provided. """ return data.get(name) def value_omitted_from_data(self, data, files, name): return name not in data def id_for_label(self, id_): """ Return the HTML ID attribute of this Widget for use by a <label>, given the ID of the field. Return an empty string if no ID is available. This hook is necessary because some widgets have multiple HTML elements and, thus, multiple IDs. In that case, this method should return an ID value that corresponds to the first ID in the widget's tags. """ return id_ def use_required_attribute(self, initial): return not self.is_hidden class Input(Widget): """ Base class for all <input> widgets. """ input_type = None # Subclasses must define this. template_name = "django/forms/widgets/input.html" def __init__(self, attrs=None): if attrs is not None: attrs = attrs.copy() self.input_type = attrs.pop("type", self.input_type) super().__init__(attrs) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context["widget"]["type"] = self.input_type return context class TextInput(Input): input_type = "text" template_name = "django/forms/widgets/text.html" class NumberInput(Input): input_type = "number" template_name = "django/forms/widgets/number.html" class EmailInput(Input): input_type = "email" template_name = "django/forms/widgets/email.html" class URLInput(Input): input_type = "url" template_name = "django/forms/widgets/url.html" class PasswordInput(Input): input_type = "password" template_name = "django/forms/widgets/password.html" def __init__(self, attrs=None, render_value=False): super().__init__(attrs) self.render_value = render_value def get_context(self, name, value, attrs): if not self.render_value: value = None return super().get_context(name, value, attrs) class HiddenInput(Input): input_type = "hidden" template_name = "django/forms/widgets/hidden.html" class MultipleHiddenInput(HiddenInput): """ Handle <input type="hidden"> for fields that have a list of values. """ template_name = "django/forms/widgets/multiple_hidden.html" def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) final_attrs = context["widget"]["attrs"] id_ = context["widget"]["attrs"].get("id") subwidgets = [] for index, value_ in enumerate(context["widget"]["value"]): widget_attrs = final_attrs.copy() if id_: # An ID attribute was given. Add a numeric index as a suffix # so that the inputs don't all have the same ID attribute. widget_attrs["id"] = "%s_%s" % (id_, index) widget = HiddenInput() widget.is_required = self.is_required subwidgets.append(widget.get_context(name, value_, widget_attrs)["widget"]) context["widget"]["subwidgets"] = subwidgets return context def value_from_datadict(self, data, files, name): try: getter = data.getlist except AttributeError: getter = data.get return getter(name) def format_value(self, value): return [] if value is None else value class FileInput(Input): input_type = "file" needs_multipart_form = True template_name = "django/forms/widgets/file.html" def format_value(self, value): """File input never renders a value.""" return def value_from_datadict(self, data, files, name): "File widgets take data from FILES, not POST" return files.get(name) def value_omitted_from_data(self, data, files, name): return name not in files def use_required_attribute(self, initial): return super().use_required_attribute(initial) and not initial FILE_INPUT_CONTRADICTION = object() class ClearableFileInput(FileInput): clear_checkbox_label = _("Clear") initial_text = _("Currently") input_text = _("Change") template_name = "django/forms/widgets/clearable_file_input.html" checked = False def clear_checkbox_name(self, name): """ Given the name of the file input, return the name of the clear checkbox input. """ return name + "-clear" def clear_checkbox_id(self, name): """ Given the name of the clear checkbox input, return the HTML id for it. """ return name + "_id" def is_initial(self, value): """ Return whether value is considered to be initial value. """ return bool(value and getattr(value, "url", False)) def format_value(self, value): """ Return the file object if it has a defined url attribute. """ if self.is_initial(value): return value def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) checkbox_name = self.clear_checkbox_name(name) checkbox_id = self.clear_checkbox_id(checkbox_name) context["widget"].update( { "checkbox_name": checkbox_name, "checkbox_id": checkbox_id, "is_initial": self.is_initial(value), "input_text": self.input_text, "initial_text": self.initial_text, "clear_checkbox_label": self.clear_checkbox_label, } ) context["widget"]["attrs"].setdefault("disabled", False) context["widget"]["attrs"]["checked"] = self.checked return context def value_from_datadict(self, data, files, name): upload = super().value_from_datadict(data, files, name) self.checked = self.clear_checkbox_name(name) in data if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name) ): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload def value_omitted_from_data(self, data, files, name): return ( super().value_omitted_from_data(data, files, name) and self.clear_checkbox_name(name) not in data ) class Textarea(Widget): template_name = "django/forms/widgets/textarea.html" def __init__(self, attrs=None): # Use slightly better defaults than HTML's 20x2 box default_attrs = {"cols": "40", "rows": "10"} if attrs: default_attrs.update(attrs) super().__init__(default_attrs) class DateTimeBaseInput(TextInput): format_key = "" supports_microseconds = False def __init__(self, attrs=None, format=None): super().__init__(attrs) self.format = format or None def format_value(self, value): return formats.localize_input( value, self.format or formats.get_format(self.format_key)[0] ) class DateInput(DateTimeBaseInput): format_key = "DATE_INPUT_FORMATS" template_name = "django/forms/widgets/date.html" class DateTimeInput(DateTimeBaseInput): format_key = "DATETIME_INPUT_FORMATS" template_name = "django/forms/widgets/datetime.html" class TimeInput(DateTimeBaseInput): format_key = "TIME_INPUT_FORMATS" template_name = "django/forms/widgets/time.html" # Defined at module level so that CheckboxInput is picklable (#17976) def boolean_check(v): return not (v is False or v is None or v == "") class CheckboxInput(Input): input_type = "checkbox" template_name = "django/forms/widgets/checkbox.html" def __init__(self, attrs=None, check_test=None): super().__init__(attrs) # check_test is a callable that takes a value and returns True # if the checkbox should be checked for that value. self.check_test = boolean_check if check_test is None else check_test def format_value(self, value): """Only return the 'value' attribute if value isn't empty.""" if value is True or value is False or value is None or value == "": return return str(value) def get_context(self, name, value, attrs): if self.check_test(value): attrs = {**(attrs or {}), "checked": True} return super().get_context(name, value, attrs) def value_from_datadict(self, data, files, name): if name not in data: # A missing value means False because HTML form submission does not # send results for unselected checkboxes. return False value = data.get(name) # Translate true and false strings to boolean values. values = {"true": True, "false": False} if isinstance(value, str): value = values.get(value.lower(), value) return bool(value) def value_omitted_from_data(self, data, files, name): # HTML checkboxes don't appear in POST data if not checked, so it's # never known if the value is actually omitted. return False class ChoiceWidget(Widget): allow_multiple_selected = False input_type = None template_name = None option_template_name = None add_id_index = True checked_attribute = {"checked": True} option_inherits_attrs = True def __init__(self, attrs=None, choices=()): super().__init__(attrs) # choices can be any iterable, but we may need to render this widget # multiple times. Thus, collapse it into a list so it can be consumed # more than once. self.choices = list(choices) def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() obj.choices = copy.copy(self.choices) memo[id(self)] = obj return obj def subwidgets(self, name, value, attrs=None): """ Yield all "subwidgets" of this widget. Used to enable iterating options from a BoundField for choice widgets. """ value = self.format_value(value) yield from self.options(name, value, attrs) def options(self, name, value, attrs=None): """Yield a flat list of options for this widget.""" for group in self.optgroups(name, value, attrs): yield from group[1] def optgroups(self, name, value, attrs=None): """Return a list of optgroups for this widget.""" groups = [] has_selected = False for index, (option_value, option_label) in enumerate(self.choices): if option_value is None: option_value = "" subgroup = [] if isinstance(option_label, (list, tuple)): group_name = option_value subindex = 0 choices = option_label else: group_name = None subindex = None choices = [(option_value, option_label)] groups.append((group_name, subgroup, index)) for subvalue, sublabel in choices: selected = (not has_selected or self.allow_multiple_selected) and str( subvalue ) in value has_selected |= selected subgroup.append( self.create_option( name, subvalue, sublabel, selected, index, subindex=subindex, attrs=attrs, ) ) if subindex is not None: subindex += 1 return groups def create_option( self, name, value, label, selected, index, subindex=None, attrs=None ): index = str(index) if subindex is None else "%s_%s" % (index, subindex) option_attrs = ( self.build_attrs(self.attrs, attrs) if self.option_inherits_attrs else {} ) if selected: option_attrs.update(self.checked_attribute) if "id" in option_attrs: option_attrs["id"] = self.id_for_label(option_attrs["id"], index) return { "name": name, "value": value, "label": label, "selected": selected, "index": index, "attrs": option_attrs, "type": self.input_type, "template_name": self.option_template_name, "wrap_label": True, } def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context["widget"]["optgroups"] = self.optgroups( name, context["widget"]["value"], attrs ) return context def id_for_label(self, id_, index="0"): """ Use an incremented id for each option where the main widget references the zero index. """ if id_ and self.add_id_index: id_ = "%s_%s" % (id_, index) return id_ def value_from_datadict(self, data, files, name): getter = data.get if self.allow_multiple_selected: try: getter = data.getlist except AttributeError: pass return getter(name) def format_value(self, value): """Return selected values as a list.""" if value is None and self.allow_multiple_selected: return [] if not isinstance(value, (tuple, list)): value = [value] return [str(v) if v is not None else "" for v in value] class Select(ChoiceWidget): input_type = "select" template_name = "django/forms/widgets/select.html" option_template_name = "django/forms/widgets/select_option.html" add_id_index = False checked_attribute = {"selected": True} option_inherits_attrs = False def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) if self.allow_multiple_selected: context["widget"]["attrs"]["multiple"] = True return context @staticmethod def _choice_has_empty_value(choice): """Return True if the choice's value is empty string or None.""" value, _ = choice return value is None or value == "" def use_required_attribute(self, initial): """ Don't render 'required' if the first <option> has a value, as that's invalid HTML. """ use_required_attribute = super().use_required_attribute(initial) # 'required' is always okay for <select multiple>. if self.allow_multiple_selected: return use_required_attribute first_choice = next(iter(self.choices), None) return ( use_required_attribute and first_choice is not None and self._choice_has_empty_value(first_choice) ) class NullBooleanSelect(Select): """ A Select Widget intended to be used with NullBooleanField. """ def __init__(self, attrs=None): choices = ( ("unknown", _("Unknown")), ("true", _("Yes")), ("false", _("No")), ) super().__init__(attrs, choices) def format_value(self, value): try: return { True: "true", False: "false", "true": "true", "false": "false", # For backwards compatibility with Django < 2.2. "2": "true", "3": "false", }[value] except KeyError: return "unknown" def value_from_datadict(self, data, files, name): value = data.get(name) return { True: True, "True": True, "False": False, False: False, "true": True, "false": False, # For backwards compatibility with Django < 2.2. "2": True, "3": False, }.get(value) class SelectMultiple(Select): allow_multiple_selected = True def value_from_datadict(self, data, files, name): try: getter = data.getlist except AttributeError: getter = data.get return getter(name) def value_omitted_from_data(self, data, files, name): # An unselected <select multiple> doesn't appear in POST data, so it's # never known if the value is actually omitted. return False class RadioSelect(ChoiceWidget): input_type = "radio" template_name = "django/forms/widgets/radio.html" option_template_name = "django/forms/widgets/radio_option.html" use_fieldset = True def id_for_label(self, id_, index=None): """ Don't include for="field_0" in <label> to improve accessibility when using a screen reader, in addition clicking such a label would toggle the first input. """ if index is None: return "" return super().id_for_label(id_, index) class CheckboxSelectMultiple(RadioSelect): allow_multiple_selected = True input_type = "checkbox" template_name = "django/forms/widgets/checkbox_select.html" option_template_name = "django/forms/widgets/checkbox_option.html" def use_required_attribute(self, initial): # Don't use the 'required' attribute because browser validation would # require all checkboxes to be checked instead of at least one. return False def value_omitted_from_data(self, data, files, name): # HTML checkboxes don't appear in POST data if not checked, so it's # never known if the value is actually omitted. return False class MultiWidget(Widget): """ A widget that is composed of multiple widgets. In addition to the values added by Widget.get_context(), this widget adds a list of subwidgets to the context as widget['subwidgets']. These can be looped over and rendered like normal widgets. You'll probably want to use this class with MultiValueField. """ template_name = "django/forms/widgets/multiwidget.html" use_fieldset = True def __init__(self, widgets, attrs=None): if isinstance(widgets, dict): self.widgets_names = [("_%s" % name) if name else "" for name in widgets] widgets = widgets.values() else: self.widgets_names = ["_%s" % i for i in range(len(widgets))] self.widgets = [w() if isinstance(w, type) else w for w in widgets] super().__init__(attrs) @property def is_hidden(self): return all(w.is_hidden for w in self.widgets) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) if self.is_localized: for widget in self.widgets: widget.is_localized = self.is_localized # value is a list/tuple of values, each corresponding to a widget # in self.widgets. if not isinstance(value, (list, tuple)): value = self.decompress(value) final_attrs = context["widget"]["attrs"] input_type = final_attrs.pop("type", None) id_ = final_attrs.get("id") subwidgets = [] for i, (widget_name, widget) in enumerate( zip(self.widgets_names, self.widgets) ): if input_type is not None: widget.input_type = input_type widget_name = name + widget_name try: widget_value = value[i] except IndexError: widget_value = None if id_: widget_attrs = final_attrs.copy() widget_attrs["id"] = "%s_%s" % (id_, i) else: widget_attrs = final_attrs subwidgets.append( widget.get_context(widget_name, widget_value, widget_attrs)["widget"] ) context["widget"]["subwidgets"] = subwidgets return context def id_for_label(self, id_): return "" def value_from_datadict(self, data, files, name): return [ widget.value_from_datadict(data, files, name + widget_name) for widget_name, widget in zip(self.widgets_names, self.widgets) ] def value_omitted_from_data(self, data, files, name): return all( widget.value_omitted_from_data(data, files, name + widget_name) for widget_name, widget in zip(self.widgets_names, self.widgets) ) def decompress(self, value): """ Return a list of decompressed values for the given compressed value. The given value can be assumed to be valid, but not necessarily non-empty. """ raise NotImplementedError("Subclasses must implement this method.") def _get_media(self): """ Media for a multiwidget is the combination of all media of the subwidgets. """ media = Media() for w in self.widgets: media += w.media return media media = property(_get_media) def __deepcopy__(self, memo): obj = super().__deepcopy__(memo) obj.widgets = copy.deepcopy(self.widgets) return obj @property def needs_multipart_form(self): return any(w.needs_multipart_form for w in self.widgets) class SplitDateTimeWidget(MultiWidget): """ A widget that splits datetime input into two <input type="text"> boxes. """ supports_microseconds = False template_name = "django/forms/widgets/splitdatetime.html" def __init__( self, attrs=None, date_format=None, time_format=None, date_attrs=None, time_attrs=None, ): widgets = ( DateInput( attrs=attrs if date_attrs is None else date_attrs, format=date_format, ), TimeInput( attrs=attrs if time_attrs is None else time_attrs, format=time_format, ), ) super().__init__(widgets) def decompress(self, value): if value: value = to_current_timezone(value) return [value.date(), value.time()] return [None, None] class SplitHiddenDateTimeWidget(SplitDateTimeWidget): """ A widget that splits datetime input into two <input type="hidden"> inputs. """ template_name = "django/forms/widgets/splithiddendatetime.html" def __init__( self, attrs=None, date_format=None, time_format=None, date_attrs=None, time_attrs=None, ): super().__init__(attrs, date_format, time_format, date_attrs, time_attrs) for widget in self.widgets: widget.input_type = "hidden" class SelectDateWidget(Widget): """ A widget that splits date input into three <select> boxes. This also serves as an example of a Widget that has more than one HTML element and hence implements value_from_datadict. """ none_value = ("", "---") month_field = "%s_month" day_field = "%s_day" year_field = "%s_year" template_name = "django/forms/widgets/select_date.html" input_type = "select" select_widget = Select date_re = _lazy_re_compile(r"(\d{4}|0)-(\d\d?)-(\d\d?)$") use_fieldset = True def __init__(self, attrs=None, years=None, months=None, empty_label=None): self.attrs = attrs or {} # Optional list or tuple of years to use in the "year" select box. if years: self.years = years else: this_year = datetime.date.today().year self.years = range(this_year, this_year + 10) # Optional dict of months to use in the "month" select box. if months: self.months = months else: self.months = MONTHS # Optional string, list, or tuple to use as empty_label. if isinstance(empty_label, (list, tuple)): if not len(empty_label) == 3: raise ValueError("empty_label list/tuple must have 3 elements.") self.year_none_value = ("", empty_label[0]) self.month_none_value = ("", empty_label[1]) self.day_none_value = ("", empty_label[2]) else: if empty_label is not None: self.none_value = ("", empty_label) self.year_none_value = self.none_value self.month_none_value = self.none_value self.day_none_value = self.none_value def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) date_context = {} year_choices = [(i, str(i)) for i in self.years] if not self.is_required: year_choices.insert(0, self.year_none_value) year_name = self.year_field % name date_context["year"] = self.select_widget( attrs, choices=year_choices ).get_context( name=year_name, value=context["widget"]["value"]["year"], attrs={**context["widget"]["attrs"], "id": "id_%s" % year_name}, ) month_choices = list(self.months.items()) if not self.is_required: month_choices.insert(0, self.month_none_value) month_name = self.month_field % name date_context["month"] = self.select_widget( attrs, choices=month_choices ).get_context( name=month_name, value=context["widget"]["value"]["month"], attrs={**context["widget"]["attrs"], "id": "id_%s" % month_name}, ) day_choices = [(i, i) for i in range(1, 32)] if not self.is_required: day_choices.insert(0, self.day_none_value) day_name = self.day_field % name date_context["day"] = self.select_widget( attrs, choices=day_choices, ).get_context( name=day_name, value=context["widget"]["value"]["day"], attrs={**context["widget"]["attrs"], "id": "id_%s" % day_name}, ) subwidgets = [] for field in self._parse_date_fmt(): subwidgets.append(date_context[field]["widget"]) context["widget"]["subwidgets"] = subwidgets return context def format_value(self, value): """ Return a dict containing the year, month, and day of the current value. Use dict instead of a datetime to allow invalid dates such as February 31 to display correctly. """ year, month, day = None, None, None if isinstance(value, (datetime.date, datetime.datetime)): year, month, day = value.year, value.month, value.day elif isinstance(value, str): match = self.date_re.match(value) if match: # Convert any zeros in the date to empty strings to match the # empty option value. year, month, day = [int(val) or "" for val in match.groups()] else: input_format = get_format("DATE_INPUT_FORMATS")[0] try: d = datetime.datetime.strptime(value, input_format) except ValueError: pass else: year, month, day = d.year, d.month, d.day return {"year": year, "month": month, "day": day} @staticmethod def _parse_date_fmt(): fmt = get_format("DATE_FORMAT") escaped = False for char in fmt: if escaped: escaped = False elif char == "\\": escaped = True elif char in "Yy": yield "year" elif char in "bEFMmNn": yield "month" elif char in "dj": yield "day" def id_for_label(self, id_): for first_select in self._parse_date_fmt(): return "%s_%s" % (id_, first_select) return "%s_month" % id_ def value_from_datadict(self, data, files, name): y = data.get(self.year_field % name) m = data.get(self.month_field % name) d = data.get(self.day_field % name) if y == m == d == "": return None if y is not None and m is not None and d is not None: input_format = get_format("DATE_INPUT_FORMATS")[0] input_format = formats.sanitize_strftime_format(input_format) try: date_value = datetime.date(int(y), int(m), int(d)) except ValueError: # Return pseudo-ISO dates with zeros for any unselected values, # e.g. '2017-0-23'. return "%s-%s-%s" % (y or 0, m or 0, d or 0) except OverflowError: return "0-0-0" return date_value.strftime(input_format) return data.get(name) def value_omitted_from_data(self, data, files, name): return not any( ("{}_{}".format(name, interval) in data) for interval in ("year", "month", "day") )
77a5c981469631bfea2577f67a44c258553a061230445e451fb756969426f8d5
""" Field classes. """ import copy import datetime import json import math import operator import os import re import uuid import warnings from decimal import Decimal, DecimalException from io import BytesIO from urllib.parse import urlsplit, urlunsplit from django.core import validators from django.core.exceptions import ValidationError from django.db.models.enums import ChoicesMeta from django.forms.boundfield import BoundField from django.forms.utils import from_current_timezone, to_current_timezone from django.forms.widgets import ( FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput, DateInput, DateTimeInput, EmailInput, FileInput, HiddenInput, MultipleHiddenInput, NullBooleanSelect, NumberInput, Select, SelectMultiple, SplitDateTimeWidget, SplitHiddenDateTimeWidget, Textarea, TextInput, TimeInput, URLInput, ) from django.utils import formats from django.utils.dateparse import parse_datetime, parse_duration from django.utils.deprecation import RemovedInDjango60Warning from django.utils.duration import duration_string from django.utils.ipv6 import clean_ipv6_address from django.utils.regex_helper import _lazy_re_compile from django.utils.translation import gettext_lazy as _ from django.utils.translation import ngettext_lazy __all__ = ( "Field", "CharField", "IntegerField", "DateField", "TimeField", "DateTimeField", "DurationField", "RegexField", "EmailField", "FileField", "ImageField", "URLField", "BooleanField", "NullBooleanField", "ChoiceField", "MultipleChoiceField", "ComboField", "MultiValueField", "FloatField", "DecimalField", "SplitDateTimeField", "GenericIPAddressField", "FilePathField", "JSONField", "SlugField", "TypedChoiceField", "TypedMultipleChoiceField", "UUIDField", ) class Field: widget = TextInput # Default widget to use when rendering this type of Field. hidden_widget = ( HiddenInput # Default widget to use when rendering this as "hidden". ) default_validators = [] # Default set of validators # Add an 'invalid' entry to default_error_message if you want a specific # field error message not raised by the field validators. default_error_messages = { "required": _("This field is required."), } empty_values = list(validators.EMPTY_VALUES) def __init__( self, *, required=True, widget=None, label=None, initial=None, help_text="", error_messages=None, show_hidden_initial=False, validators=(), localize=False, disabled=False, label_suffix=None, template_name=None, ): # required -- Boolean that specifies whether the field is required. # True by default. # widget -- A Widget class, or instance of a Widget class, that should # be used for this Field when displaying it. Each Field has a # default Widget that it'll use if you don't specify this. In # most cases, the default widget is TextInput. # label -- A verbose name for this field, for use in displaying this # field in a form. By default, Django will use a "pretty" # version of the form field name, if the Field is part of a # Form. # initial -- A value to use in this Field's initial display. This value # is *not* used as a fallback if data isn't given. # help_text -- An optional string to use as "help text" for this Field. # error_messages -- An optional dictionary to override the default # messages that the field will raise. # show_hidden_initial -- Boolean that specifies if it is needed to render a # hidden widget with initial value after widget. # validators -- List of additional validators to use # localize -- Boolean that specifies if the field should be localized. # disabled -- Boolean that specifies whether the field is disabled, that # is its widget is shown in the form but not editable. # label_suffix -- Suffix to be added to the label. Overrides # form's label_suffix. self.required, self.label, self.initial = required, label, initial self.show_hidden_initial = show_hidden_initial self.help_text = help_text self.disabled = disabled self.label_suffix = label_suffix widget = widget or self.widget if isinstance(widget, type): widget = widget() else: widget = copy.deepcopy(widget) # Trigger the localization machinery if needed. self.localize = localize if self.localize: widget.is_localized = True # Let the widget know whether it should display as required. widget.is_required = self.required # Hook into self.widget_attrs() for any Field-specific HTML attributes. extra_attrs = self.widget_attrs(widget) if extra_attrs: widget.attrs.update(extra_attrs) self.widget = widget messages = {} for c in reversed(self.__class__.__mro__): messages.update(getattr(c, "default_error_messages", {})) messages.update(error_messages or {}) self.error_messages = messages self.validators = [*self.default_validators, *validators] self.template_name = template_name super().__init__() def prepare_value(self, value): return value def to_python(self, value): return value def validate(self, value): if value in self.empty_values and self.required: raise ValidationError(self.error_messages["required"], code="required") def run_validators(self, value): if value in self.empty_values: return errors = [] for v in self.validators: try: v(value) except ValidationError as e: if hasattr(e, "code") and e.code in self.error_messages: e.message = self.error_messages[e.code] errors.extend(e.error_list) if errors: raise ValidationError(errors) def clean(self, value): """ Validate the given value and return its "cleaned" value as an appropriate Python object. Raise ValidationError for any errors. """ value = self.to_python(value) self.validate(value) self.run_validators(value) return value def bound_data(self, data, initial): """ Return the value that should be shown for this field on render of a bound form, given the submitted POST data for the field and the initial data, if any. For most fields, this will simply be data; FileFields need to handle it a bit differently. """ if self.disabled: return initial return data def widget_attrs(self, widget): """ Given a Widget instance (*not* a Widget class), return a dictionary of any HTML attributes that should be added to the Widget, based on this Field. """ return {} def has_changed(self, initial, data): """Return True if data differs from initial.""" # Always return False if the field is disabled since self.bound_data # always uses the initial value in this case. if self.disabled: return False try: data = self.to_python(data) if hasattr(self, "_coerce"): return self._coerce(data) != self._coerce(initial) except ValidationError: return True # For purposes of seeing whether something has changed, None is # the same as an empty string, if the data or initial value we get # is None, replace it with ''. initial_value = initial if initial is not None else "" data_value = data if data is not None else "" return initial_value != data_value def get_bound_field(self, form, field_name): """ Return a BoundField instance that will be used when accessing the form field in a template. """ return BoundField(form, self, field_name) def __deepcopy__(self, memo): result = copy.copy(self) memo[id(self)] = result result.widget = copy.deepcopy(self.widget, memo) result.error_messages = self.error_messages.copy() result.validators = self.validators[:] return result class CharField(Field): def __init__( self, *, max_length=None, min_length=None, strip=True, empty_value="", **kwargs ): self.max_length = max_length self.min_length = min_length self.strip = strip self.empty_value = empty_value super().__init__(**kwargs) if min_length is not None: self.validators.append(validators.MinLengthValidator(int(min_length))) if max_length is not None: self.validators.append(validators.MaxLengthValidator(int(max_length))) self.validators.append(validators.ProhibitNullCharactersValidator()) def to_python(self, value): """Return a string.""" if value not in self.empty_values: value = str(value) if self.strip: value = value.strip() if value in self.empty_values: return self.empty_value return value def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if self.max_length is not None and not widget.is_hidden: # The HTML attribute is maxlength, not max_length. attrs["maxlength"] = str(self.max_length) if self.min_length is not None and not widget.is_hidden: # The HTML attribute is minlength, not min_length. attrs["minlength"] = str(self.min_length) return attrs class IntegerField(Field): widget = NumberInput default_error_messages = { "invalid": _("Enter a whole number."), } re_decimal = _lazy_re_compile(r"\.0*\s*$") def __init__(self, *, max_value=None, min_value=None, step_size=None, **kwargs): self.max_value, self.min_value, self.step_size = max_value, min_value, step_size if kwargs.get("localize") and self.widget == NumberInput: # Localized number input is not well supported on most browsers kwargs.setdefault("widget", super().widget) super().__init__(**kwargs) if max_value is not None: self.validators.append(validators.MaxValueValidator(max_value)) if min_value is not None: self.validators.append(validators.MinValueValidator(min_value)) if step_size is not None: self.validators.append(validators.StepValueValidator(step_size)) def to_python(self, value): """ Validate that int() can be called on the input. Return the result of int() or None for empty values. """ value = super().to_python(value) if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) # Strip trailing decimal and zeros. try: value = int(self.re_decimal.sub("", str(value))) except (ValueError, TypeError): raise ValidationError(self.error_messages["invalid"], code="invalid") return value def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput): if self.min_value is not None: attrs["min"] = self.min_value if self.max_value is not None: attrs["max"] = self.max_value if self.step_size is not None: attrs["step"] = self.step_size return attrs class FloatField(IntegerField): default_error_messages = { "invalid": _("Enter a number."), } def to_python(self, value): """ Validate that float() can be called on the input. Return the result of float() or None for empty values. """ value = super(IntegerField, self).to_python(value) if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) try: value = float(value) except (ValueError, TypeError): raise ValidationError(self.error_messages["invalid"], code="invalid") return value def validate(self, value): super().validate(value) if value in self.empty_values: return if not math.isfinite(value): raise ValidationError(self.error_messages["invalid"], code="invalid") def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput) and "step" not in widget.attrs: if self.step_size is not None: step = str(self.step_size) else: step = "any" attrs.setdefault("step", step) return attrs class DecimalField(IntegerField): default_error_messages = { "invalid": _("Enter a number."), } def __init__( self, *, max_value=None, min_value=None, max_digits=None, decimal_places=None, **kwargs, ): self.max_digits, self.decimal_places = max_digits, decimal_places super().__init__(max_value=max_value, min_value=min_value, **kwargs) self.validators.append(validators.DecimalValidator(max_digits, decimal_places)) def to_python(self, value): """ Validate that the input is a decimal number. Return a Decimal instance or None for empty values. Ensure that there are no more than max_digits in the number and no more than decimal_places digits after the decimal point. """ if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) try: value = Decimal(str(value)) except DecimalException: raise ValidationError(self.error_messages["invalid"], code="invalid") return value def validate(self, value): super().validate(value) if value in self.empty_values: return if not value.is_finite(): raise ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput) and "step" not in widget.attrs: if self.decimal_places is not None: # Use exponential notation for small values since they might # be parsed as 0 otherwise. ref #20765 step = str(Decimal(1).scaleb(-self.decimal_places)).lower() else: step = "any" attrs.setdefault("step", step) return attrs class BaseTemporalField(Field): def __init__(self, *, input_formats=None, **kwargs): super().__init__(**kwargs) if input_formats is not None: self.input_formats = input_formats def to_python(self, value): value = value.strip() # Try to strptime against each input format. for format in self.input_formats: try: return self.strptime(value, format) except (ValueError, TypeError): continue raise ValidationError(self.error_messages["invalid"], code="invalid") def strptime(self, value, format): raise NotImplementedError("Subclasses must define this method.") class DateField(BaseTemporalField): widget = DateInput input_formats = formats.get_format_lazy("DATE_INPUT_FORMATS") default_error_messages = { "invalid": _("Enter a valid date."), } def to_python(self, value): """ Validate that the input can be converted to a date. Return a Python datetime.date object. """ if value in self.empty_values: return None if isinstance(value, datetime.datetime): return value.date() if isinstance(value, datetime.date): return value return super().to_python(value) def strptime(self, value, format): return datetime.datetime.strptime(value, format).date() class TimeField(BaseTemporalField): widget = TimeInput input_formats = formats.get_format_lazy("TIME_INPUT_FORMATS") default_error_messages = {"invalid": _("Enter a valid time.")} def to_python(self, value): """ Validate that the input can be converted to a time. Return a Python datetime.time object. """ if value in self.empty_values: return None if isinstance(value, datetime.time): return value return super().to_python(value) def strptime(self, value, format): return datetime.datetime.strptime(value, format).time() class DateTimeFormatsIterator: def __iter__(self): yield from formats.get_format("DATETIME_INPUT_FORMATS") yield from formats.get_format("DATE_INPUT_FORMATS") class DateTimeField(BaseTemporalField): widget = DateTimeInput input_formats = DateTimeFormatsIterator() default_error_messages = { "invalid": _("Enter a valid date/time."), } def prepare_value(self, value): if isinstance(value, datetime.datetime): value = to_current_timezone(value) return value def to_python(self, value): """ Validate that the input can be converted to a datetime. Return a Python datetime.datetime object. """ if value in self.empty_values: return None if isinstance(value, datetime.datetime): return from_current_timezone(value) if isinstance(value, datetime.date): result = datetime.datetime(value.year, value.month, value.day) return from_current_timezone(result) try: result = parse_datetime(value.strip()) except ValueError: raise ValidationError(self.error_messages["invalid"], code="invalid") if not result: result = super().to_python(value) return from_current_timezone(result) def strptime(self, value, format): return datetime.datetime.strptime(value, format) class DurationField(Field): default_error_messages = { "invalid": _("Enter a valid duration."), "overflow": _("The number of days must be between {min_days} and {max_days}."), } def prepare_value(self, value): if isinstance(value, datetime.timedelta): return duration_string(value) return value def to_python(self, value): if value in self.empty_values: return None if isinstance(value, datetime.timedelta): return value try: value = parse_duration(str(value)) except OverflowError: raise ValidationError( self.error_messages["overflow"].format( min_days=datetime.timedelta.min.days, max_days=datetime.timedelta.max.days, ), code="overflow", ) if value is None: raise ValidationError(self.error_messages["invalid"], code="invalid") return value class RegexField(CharField): def __init__(self, regex, **kwargs): """ regex can be either a string or a compiled regular expression object. """ kwargs.setdefault("strip", False) super().__init__(**kwargs) self._set_regex(regex) def _get_regex(self): return self._regex def _set_regex(self, regex): if isinstance(regex, str): regex = re.compile(regex) self._regex = regex if ( hasattr(self, "_regex_validator") and self._regex_validator in self.validators ): self.validators.remove(self._regex_validator) self._regex_validator = validators.RegexValidator(regex=regex) self.validators.append(self._regex_validator) regex = property(_get_regex, _set_regex) class EmailField(CharField): widget = EmailInput default_validators = [validators.validate_email] def __init__(self, **kwargs): super().__init__(strip=True, **kwargs) class FileField(Field): widget = ClearableFileInput default_error_messages = { "invalid": _("No file was submitted. Check the encoding type on the form."), "missing": _("No file was submitted."), "empty": _("The submitted file is empty."), "max_length": ngettext_lazy( "Ensure this filename has at most %(max)d character (it has %(length)d).", "Ensure this filename has at most %(max)d characters (it has %(length)d).", "max", ), "contradiction": _( "Please either submit a file or check the clear checkbox, not both." ), } def __init__(self, *, max_length=None, allow_empty_file=False, **kwargs): self.max_length = max_length self.allow_empty_file = allow_empty_file super().__init__(**kwargs) def to_python(self, data): if data in self.empty_values: return None # UploadedFile objects should have name and size attributes. try: file_name = data.name file_size = data.size except AttributeError: raise ValidationError(self.error_messages["invalid"], code="invalid") if self.max_length is not None and len(file_name) > self.max_length: params = {"max": self.max_length, "length": len(file_name)} raise ValidationError( self.error_messages["max_length"], code="max_length", params=params ) if not file_name: raise ValidationError(self.error_messages["invalid"], code="invalid") if not self.allow_empty_file and not file_size: raise ValidationError(self.error_messages["empty"], code="empty") return data def clean(self, data, initial=None): # If the widget got contradictory inputs, we raise a validation error if data is FILE_INPUT_CONTRADICTION: raise ValidationError( self.error_messages["contradiction"], code="contradiction" ) # False means the field value should be cleared; further validation is # not needed. if data is False: if not self.required: return False # If the field is required, clearing is not possible (the widget # shouldn't return False data in that case anyway). False is not # in self.empty_value; if a False value makes it this far # it should be validated from here on out as None (so it will be # caught by the required check). data = None if not data and initial: return initial return super().clean(data) def bound_data(self, _, initial): return initial def has_changed(self, initial, data): return not self.disabled and data is not None class ImageField(FileField): default_validators = [validators.validate_image_file_extension] default_error_messages = { "invalid_image": _( "Upload a valid image. The file you uploaded was either not an " "image or a corrupted image." ), } def to_python(self, data): """ Check that the file-upload field data contains a valid image (GIF, JPG, PNG, etc. -- whatever Pillow supports). """ f = super().to_python(data) if f is None: return None from PIL import Image # We need to get a file object for Pillow. We might have a path or we might # have to read the data into memory. if hasattr(data, "temporary_file_path"): file = data.temporary_file_path() else: if hasattr(data, "read"): file = BytesIO(data.read()) else: file = BytesIO(data["content"]) try: # load() could spot a truncated JPEG, but it loads the entire # image in memory, which is a DoS vector. See #3848 and #18520. image = Image.open(file) # verify() must be called immediately after the constructor. image.verify() # Annotating so subclasses can reuse it for their own validation f.image = image # Pillow doesn't detect the MIME type of all formats. In those # cases, content_type will be None. f.content_type = Image.MIME.get(image.format) except Exception as exc: # Pillow doesn't recognize it as an image. raise ValidationError( self.error_messages["invalid_image"], code="invalid_image", ) from exc if hasattr(f, "seek") and callable(f.seek): f.seek(0) return f def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, FileInput) and "accept" not in widget.attrs: attrs.setdefault("accept", "image/*") return attrs class URLField(CharField): widget = URLInput default_error_messages = { "invalid": _("Enter a valid URL."), } default_validators = [validators.URLValidator()] def __init__(self, *, assume_scheme=None, **kwargs): if assume_scheme is None: warnings.warn( "The default scheme will be changed from 'http' to 'https' in Django " "6.0. Pass the forms.URLField.assume_scheme argument to silence this " "warning.", RemovedInDjango60Warning, stacklevel=2, ) assume_scheme = "http" # RemovedInDjango60Warning: When the deprecation ends, replace with: # self.assume_scheme = assume_scheme or "https" self.assume_scheme = assume_scheme super().__init__(strip=True, **kwargs) def to_python(self, value): def split_url(url): """ Return a list of url parts via urlparse.urlsplit(), or raise ValidationError for some malformed URLs. """ try: return list(urlsplit(url)) except ValueError: # urlparse.urlsplit can raise a ValueError with some # misformatted URLs. raise ValidationError(self.error_messages["invalid"], code="invalid") value = super().to_python(value) if value: url_fields = split_url(value) if not url_fields[0]: # If no URL scheme given, add a scheme. url_fields[0] = self.assume_scheme if not url_fields[1]: # Assume that if no domain is provided, that the path segment # contains the domain. url_fields[1] = url_fields[2] url_fields[2] = "" # Rebuild the url_fields list, since the domain segment may now # contain the path too. url_fields = split_url(urlunsplit(url_fields)) value = urlunsplit(url_fields) return value class BooleanField(Field): widget = CheckboxInput def to_python(self, value): """Return a Python boolean object.""" # Explicitly check for the string 'False', which is what a hidden field # will submit for False. Also check for '0', since this is what # RadioSelect will provide. Because bool("True") == bool('1') == True, # we don't need to handle that explicitly. if isinstance(value, str) and value.lower() in ("false", "0"): value = False else: value = bool(value) return super().to_python(value) def validate(self, value): if not value and self.required: raise ValidationError(self.error_messages["required"], code="required") def has_changed(self, initial, data): if self.disabled: return False # Sometimes data or initial may be a string equivalent of a boolean # so we should run it through to_python first to get a boolean value return self.to_python(initial) != self.to_python(data) class NullBooleanField(BooleanField): """ A field whose valid values are None, True, and False. Clean invalid values to None. """ widget = NullBooleanSelect def to_python(self, value): """ Explicitly check for the string 'True' and 'False', which is what a hidden field will submit for True and False, for 'true' and 'false', which are likely to be returned by JavaScript serializations of forms, and for '1' and '0', which is what a RadioField will submit. Unlike the Booleanfield, this field must check for True because it doesn't use the bool() function. """ if value in (True, "True", "true", "1"): return True elif value in (False, "False", "false", "0"): return False else: return None def validate(self, value): pass class CallableChoiceIterator: def __init__(self, choices_func): self.choices_func = choices_func def __iter__(self): yield from self.choices_func() class ChoiceField(Field): widget = Select default_error_messages = { "invalid_choice": _( "Select a valid choice. %(value)s is not one of the available choices." ), } def __init__(self, *, choices=(), **kwargs): super().__init__(**kwargs) if isinstance(choices, ChoicesMeta): choices = choices.choices self.choices = choices def __deepcopy__(self, memo): result = super().__deepcopy__(memo) result._choices = copy.deepcopy(self._choices, memo) return result def _get_choices(self): return self._choices def _set_choices(self, value): # Setting choices also sets the choices on the widget. # choices can be any iterable, but we call list() on it because # it will be consumed more than once. if callable(value): value = CallableChoiceIterator(value) else: value = list(value) self._choices = self.widget.choices = value choices = property(_get_choices, _set_choices) def to_python(self, value): """Return a string.""" if value in self.empty_values: return "" return str(value) def validate(self, value): """Validate that the input is in self.choices.""" super().validate(value) if value and not self.valid_value(value): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}, ) def valid_value(self, value): """Check to see if the provided value is a valid choice.""" text_value = str(value) for k, v in self.choices: if isinstance(v, (list, tuple)): # This is an optgroup, so look inside the group for options for k2, v2 in v: if value == k2 or text_value == str(k2): return True else: if value == k or text_value == str(k): return True return False class TypedChoiceField(ChoiceField): def __init__(self, *, coerce=lambda val: val, empty_value="", **kwargs): self.coerce = coerce self.empty_value = empty_value super().__init__(**kwargs) def _coerce(self, value): """ Validate that the value can be coerced to the right type (if not empty). """ if value == self.empty_value or value in self.empty_values: return self.empty_value try: value = self.coerce(value) except (ValueError, TypeError, ValidationError): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}, ) return value def clean(self, value): value = super().clean(value) return self._coerce(value) class MultipleChoiceField(ChoiceField): hidden_widget = MultipleHiddenInput widget = SelectMultiple default_error_messages = { "invalid_choice": _( "Select a valid choice. %(value)s is not one of the available choices." ), "invalid_list": _("Enter a list of values."), } def to_python(self, value): if not value: return [] elif not isinstance(value, (list, tuple)): raise ValidationError( self.error_messages["invalid_list"], code="invalid_list" ) return [str(val) for val in value] def validate(self, value): """Validate that the input is a list or tuple.""" if self.required and not value: raise ValidationError(self.error_messages["required"], code="required") # Validate that each value in the value list is in self.choices. for val in value: if not self.valid_value(val): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": val}, ) def has_changed(self, initial, data): if self.disabled: return False if initial is None: initial = [] if data is None: data = [] if len(initial) != len(data): return True initial_set = {str(value) for value in initial} data_set = {str(value) for value in data} return data_set != initial_set class TypedMultipleChoiceField(MultipleChoiceField): def __init__(self, *, coerce=lambda val: val, **kwargs): self.coerce = coerce self.empty_value = kwargs.pop("empty_value", []) super().__init__(**kwargs) def _coerce(self, value): """ Validate that the values are in self.choices and can be coerced to the right type. """ if value == self.empty_value or value in self.empty_values: return self.empty_value new_value = [] for choice in value: try: new_value.append(self.coerce(choice)) except (ValueError, TypeError, ValidationError): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": choice}, ) return new_value def clean(self, value): value = super().clean(value) return self._coerce(value) def validate(self, value): if value != self.empty_value: super().validate(value) elif self.required: raise ValidationError(self.error_messages["required"], code="required") class ComboField(Field): """ A Field whose clean() method calls multiple Field clean() methods. """ def __init__(self, fields, **kwargs): super().__init__(**kwargs) # Set 'required' to False on the individual fields, because the # required validation will be handled by ComboField, not by those # individual fields. for f in fields: f.required = False self.fields = fields def clean(self, value): """ Validate the given value against all of self.fields, which is a list of Field instances. """ super().clean(value) for field in self.fields: value = field.clean(value) return value class MultiValueField(Field): """ Aggregate the logic of multiple Fields. Its clean() method takes a "decompressed" list of values, which are then cleaned into a single value according to self.fields. Each value in this list is cleaned by the corresponding field -- the first value is cleaned by the first field, the second value is cleaned by the second field, etc. Once all fields are cleaned, the list of clean values is "compressed" into a single value. Subclasses should not have to implement clean(). Instead, they must implement compress(), which takes a list of valid values and returns a "compressed" version of those values -- a single value. You'll probably want to use this with MultiWidget. """ default_error_messages = { "invalid": _("Enter a list of values."), "incomplete": _("Enter a complete value."), } def __init__(self, fields, *, require_all_fields=True, **kwargs): self.require_all_fields = require_all_fields super().__init__(**kwargs) for f in fields: f.error_messages.setdefault("incomplete", self.error_messages["incomplete"]) if self.disabled: f.disabled = True if self.require_all_fields: # Set 'required' to False on the individual fields, because the # required validation will be handled by MultiValueField, not # by those individual fields. f.required = False self.fields = fields def __deepcopy__(self, memo): result = super().__deepcopy__(memo) result.fields = tuple(x.__deepcopy__(memo) for x in self.fields) return result def validate(self, value): pass def clean(self, value): """ Validate every value in the given list. A value is validated against the corresponding Field in self.fields. For example, if this MultiValueField was instantiated with fields=(DateField(), TimeField()), clean() would call DateField.clean(value[0]) and TimeField.clean(value[1]). """ clean_data = [] errors = [] if self.disabled and not isinstance(value, list): value = self.widget.decompress(value) if not value or isinstance(value, (list, tuple)): if not value or not [v for v in value if v not in self.empty_values]: if self.required: raise ValidationError( self.error_messages["required"], code="required" ) else: return self.compress([]) else: raise ValidationError(self.error_messages["invalid"], code="invalid") for i, field in enumerate(self.fields): try: field_value = value[i] except IndexError: field_value = None if field_value in self.empty_values: if self.require_all_fields: # Raise a 'required' error if the MultiValueField is # required and any field is empty. if self.required: raise ValidationError( self.error_messages["required"], code="required" ) elif field.required: # Otherwise, add an 'incomplete' error to the list of # collected errors and skip field cleaning, if a required # field is empty. if field.error_messages["incomplete"] not in errors: errors.append(field.error_messages["incomplete"]) continue try: clean_data.append(field.clean(field_value)) except ValidationError as e: # Collect all validation errors in a single list, which we'll # raise at the end of clean(), rather than raising a single # exception for the first error we encounter. Skip duplicates. errors.extend(m for m in e.error_list if m not in errors) if errors: raise ValidationError(errors) out = self.compress(clean_data) self.validate(out) self.run_validators(out) return out def compress(self, data_list): """ Return a single value for the given list of values. The values can be assumed to be valid. For example, if this MultiValueField was instantiated with fields=(DateField(), TimeField()), this might return a datetime object created by combining the date and time in data_list. """ raise NotImplementedError("Subclasses must implement this method.") def has_changed(self, initial, data): if self.disabled: return False if initial is None: initial = ["" for x in range(0, len(data))] else: if not isinstance(initial, list): initial = self.widget.decompress(initial) for field, initial, data in zip(self.fields, initial, data): try: initial = field.to_python(initial) except ValidationError: return True if field.has_changed(initial, data): return True return False class FilePathField(ChoiceField): def __init__( self, path, *, match=None, recursive=False, allow_files=True, allow_folders=False, **kwargs, ): self.path, self.match, self.recursive = path, match, recursive self.allow_files, self.allow_folders = allow_files, allow_folders super().__init__(choices=(), **kwargs) if self.required: self.choices = [] else: self.choices = [("", "---------")] if self.match is not None: self.match_re = re.compile(self.match) if recursive: for root, dirs, files in sorted(os.walk(self.path)): if self.allow_files: for f in sorted(files): if self.match is None or self.match_re.search(f): f = os.path.join(root, f) self.choices.append((f, f.replace(path, "", 1))) if self.allow_folders: for f in sorted(dirs): if f == "__pycache__": continue if self.match is None or self.match_re.search(f): f = os.path.join(root, f) self.choices.append((f, f.replace(path, "", 1))) else: choices = [] with os.scandir(self.path) as entries: for f in entries: if f.name == "__pycache__": continue if ( (self.allow_files and f.is_file()) or (self.allow_folders and f.is_dir()) ) and (self.match is None or self.match_re.search(f.name)): choices.append((f.path, f.name)) choices.sort(key=operator.itemgetter(1)) self.choices.extend(choices) self.widget.choices = self.choices class SplitDateTimeField(MultiValueField): widget = SplitDateTimeWidget hidden_widget = SplitHiddenDateTimeWidget default_error_messages = { "invalid_date": _("Enter a valid date."), "invalid_time": _("Enter a valid time."), } def __init__(self, *, input_date_formats=None, input_time_formats=None, **kwargs): errors = self.default_error_messages.copy() if "error_messages" in kwargs: errors.update(kwargs["error_messages"]) localize = kwargs.get("localize", False) fields = ( DateField( input_formats=input_date_formats, error_messages={"invalid": errors["invalid_date"]}, localize=localize, ), TimeField( input_formats=input_time_formats, error_messages={"invalid": errors["invalid_time"]}, localize=localize, ), ) super().__init__(fields, **kwargs) def compress(self, data_list): if data_list: # Raise a validation error if time or date is empty # (possible if SplitDateTimeField has required=False). if data_list[0] in self.empty_values: raise ValidationError( self.error_messages["invalid_date"], code="invalid_date" ) if data_list[1] in self.empty_values: raise ValidationError( self.error_messages["invalid_time"], code="invalid_time" ) result = datetime.datetime.combine(*data_list) return from_current_timezone(result) return None class GenericIPAddressField(CharField): def __init__(self, *, protocol="both", unpack_ipv4=False, **kwargs): self.unpack_ipv4 = unpack_ipv4 self.default_validators = validators.ip_address_validators( protocol, unpack_ipv4 )[0] super().__init__(**kwargs) def to_python(self, value): if value in self.empty_values: return "" value = value.strip() if value and ":" in value: return clean_ipv6_address(value, self.unpack_ipv4) return value class SlugField(CharField): default_validators = [validators.validate_slug] def __init__(self, *, allow_unicode=False, **kwargs): self.allow_unicode = allow_unicode if self.allow_unicode: self.default_validators = [validators.validate_unicode_slug] super().__init__(**kwargs) class UUIDField(CharField): default_error_messages = { "invalid": _("Enter a valid UUID."), } def prepare_value(self, value): if isinstance(value, uuid.UUID): return str(value) return value def to_python(self, value): value = super().to_python(value) if value in self.empty_values: return None if not isinstance(value, uuid.UUID): try: value = uuid.UUID(value) except ValueError: raise ValidationError(self.error_messages["invalid"], code="invalid") return value class InvalidJSONInput(str): pass class JSONString(str): pass class JSONField(CharField): default_error_messages = { "invalid": _("Enter a valid JSON."), } widget = Textarea def __init__(self, encoder=None, decoder=None, **kwargs): self.encoder = encoder self.decoder = decoder super().__init__(**kwargs) def to_python(self, value): if self.disabled: return value if value in self.empty_values: return None elif isinstance(value, (list, dict, int, float, JSONString)): return value try: converted = json.loads(value, cls=self.decoder) except json.JSONDecodeError: raise ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) if isinstance(converted, str): return JSONString(converted) else: return converted def bound_data(self, data, initial): if self.disabled: return initial if data is None: return None try: return json.loads(data, cls=self.decoder) except json.JSONDecodeError: return InvalidJSONInput(data) def prepare_value(self, value): if isinstance(value, InvalidJSONInput): return value return json.dumps(value, ensure_ascii=False, cls=self.encoder) def has_changed(self, initial, data): if super().has_changed(initial, data): return True # For purposes of seeing whether something has changed, True isn't the # same as 1 and the order of keys doesn't matter. return json.dumps(initial, sort_keys=True, cls=self.encoder) != json.dumps( self.to_python(data), sort_keys=True, cls=self.encoder )
605476104d16d9c2e112e5d2588ebb737dc3ade5554b1973f71463a86b39d337
import collections.abc import inspect import warnings from math import ceil from django.utils.functional import cached_property from django.utils.inspect import method_has_no_args from django.utils.translation import gettext_lazy as _ class UnorderedObjectListWarning(RuntimeWarning): pass class InvalidPage(Exception): pass class PageNotAnInteger(InvalidPage): pass class EmptyPage(InvalidPage): pass class Paginator: # Translators: String used to replace omitted page numbers in elided page # range generated by paginators, e.g. [1, 2, '…', 5, 6, 7, '…', 9, 10]. ELLIPSIS = _("…") default_error_messages = { "invalid_page": _("That page number is not an integer"), "min_page": _("That page number is less than 1"), "no_results": _("That page contains no results"), } def __init__( self, object_list, per_page, orphans=0, allow_empty_first_page=True, error_messages=None, ): self.object_list = object_list self._check_object_list_is_ordered() self.per_page = int(per_page) self.orphans = int(orphans) self.allow_empty_first_page = allow_empty_first_page self.error_messages = ( self.default_error_messages if error_messages is None else self.default_error_messages | error_messages ) def __iter__(self): for page_number in self.page_range: yield self.page(page_number) def validate_number(self, number): """Validate the given 1-based page number.""" try: if isinstance(number, float) and not number.is_integer(): raise ValueError number = int(number) except (TypeError, ValueError): raise PageNotAnInteger(self.error_messages["invalid_page"]) if number < 1: raise EmptyPage(self.error_messages["min_page"]) if number > self.num_pages: raise EmptyPage(self.error_messages["no_results"]) return number def get_page(self, number): """ Return a valid page, even if the page argument isn't a number or isn't in range. """ try: number = self.validate_number(number) except PageNotAnInteger: number = 1 except EmptyPage: number = self.num_pages return self.page(number) def page(self, number): """Return a Page object for the given 1-based page number.""" number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page if top + self.orphans >= self.count: top = self.count return self._get_page(self.object_list[bottom:top], number, self) def _get_page(self, *args, **kwargs): """ Return an instance of a single page. This hook can be used by subclasses to use an alternative to the standard :cls:`Page` object. """ return Page(*args, **kwargs) @cached_property def count(self): """Return the total number of objects, across all pages.""" c = getattr(self.object_list, "count", None) if callable(c) and not inspect.isbuiltin(c) and method_has_no_args(c): return c() return len(self.object_list) @cached_property def num_pages(self): """Return the total number of pages.""" if self.count == 0 and not self.allow_empty_first_page: return 0 hits = max(1, self.count - self.orphans) return ceil(hits / self.per_page) @property def page_range(self): """ Return a 1-based range of pages for iterating through within a template for loop. """ return range(1, self.num_pages + 1) def _check_object_list_is_ordered(self): """ Warn if self.object_list is unordered (typically a QuerySet). """ ordered = getattr(self.object_list, "ordered", None) if ordered is not None and not ordered: obj_list_repr = ( "{} {}".format( self.object_list.model, self.object_list.__class__.__name__ ) if hasattr(self.object_list, "model") else "{!r}".format(self.object_list) ) warnings.warn( "Pagination may yield inconsistent results with an unordered " "object_list: {}.".format(obj_list_repr), UnorderedObjectListWarning, stacklevel=3, ) def get_elided_page_range(self, number=1, *, on_each_side=3, on_ends=2): """ Return a 1-based range of pages with some values elided. If the page range is larger than a given size, the whole range is not provided and a compact form is returned instead, e.g. for a paginator with 50 pages, if page 43 were the current page, the output, with the default arguments, would be: 1, 2, …, 40, 41, 42, 43, 44, 45, 46, …, 49, 50. """ number = self.validate_number(number) if self.num_pages <= (on_each_side + on_ends) * 2: yield from self.page_range return if number > (1 + on_each_side + on_ends) + 1: yield from range(1, on_ends + 1) yield self.ELLIPSIS yield from range(number - on_each_side, number + 1) else: yield from range(1, number + 1) if number < (self.num_pages - on_each_side - on_ends) - 1: yield from range(number + 1, number + on_each_side + 1) yield self.ELLIPSIS yield from range(self.num_pages - on_ends + 1, self.num_pages + 1) else: yield from range(number + 1, self.num_pages + 1) class Page(collections.abc.Sequence): def __init__(self, object_list, number, paginator): self.object_list = object_list self.number = number self.paginator = paginator def __repr__(self): return "<Page %s of %s>" % (self.number, self.paginator.num_pages) def __len__(self): return len(self.object_list) def __getitem__(self, index): if not isinstance(index, (int, slice)): raise TypeError( "Page indices must be integers or slices, not %s." % type(index).__name__ ) # The object_list is converted to a list so that if it was a QuerySet # it won't be a database hit per __getitem__. if not isinstance(self.object_list, list): self.object_list = list(self.object_list) return self.object_list[index] def has_next(self): return self.number < self.paginator.num_pages def has_previous(self): return self.number > 1 def has_other_pages(self): return self.has_previous() or self.has_next() def next_page_number(self): return self.paginator.validate_number(self.number + 1) def previous_page_number(self): return self.paginator.validate_number(self.number - 1) def start_index(self): """ Return the 1-based index of the first object on this page, relative to total objects in the paginator. """ # Special case, return zero if no items. if self.paginator.count == 0: return 0 return (self.paginator.per_page * (self.number - 1)) + 1 def end_index(self): """ Return the 1-based index of the last object on this page, relative to total objects found (hits). """ # Special case for the last page because there can be orphans. if self.number == self.paginator.num_pages: return self.paginator.count return self.number * self.paginator.per_page
eb65e3d0d84b7d847f57f507b8b11d74d2a27fe3b9e511e06616a7e43d534b1a
import datetime import io import json import mimetypes import os import re import sys import time import warnings from email.header import Header from http.client import responses from urllib.parse import urlparse from asgiref.sync import async_to_sync, sync_to_async from django.conf import settings from django.core import signals, signing from django.core.exceptions import DisallowedRedirect from django.core.serializers.json import DjangoJSONEncoder from django.http.cookie import SimpleCookie from django.utils import timezone from django.utils.datastructures import CaseInsensitiveMapping from django.utils.encoding import iri_to_uri from django.utils.http import content_disposition_header, http_date from django.utils.regex_helper import _lazy_re_compile _charset_from_content_type_re = _lazy_re_compile( r";\s*charset=(?P<charset>[^\s;]+)", re.I ) class ResponseHeaders(CaseInsensitiveMapping): def __init__(self, data): """ Populate the initial data using __setitem__ to ensure values are correctly encoded. """ self._store = {} if data: for header, value in self._unpack_items(data): self[header] = value def _convert_to_charset(self, value, charset, mime_encode=False): """ Convert headers key/value to ascii/latin-1 native strings. `charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and `value` can't be represented in the given charset, apply MIME-encoding. """ try: if isinstance(value, str): # Ensure string is valid in given charset value.encode(charset) elif isinstance(value, bytes): # Convert bytestring using given charset value = value.decode(charset) else: value = str(value) # Ensure string is valid in given charset. value.encode(charset) if "\n" in value or "\r" in value: raise BadHeaderError( f"Header values can't contain newlines (got {value!r})" ) except UnicodeError as e: # Encoding to a string of the specified charset failed, but we # don't know what type that value was, or if it contains newlines, # which we may need to check for before sending it to be # encoded for multiple character sets. if (isinstance(value, bytes) and (b"\n" in value or b"\r" in value)) or ( isinstance(value, str) and ("\n" in value or "\r" in value) ): raise BadHeaderError( f"Header values can't contain newlines (got {value!r})" ) from e if mime_encode: value = Header(value, "utf-8", maxlinelen=sys.maxsize).encode() else: e.reason += ", HTTP response headers must be in %s format" % charset raise return value def __delitem__(self, key): self.pop(key) def __setitem__(self, key, value): key = self._convert_to_charset(key, "ascii") value = self._convert_to_charset(value, "latin-1", mime_encode=True) self._store[key.lower()] = (key, value) def pop(self, key, default=None): return self._store.pop(key.lower(), default) def setdefault(self, key, value): if key not in self: self[key] = value class BadHeaderError(ValueError): pass class HttpResponseBase: """ An HTTP response base class with dictionary-accessed headers. This class doesn't handle content. It should not be used directly. Use the HttpResponse and StreamingHttpResponse subclasses instead. """ status_code = 200 def __init__( self, content_type=None, status=None, reason=None, charset=None, headers=None ): self.headers = ResponseHeaders(headers) self._charset = charset if "Content-Type" not in self.headers: if content_type is None: content_type = f"text/html; charset={self.charset}" self.headers["Content-Type"] = content_type elif content_type: raise ValueError( "'headers' must not contain 'Content-Type' when the " "'content_type' parameter is provided." ) self._resource_closers = [] # This parameter is set by the handler. It's necessary to preserve the # historical behavior of request_finished. self._handler_class = None self.cookies = SimpleCookie() self.closed = False if status is not None: try: self.status_code = int(status) except (ValueError, TypeError): raise TypeError("HTTP status code must be an integer.") if not 100 <= self.status_code <= 599: raise ValueError("HTTP status code must be an integer from 100 to 599.") self._reason_phrase = reason @property def reason_phrase(self): if self._reason_phrase is not None: return self._reason_phrase # Leave self._reason_phrase unset in order to use the default # reason phrase for status code. return responses.get(self.status_code, "Unknown Status Code") @reason_phrase.setter def reason_phrase(self, value): self._reason_phrase = value @property def charset(self): if self._charset is not None: return self._charset # The Content-Type header may not yet be set, because the charset is # being inserted *into* it. if content_type := self.headers.get("Content-Type"): if matched := _charset_from_content_type_re.search(content_type): # Extract the charset and strip its double quotes. # Note that having parsed it from the Content-Type, we don't # store it back into the _charset for later intentionally, to # allow for the Content-Type to be switched again later. return matched["charset"].replace('"', "") return settings.DEFAULT_CHARSET @charset.setter def charset(self, value): self._charset = value def serialize_headers(self): """HTTP headers as a bytestring.""" return b"\r\n".join( [ key.encode("ascii") + b": " + value.encode("latin-1") for key, value in self.headers.items() ] ) __bytes__ = serialize_headers @property def _content_type_for_repr(self): return ( ', "%s"' % self.headers["Content-Type"] if "Content-Type" in self.headers else "" ) def __setitem__(self, header, value): self.headers[header] = value def __delitem__(self, header): del self.headers[header] def __getitem__(self, header): return self.headers[header] def has_header(self, header): """Case-insensitive check for a header.""" return header in self.headers __contains__ = has_header def items(self): return self.headers.items() def get(self, header, alternate=None): return self.headers.get(header, alternate) def set_cookie( self, key, value="", max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite=None, ): """ Set a cookie. ``expires`` can be: - a string in the correct format, - a naive ``datetime.datetime`` object in UTC, - an aware ``datetime.datetime`` object in any time zone. If it is a ``datetime.datetime`` object then calculate ``max_age``. ``max_age`` can be: - int/float specifying seconds, - ``datetime.timedelta`` object. """ self.cookies[key] = value if expires is not None: if isinstance(expires, datetime.datetime): if timezone.is_naive(expires): expires = timezone.make_aware(expires, datetime.timezone.utc) delta = expires - datetime.datetime.now(tz=datetime.timezone.utc) # Add one second so the date matches exactly (a fraction of # time gets lost between converting to a timedelta and # then the date string). delta += datetime.timedelta(seconds=1) # Just set max_age - the max_age logic will set expires. expires = None if max_age is not None: raise ValueError("'expires' and 'max_age' can't be used together.") max_age = max(0, delta.days * 86400 + delta.seconds) else: self.cookies[key]["expires"] = expires else: self.cookies[key]["expires"] = "" if max_age is not None: if isinstance(max_age, datetime.timedelta): max_age = max_age.total_seconds() self.cookies[key]["max-age"] = int(max_age) # IE requires expires, so set it if hasn't been already. if not expires: self.cookies[key]["expires"] = http_date(time.time() + max_age) if path is not None: self.cookies[key]["path"] = path if domain is not None: self.cookies[key]["domain"] = domain if secure: self.cookies[key]["secure"] = True if httponly: self.cookies[key]["httponly"] = True if samesite: if samesite.lower() not in ("lax", "none", "strict"): raise ValueError('samesite must be "lax", "none", or "strict".') self.cookies[key]["samesite"] = samesite def setdefault(self, key, value): """Set a header unless it has already been set.""" self.headers.setdefault(key, value) def set_signed_cookie(self, key, value, salt="", **kwargs): value = signing.get_cookie_signer(salt=key + salt).sign(value) return self.set_cookie(key, value, **kwargs) def delete_cookie(self, key, path="/", domain=None, samesite=None): # Browsers can ignore the Set-Cookie header if the cookie doesn't use # the secure flag and: # - the cookie name starts with "__Host-" or "__Secure-", or # - the samesite is "none". secure = key.startswith(("__Secure-", "__Host-")) or ( samesite and samesite.lower() == "none" ) self.set_cookie( key, max_age=0, path=path, domain=domain, secure=secure, expires="Thu, 01 Jan 1970 00:00:00 GMT", samesite=samesite, ) # Common methods used by subclasses def make_bytes(self, value): """Turn a value into a bytestring encoded in the output charset.""" # Per PEP 3333, this response body must be bytes. To avoid returning # an instance of a subclass, this function returns `bytes(value)`. # This doesn't make a copy when `value` already contains bytes. # Handle string types -- we can't rely on force_bytes here because: # - Python attempts str conversion first # - when self._charset != 'utf-8' it re-encodes the content if isinstance(value, (bytes, memoryview)): return bytes(value) if isinstance(value, str): return bytes(value.encode(self.charset)) # Handle non-string types. return str(value).encode(self.charset) # These methods partially implement the file-like object interface. # See https://docs.python.org/library/io.html#io.IOBase # The WSGI server must call this method upon completion of the request. # See http://blog.dscpl.com.au/2012/10/obligations-for-calling-close-on.html def close(self): for closer in self._resource_closers: try: closer() except Exception: pass # Free resources that were still referenced. self._resource_closers.clear() self.closed = True signals.request_finished.send(sender=self._handler_class) def write(self, content): raise OSError("This %s instance is not writable" % self.__class__.__name__) def flush(self): pass def tell(self): raise OSError( "This %s instance cannot tell its position" % self.__class__.__name__ ) # These methods partially implement a stream-like object interface. # See https://docs.python.org/library/io.html#io.IOBase def readable(self): return False def seekable(self): return False def writable(self): return False def writelines(self, lines): raise OSError("This %s instance is not writable" % self.__class__.__name__) class HttpResponse(HttpResponseBase): """ An HTTP response class with a string as content. This content can be read, appended to, or replaced. """ streaming = False def __init__(self, content=b"", *args, **kwargs): super().__init__(*args, **kwargs) # Content is a bytestring. See the `content` property methods. self.content = content def __repr__(self): return "<%(cls)s status_code=%(status_code)d%(content_type)s>" % { "cls": self.__class__.__name__, "status_code": self.status_code, "content_type": self._content_type_for_repr, } def serialize(self): """Full HTTP message, including headers, as a bytestring.""" return self.serialize_headers() + b"\r\n\r\n" + self.content __bytes__ = serialize @property def content(self): return b"".join(self._container) @content.setter def content(self, value): # Consume iterators upon assignment to allow repeated iteration. if hasattr(value, "__iter__") and not isinstance( value, (bytes, memoryview, str) ): content = b"".join(self.make_bytes(chunk) for chunk in value) if hasattr(value, "close"): try: value.close() except Exception: pass else: content = self.make_bytes(value) # Create a list of properly encoded bytestrings to support write(). self._container = [content] def __iter__(self): return iter(self._container) def write(self, content): self._container.append(self.make_bytes(content)) def tell(self): return len(self.content) def getvalue(self): return self.content def writable(self): return True def writelines(self, lines): for line in lines: self.write(line) class StreamingHttpResponse(HttpResponseBase): """ A streaming HTTP response class with an iterator as content. This should only be iterated once, when the response is streamed to the client. However, it can be appended to or replaced with a new iterator that wraps the original content (or yields entirely new content). """ streaming = True def __init__(self, streaming_content=(), *args, **kwargs): super().__init__(*args, **kwargs) # `streaming_content` should be an iterable of bytestrings. # See the `streaming_content` property methods. self.streaming_content = streaming_content def __repr__(self): return "<%(cls)s status_code=%(status_code)d%(content_type)s>" % { "cls": self.__class__.__qualname__, "status_code": self.status_code, "content_type": self._content_type_for_repr, } @property def content(self): raise AttributeError( "This %s instance has no `content` attribute. Use " "`streaming_content` instead." % self.__class__.__name__ ) @property def streaming_content(self): if self.is_async: # pull to lexical scope to capture fixed reference in case # streaming_content is set again later. _iterator = self._iterator async def awrapper(): async for part in _iterator: yield self.make_bytes(part) return awrapper() else: return map(self.make_bytes, self._iterator) @streaming_content.setter def streaming_content(self, value): self._set_streaming_content(value) def _set_streaming_content(self, value): # Ensure we can never iterate on "value" more than once. try: self._iterator = iter(value) self.is_async = False except TypeError: self._iterator = aiter(value) self.is_async = True if hasattr(value, "close"): self._resource_closers.append(value.close) def __iter__(self): try: return iter(self.streaming_content) except TypeError: warnings.warn( "StreamingHttpResponse must consume asynchronous iterators in order to " "serve them synchronously. Use a synchronous iterator instead.", Warning, ) # async iterator. Consume in async_to_sync and map back. async def to_list(_iterator): as_list = [] async for chunk in _iterator: as_list.append(chunk) return as_list return map(self.make_bytes, iter(async_to_sync(to_list)(self._iterator))) async def __aiter__(self): try: async for part in self.streaming_content: yield part except TypeError: warnings.warn( "StreamingHttpResponse must consume synchronous iterators in order to " "serve them asynchronously. Use an asynchronous iterator instead.", Warning, ) # sync iterator. Consume via sync_to_async and yield via async # generator. for part in await sync_to_async(list)(self.streaming_content): yield part def getvalue(self): return b"".join(self.streaming_content) class FileResponse(StreamingHttpResponse): """ A streaming HTTP response class optimized for files. """ block_size = 4096 def __init__(self, *args, as_attachment=False, filename="", **kwargs): self.as_attachment = as_attachment self.filename = filename self._no_explicit_content_type = ( "content_type" not in kwargs or kwargs["content_type"] is None ) super().__init__(*args, **kwargs) def _set_streaming_content(self, value): if not hasattr(value, "read"): self.file_to_stream = None return super()._set_streaming_content(value) self.file_to_stream = filelike = value if hasattr(filelike, "close"): self._resource_closers.append(filelike.close) value = iter(lambda: filelike.read(self.block_size), b"") self.set_headers(filelike) super()._set_streaming_content(value) def set_headers(self, filelike): """ Set some common response headers (Content-Length, Content-Type, and Content-Disposition) based on the `filelike` response content. """ filename = getattr(filelike, "name", "") filename = filename if isinstance(filename, str) else "" seekable = hasattr(filelike, "seek") and ( not hasattr(filelike, "seekable") or filelike.seekable() ) if hasattr(filelike, "tell"): if seekable: initial_position = filelike.tell() filelike.seek(0, io.SEEK_END) self.headers["Content-Length"] = filelike.tell() - initial_position filelike.seek(initial_position) elif hasattr(filelike, "getbuffer"): self.headers["Content-Length"] = ( filelike.getbuffer().nbytes - filelike.tell() ) elif os.path.exists(filename): self.headers["Content-Length"] = ( os.path.getsize(filename) - filelike.tell() ) elif seekable: self.headers["Content-Length"] = sum( iter(lambda: len(filelike.read(self.block_size)), 0) ) filelike.seek(-int(self.headers["Content-Length"]), io.SEEK_END) filename = os.path.basename(self.filename or filename) if self._no_explicit_content_type: if filename: content_type, encoding = mimetypes.guess_type(filename) # Encoding isn't set to prevent browsers from automatically # uncompressing files. content_type = { "br": "application/x-brotli", "bzip2": "application/x-bzip", "compress": "application/x-compress", "gzip": "application/gzip", "xz": "application/x-xz", }.get(encoding, content_type) self.headers["Content-Type"] = ( content_type or "application/octet-stream" ) else: self.headers["Content-Type"] = "application/octet-stream" if content_disposition := content_disposition_header( self.as_attachment, filename ): self.headers["Content-Disposition"] = content_disposition class HttpResponseRedirectBase(HttpResponse): allowed_schemes = ["http", "https", "ftp"] def __init__(self, redirect_to, *args, **kwargs): super().__init__(*args, **kwargs) self["Location"] = iri_to_uri(redirect_to) parsed = urlparse(str(redirect_to)) if parsed.scheme and parsed.scheme not in self.allowed_schemes: raise DisallowedRedirect( "Unsafe redirect to URL with protocol '%s'" % parsed.scheme ) url = property(lambda self: self["Location"]) def __repr__(self): return ( '<%(cls)s status_code=%(status_code)d%(content_type)s, url="%(url)s">' % { "cls": self.__class__.__name__, "status_code": self.status_code, "content_type": self._content_type_for_repr, "url": self.url, } ) class HttpResponseRedirect(HttpResponseRedirectBase): status_code = 302 class HttpResponsePermanentRedirect(HttpResponseRedirectBase): status_code = 301 class HttpResponseNotModified(HttpResponse): status_code = 304 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self["content-type"] @HttpResponse.content.setter def content(self, value): if value: raise AttributeError( "You cannot set content to a 304 (Not Modified) response" ) self._container = [] class HttpResponseBadRequest(HttpResponse): status_code = 400 class HttpResponseNotFound(HttpResponse): status_code = 404 class HttpResponseForbidden(HttpResponse): status_code = 403 class HttpResponseNotAllowed(HttpResponse): status_code = 405 def __init__(self, permitted_methods, *args, **kwargs): super().__init__(*args, **kwargs) self["Allow"] = ", ".join(permitted_methods) def __repr__(self): return "<%(cls)s [%(methods)s] status_code=%(status_code)d%(content_type)s>" % { "cls": self.__class__.__name__, "status_code": self.status_code, "content_type": self._content_type_for_repr, "methods": self["Allow"], } class HttpResponseGone(HttpResponse): status_code = 410 class HttpResponseServerError(HttpResponse): status_code = 500 class Http404(Exception): pass class JsonResponse(HttpResponse): """ An HTTP response class that consumes data to be serialized to JSON. :param data: Data to be dumped into json. By default only ``dict`` objects are allowed to be passed due to a security flaw before ECMAScript 5. See the ``safe`` parameter for more information. :param encoder: Should be a json encoder class. Defaults to ``django.core.serializers.json.DjangoJSONEncoder``. :param safe: Controls if only ``dict`` objects may be serialized. Defaults to ``True``. :param json_dumps_params: A dictionary of kwargs passed to json.dumps(). """ def __init__( self, data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs, ): if safe and not isinstance(data, dict): raise TypeError( "In order to allow non-dict objects to be serialized set the " "safe parameter to False." ) if json_dumps_params is None: json_dumps_params = {} kwargs.setdefault("content_type", "application/json") data = json.dumps(data, cls=encoder, **json_dumps_params) super().__init__(content=data, **kwargs)
f644942b1784f9ed0fe19005282f4d46cbd2df5cf272db48af0b891782ca08e1
import codecs import copy from io import BytesIO from itertools import chain from urllib.parse import parse_qsl, quote, urlencode, urljoin, urlsplit from django.conf import settings from django.core import signing from django.core.exceptions import ( DisallowedHost, ImproperlyConfigured, RequestDataTooBig, TooManyFieldsSent, ) from django.core.files import uploadhandler from django.http.multipartparser import ( MultiPartParser, MultiPartParserError, TooManyFilesSent, ) from django.utils.datastructures import ( CaseInsensitiveMapping, ImmutableList, MultiValueDict, ) from django.utils.encoding import escape_uri_path, iri_to_uri from django.utils.functional import cached_property from django.utils.http import is_same_domain, parse_header_parameters from django.utils.regex_helper import _lazy_re_compile RAISE_ERROR = object() host_validation_re = _lazy_re_compile( r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9\.:]+\])(:[0-9]+)?$" ) class UnreadablePostError(OSError): pass class RawPostDataException(Exception): """ You cannot access raw_post_data from a request that has multipart/* POST data if it has been accessed via POST, FILES, etc.. """ pass class HttpRequest: """A basic HTTP request.""" # The encoding used in GET/POST dicts. None means use default setting. _encoding = None _upload_handlers = [] def __init__(self): # WARNING: The `WSGIRequest` subclass doesn't call `super`. # Any variable assignment made here should also happen in # `WSGIRequest.__init__()`. self.GET = QueryDict(mutable=True) self.POST = QueryDict(mutable=True) self.COOKIES = {} self.META = {} self.FILES = MultiValueDict() self.path = "" self.path_info = "" self.method = None self.resolver_match = None self.content_type = None self.content_params = None def __repr__(self): if self.method is None or not self.get_full_path(): return "<%s>" % self.__class__.__name__ return "<%s: %s %r>" % ( self.__class__.__name__, self.method, self.get_full_path(), ) @cached_property def headers(self): return HttpHeaders(self.META) @cached_property def accepted_types(self): """Return a list of MediaType instances.""" return parse_accept_header(self.headers.get("Accept", "*/*")) def accepts(self, media_type): return any( accepted_type.match(media_type) for accepted_type in self.accepted_types ) def _set_content_type_params(self, meta): """Set content_type, content_params, and encoding.""" self.content_type, self.content_params = parse_header_parameters( meta.get("CONTENT_TYPE", "") ) if "charset" in self.content_params: try: codecs.lookup(self.content_params["charset"]) except LookupError: pass else: self.encoding = self.content_params["charset"] def _get_raw_host(self): """ Return the HTTP host using the environment or request headers. Skip allowed hosts protection, so may return an insecure host. """ # We try three options, in order of decreasing preference. if settings.USE_X_FORWARDED_HOST and ("HTTP_X_FORWARDED_HOST" in self.META): host = self.META["HTTP_X_FORWARDED_HOST"] elif "HTTP_HOST" in self.META: host = self.META["HTTP_HOST"] else: # Reconstruct the host using the algorithm from PEP 333. host = self.META["SERVER_NAME"] server_port = self.get_port() if server_port != ("443" if self.is_secure() else "80"): host = "%s:%s" % (host, server_port) return host def get_host(self): """Return the HTTP host using the environment or request headers.""" host = self._get_raw_host() # Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True. allowed_hosts = settings.ALLOWED_HOSTS if settings.DEBUG and not allowed_hosts: allowed_hosts = [".localhost", "127.0.0.1", "[::1]"] domain, port = split_domain_port(host) if domain and validate_host(domain, allowed_hosts): return host else: msg = "Invalid HTTP_HOST header: %r." % host if domain: msg += " You may need to add %r to ALLOWED_HOSTS." % domain else: msg += ( " The domain name provided is not valid according to RFC 1034/1035." ) raise DisallowedHost(msg) def get_port(self): """Return the port number for the request as a string.""" if settings.USE_X_FORWARDED_PORT and "HTTP_X_FORWARDED_PORT" in self.META: port = self.META["HTTP_X_FORWARDED_PORT"] else: port = self.META["SERVER_PORT"] return str(port) def get_full_path(self, force_append_slash=False): return self._get_full_path(self.path, force_append_slash) def get_full_path_info(self, force_append_slash=False): return self._get_full_path(self.path_info, force_append_slash) def _get_full_path(self, path, force_append_slash): # RFC 3986 requires query string arguments to be in the ASCII range. # Rather than crash if this doesn't happen, we encode defensively. return "%s%s%s" % ( escape_uri_path(path), "/" if force_append_slash and not path.endswith("/") else "", ("?" + iri_to_uri(self.META.get("QUERY_STRING", ""))) if self.META.get("QUERY_STRING", "") else "", ) def get_signed_cookie(self, key, default=RAISE_ERROR, salt="", max_age=None): """ Attempt to return a signed cookie. If the signature fails or the cookie has expired, raise an exception, unless the `default` argument is provided, in which case return that value. """ try: cookie_value = self.COOKIES[key] except KeyError: if default is not RAISE_ERROR: return default else: raise try: value = signing.get_cookie_signer(salt=key + salt).unsign( cookie_value, max_age=max_age ) except signing.BadSignature: if default is not RAISE_ERROR: return default else: raise return value def build_absolute_uri(self, location=None): """ Build an absolute URI from the location and the variables available in this request. If no ``location`` is specified, build the absolute URI using request.get_full_path(). If the location is absolute, convert it to an RFC 3987 compliant URI and return it. If location is relative or is scheme-relative (i.e., ``//example.com/``), urljoin() it to a base URL constructed from the request variables. """ if location is None: # Make it an absolute url (but schemeless and domainless) for the # edge case that the path starts with '//'. location = "//%s" % self.get_full_path() else: # Coerce lazy locations. location = str(location) bits = urlsplit(location) if not (bits.scheme and bits.netloc): # Handle the simple, most common case. If the location is absolute # and a scheme or host (netloc) isn't provided, skip an expensive # urljoin() as long as no path segments are '.' or '..'. if ( bits.path.startswith("/") and not bits.scheme and not bits.netloc and "/./" not in bits.path and "/../" not in bits.path ): # If location starts with '//' but has no netloc, reuse the # schema and netloc from the current request. Strip the double # slashes and continue as if it wasn't specified. location = self._current_scheme_host + location.removeprefix("//") else: # Join the constructed URL with the provided location, which # allows the provided location to apply query strings to the # base path. location = urljoin(self._current_scheme_host + self.path, location) return iri_to_uri(location) @cached_property def _current_scheme_host(self): return "{}://{}".format(self.scheme, self.get_host()) def _get_scheme(self): """ Hook for subclasses like WSGIRequest to implement. Return 'http' by default. """ return "http" @property def scheme(self): if settings.SECURE_PROXY_SSL_HEADER: try: header, secure_value = settings.SECURE_PROXY_SSL_HEADER except ValueError: raise ImproperlyConfigured( "The SECURE_PROXY_SSL_HEADER setting must be a tuple containing " "two values." ) header_value = self.META.get(header) if header_value is not None: header_value, *_ = header_value.split(",", 1) return "https" if header_value.strip() == secure_value else "http" return self._get_scheme() def is_secure(self): return self.scheme == "https" @property def encoding(self): return self._encoding @encoding.setter def encoding(self, val): """ Set the encoding used for GET/POST accesses. If the GET or POST dictionary has already been created, remove and recreate it on the next access (so that it is decoded correctly). """ self._encoding = val if hasattr(self, "GET"): del self.GET if hasattr(self, "_post"): del self._post def _initialize_handlers(self): self._upload_handlers = [ uploadhandler.load_handler(handler, self) for handler in settings.FILE_UPLOAD_HANDLERS ] @property def upload_handlers(self): if not self._upload_handlers: # If there are no upload handlers defined, initialize them from settings. self._initialize_handlers() return self._upload_handlers @upload_handlers.setter def upload_handlers(self, upload_handlers): if hasattr(self, "_files"): raise AttributeError( "You cannot set the upload handlers after the upload has been " "processed." ) self._upload_handlers = upload_handlers def parse_file_upload(self, META, post_data): """Return a tuple of (POST QueryDict, FILES MultiValueDict).""" self.upload_handlers = ImmutableList( self.upload_handlers, warning=( "You cannot alter upload handlers after the upload has been " "processed." ), ) parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding) return parser.parse() @property def body(self): if not hasattr(self, "_body"): if self._read_started: raise RawPostDataException( "You cannot access body after reading from request's data stream" ) # Limit the maximum request data size that will be handled in-memory. if ( settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and int(self.META.get("CONTENT_LENGTH") or 0) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE ): raise RequestDataTooBig( "Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE." ) try: self._body = self.read() except OSError as e: raise UnreadablePostError(*e.args) from e finally: self._stream.close() self._stream = BytesIO(self._body) return self._body def _mark_post_parse_error(self): self._post = QueryDict() self._files = MultiValueDict() def _load_post_and_files(self): """Populate self._post and self._files if the content-type is a form type""" if self.method != "POST": self._post, self._files = ( QueryDict(encoding=self._encoding), MultiValueDict(), ) return if self._read_started and not hasattr(self, "_body"): self._mark_post_parse_error() return if self.content_type == "multipart/form-data": if hasattr(self, "_body"): # Use already read data data = BytesIO(self._body) else: data = self try: self._post, self._files = self.parse_file_upload(self.META, data) except (MultiPartParserError, TooManyFilesSent): # An error occurred while parsing POST data. Since when # formatting the error the request handler might access # self.POST, set self._post and self._file to prevent # attempts to parse POST data again. self._mark_post_parse_error() raise elif self.content_type == "application/x-www-form-urlencoded": self._post, self._files = ( QueryDict(self.body, encoding=self._encoding), MultiValueDict(), ) else: self._post, self._files = ( QueryDict(encoding=self._encoding), MultiValueDict(), ) def close(self): if hasattr(self, "_files"): for f in chain.from_iterable(list_[1] for list_ in self._files.lists()): f.close() # File-like and iterator interface. # # Expects self._stream to be set to an appropriate source of bytes by # a corresponding request subclass (e.g. WSGIRequest). # Also when request data has already been read by request.POST or # request.body, self._stream points to a BytesIO instance # containing that data. def read(self, *args, **kwargs): self._read_started = True try: return self._stream.read(*args, **kwargs) except OSError as e: raise UnreadablePostError(*e.args) from e def readline(self, *args, **kwargs): self._read_started = True try: return self._stream.readline(*args, **kwargs) except OSError as e: raise UnreadablePostError(*e.args) from e def __iter__(self): return iter(self.readline, b"") def readlines(self): return list(self) class HttpHeaders(CaseInsensitiveMapping): HTTP_PREFIX = "HTTP_" # PEP 333 gives two headers which aren't prepended with HTTP_. UNPREFIXED_HEADERS = {"CONTENT_TYPE", "CONTENT_LENGTH"} def __init__(self, environ): headers = {} for header, value in environ.items(): name = self.parse_header_name(header) if name: headers[name] = value super().__init__(headers) def __getitem__(self, key): """Allow header lookup using underscores in place of hyphens.""" return super().__getitem__(key.replace("_", "-")) @classmethod def parse_header_name(cls, header): if header.startswith(cls.HTTP_PREFIX): header = header.removeprefix(cls.HTTP_PREFIX) elif header not in cls.UNPREFIXED_HEADERS: return None return header.replace("_", "-").title() @classmethod def to_wsgi_name(cls, header): header = header.replace("-", "_").upper() if header in cls.UNPREFIXED_HEADERS: return header return f"{cls.HTTP_PREFIX}{header}" @classmethod def to_asgi_name(cls, header): return header.replace("-", "_").upper() @classmethod def to_wsgi_names(cls, headers): return { cls.to_wsgi_name(header_name): value for header_name, value in headers.items() } @classmethod def to_asgi_names(cls, headers): return { cls.to_asgi_name(header_name): value for header_name, value in headers.items() } class QueryDict(MultiValueDict): """ A specialized MultiValueDict which represents a query string. A QueryDict can be used to represent GET or POST data. It subclasses MultiValueDict since keys in such data can be repeated, for instance in the data from a form with a <select multiple> field. By default QueryDicts are immutable, though the copy() method will always return a mutable copy. Both keys and values set on this class are converted from the given encoding (DEFAULT_CHARSET by default) to str. """ # These are both reset in __init__, but is specified here at the class # level so that unpickling will have valid values _mutable = True _encoding = None def __init__(self, query_string=None, mutable=False, encoding=None): super().__init__() self.encoding = encoding or settings.DEFAULT_CHARSET query_string = query_string or "" parse_qsl_kwargs = { "keep_blank_values": True, "encoding": self.encoding, "max_num_fields": settings.DATA_UPLOAD_MAX_NUMBER_FIELDS, } if isinstance(query_string, bytes): # query_string normally contains URL-encoded data, a subset of ASCII. try: query_string = query_string.decode(self.encoding) except UnicodeDecodeError: # ... but some user agents are misbehaving :-( query_string = query_string.decode("iso-8859-1") try: for key, value in parse_qsl(query_string, **parse_qsl_kwargs): self.appendlist(key, value) except ValueError as e: # ValueError can also be raised if the strict_parsing argument to # parse_qsl() is True. As that is not used by Django, assume that # the exception was raised by exceeding the value of max_num_fields # instead of fragile checks of exception message strings. raise TooManyFieldsSent( "The number of GET/POST parameters exceeded " "settings.DATA_UPLOAD_MAX_NUMBER_FIELDS." ) from e self._mutable = mutable @classmethod def fromkeys(cls, iterable, value="", mutable=False, encoding=None): """ Return a new QueryDict with keys (may be repeated) from an iterable and values from value. """ q = cls("", mutable=True, encoding=encoding) for key in iterable: q.appendlist(key, value) if not mutable: q._mutable = False return q @property def encoding(self): if self._encoding is None: self._encoding = settings.DEFAULT_CHARSET return self._encoding @encoding.setter def encoding(self, value): self._encoding = value def _assert_mutable(self): if not self._mutable: raise AttributeError("This QueryDict instance is immutable") def __setitem__(self, key, value): self._assert_mutable() key = bytes_to_text(key, self.encoding) value = bytes_to_text(value, self.encoding) super().__setitem__(key, value) def __delitem__(self, key): self._assert_mutable() super().__delitem__(key) def __copy__(self): result = self.__class__("", mutable=True, encoding=self.encoding) for key, value in self.lists(): result.setlist(key, value) return result def __deepcopy__(self, memo): result = self.__class__("", mutable=True, encoding=self.encoding) memo[id(self)] = result for key, value in self.lists(): result.setlist(copy.deepcopy(key, memo), copy.deepcopy(value, memo)) return result def setlist(self, key, list_): self._assert_mutable() key = bytes_to_text(key, self.encoding) list_ = [bytes_to_text(elt, self.encoding) for elt in list_] super().setlist(key, list_) def setlistdefault(self, key, default_list=None): self._assert_mutable() return super().setlistdefault(key, default_list) def appendlist(self, key, value): self._assert_mutable() key = bytes_to_text(key, self.encoding) value = bytes_to_text(value, self.encoding) super().appendlist(key, value) def pop(self, key, *args): self._assert_mutable() return super().pop(key, *args) def popitem(self): self._assert_mutable() return super().popitem() def clear(self): self._assert_mutable() super().clear() def setdefault(self, key, default=None): self._assert_mutable() key = bytes_to_text(key, self.encoding) default = bytes_to_text(default, self.encoding) return super().setdefault(key, default) def copy(self): """Return a mutable copy of this object.""" return self.__deepcopy__({}) def urlencode(self, safe=None): """ Return an encoded string of all query string arguments. `safe` specifies characters which don't require quoting, for example:: >>> q = QueryDict(mutable=True) >>> q['next'] = '/a&b/' >>> q.urlencode() 'next=%2Fa%26b%2F' >>> q.urlencode(safe='/') 'next=/a%26b/' """ output = [] if safe: safe = safe.encode(self.encoding) def encode(k, v): return "%s=%s" % ((quote(k, safe), quote(v, safe))) else: def encode(k, v): return urlencode({k: v}) for k, list_ in self.lists(): output.extend( encode(k.encode(self.encoding), str(v).encode(self.encoding)) for v in list_ ) return "&".join(output) class MediaType: def __init__(self, media_type_raw_line): full_type, self.params = parse_header_parameters( media_type_raw_line if media_type_raw_line else "" ) self.main_type, _, self.sub_type = full_type.partition("/") def __str__(self): params_str = "".join("; %s=%s" % (k, v) for k, v in self.params.items()) return "%s%s%s" % ( self.main_type, ("/%s" % self.sub_type) if self.sub_type else "", params_str, ) def __repr__(self): return "<%s: %s>" % (self.__class__.__qualname__, self) @property def is_all_types(self): return self.main_type == "*" and self.sub_type == "*" def match(self, other): if self.is_all_types: return True other = MediaType(other) if self.main_type == other.main_type and self.sub_type in {"*", other.sub_type}: return True return False # It's neither necessary nor appropriate to use # django.utils.encoding.force_str() for parsing URLs and form inputs. Thus, # this slightly more restricted function, used by QueryDict. def bytes_to_text(s, encoding): """ Convert bytes objects to strings, using the given encoding. Illegally encoded input characters are replaced with Unicode "unknown" codepoint (\ufffd). Return any non-bytes objects without change. """ if isinstance(s, bytes): return str(s, encoding, "replace") else: return s def split_domain_port(host): """ Return a (domain, port) tuple from a given host. Returned domain is lowercased. If the host is invalid, the domain will be empty. """ host = host.lower() if not host_validation_re.match(host): return "", "" if host[-1] == "]": # It's an IPv6 address without a port. return host, "" bits = host.rsplit(":", 1) domain, port = bits if len(bits) == 2 else (bits[0], "") # Remove a trailing dot (if present) from the domain. domain = domain.removesuffix(".") return domain, port def validate_host(host, allowed_hosts): """ Validate the given host for this site. Check that the host looks valid and matches a host or host pattern in the given list of ``allowed_hosts``. Any pattern beginning with a period matches a domain and all its subdomains (e.g. ``.example.com`` matches ``example.com`` and any subdomain), ``*`` matches anything, and anything else must match exactly. Note: This function assumes that the given host is lowercased and has already had the port, if any, stripped off. Return ``True`` for a valid host, ``False`` otherwise. """ return any( pattern == "*" or is_same_domain(host, pattern) for pattern in allowed_hosts ) def parse_accept_header(header): return [MediaType(token) for token in header.split(",") if token.strip()]
e1c584596f3ca8fbf9ed2b7d5b09afd1a2b4bd5c43fbb69ebc539073ccf8a50b
from functools import wraps from asgiref.sync import iscoroutinefunction from django.middleware.cache import CacheMiddleware from django.utils.cache import add_never_cache_headers, patch_cache_control from django.utils.decorators import decorator_from_middleware_with_args def cache_page(timeout, *, cache=None, key_prefix=None): """ Decorator for views that tries getting the page from the cache and populates the cache if the page isn't in the cache yet. The cache is keyed by the URL and some data from the headers. Additionally there is the key prefix that is used to distinguish different cache areas in a multi-site setup. You could use the get_current_site().domain, for example, as that is unique across a Django project. Additionally, all headers from the response's Vary header will be taken into account on caching -- just like the middleware does. """ return decorator_from_middleware_with_args(CacheMiddleware)( page_timeout=timeout, cache_alias=cache, key_prefix=key_prefix, ) def _check_request(request, decorator_name): # Ensure argument looks like a request. if not hasattr(request, "META"): raise TypeError( f"{decorator_name} didn't receive an HttpRequest. If you are " "decorating a classmethod, be sure to use @method_decorator." ) def cache_control(**kwargs): def _cache_controller(viewfunc): if iscoroutinefunction(viewfunc): async def _view_wrapper(request, *args, **kw): _check_request(request, "cache_control") response = await viewfunc(request, *args, **kw) patch_cache_control(response, **kwargs) return response else: def _view_wrapper(request, *args, **kw): _check_request(request, "cache_control") response = viewfunc(request, *args, **kw) patch_cache_control(response, **kwargs) return response return wraps(viewfunc)(_view_wrapper) return _cache_controller def never_cache(view_func): """ Decorator that adds headers to a response so that it will never be cached. """ if iscoroutinefunction(view_func): async def _view_wrapper(request, *args, **kwargs): _check_request(request, "never_cache") response = await view_func(request, *args, **kwargs) add_never_cache_headers(response) return response else: def _view_wrapper(request, *args, **kwargs): _check_request(request, "never_cache") response = view_func(request, *args, **kwargs) add_never_cache_headers(response) return response return wraps(view_func)(_view_wrapper)
68a1084fde98eadcdb18716edeab05cc5738430feece136307af46a663faa97f
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = "j M Y" # '25 Oct 2006' TIME_FORMAT = "H:i" # '14:30' DATETIME_FORMAT = "j M Y, H:i" # '25 Oct 2006, 14:30' YEAR_MONTH_FORMAT = "F Y" # 'October 2006' MONTH_DAY_FORMAT = "j F" # '25 October' SHORT_DATE_FORMAT = "d/m/Y" # '25/10/2006' SHORT_DATETIME_FORMAT = "d/m/Y H:i" # '25/10/2006 14:30' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ "%d/%m/%Y", # '25/10/2006' "%d/%m/%y", # '25/10/06' "%d %b %Y", # '25 Oct 2006' "%d %b, %Y", # '25 Oct, 2006' "%d %B %Y", # '25 October 2006' "%d %B, %Y", # '25 October, 2006' ] DATETIME_INPUT_FORMATS = [ "%Y-%m-%d %H:%M:%S", # '2006-10-25 14:30:59' "%Y-%m-%d %H:%M:%S.%f", # '2006-10-25 14:30:59.000200' "%Y-%m-%d %H:%M", # '2006-10-25 14:30' "%d/%m/%Y %H:%M:%S", # '25/10/2006 14:30:59' "%d/%m/%Y %H:%M:%S.%f", # '25/10/2006 14:30:59.000200' "%d/%m/%Y %H:%M", # '25/10/2006 14:30' "%d/%m/%y %H:%M:%S", # '25/10/06 14:30:59' "%d/%m/%y %H:%M:%S.%f", # '25/10/06 14:30:59.000200' "%d/%m/%y %H:%M", # '25/10/06 14:30' ] DECIMAL_SEPARATOR = "." THOUSAND_SEPARATOR = "," NUMBER_GROUPING = 3
0186a68e6c63232149441f8b1493e13135665f20df52ca19a3d2ec1618fc0629
"""Translation helper functions.""" import functools import gettext as gettext_module import os import re import sys import warnings from asgiref.local import Local from django.apps import apps from django.conf import settings from django.conf.locale import LANG_INFO from django.core.exceptions import AppRegistryNotReady from django.core.signals import setting_changed from django.dispatch import receiver from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import SafeData, mark_safe from . import to_language, to_locale # Translations are cached in a dictionary for every language. # The active translations are stored by threadid to make them thread local. _translations = {} _active = Local() # The default translation is based on the settings file. _default = None # magic gettext number to separate context from message CONTEXT_SEPARATOR = "\x04" # Maximum number of characters that will be parsed from the Accept-Language # header to prevent possible denial of service or memory exhaustion attacks. # About 10x longer than the longest value shown on MDN’s Accept-Language page. ACCEPT_LANGUAGE_HEADER_MAX_LENGTH = 500 # Format of Accept-Language header values. From RFC 9110 Sections 12.4.2 and # 12.5.4, and RFC 5646 Section 2.1. accept_language_re = _lazy_re_compile( r""" # "en", "en-au", "x-y-z", "es-419", "*" ([A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*|\*) # Optional "q=1.00", "q=0.8" (?:\s*;\s*q=(0(?:\.[0-9]{,3})?|1(?:\.0{,3})?))? # Multiple accepts per header. (?:\s*,\s*|$) """, re.VERBOSE, ) language_code_re = _lazy_re_compile( r"^[a-z]{1,8}(?:-[a-z0-9]{1,8})*(?:@[a-z0-9]{1,20})?$", re.IGNORECASE ) language_code_prefix_re = _lazy_re_compile(r"^/(\w+([@-]\w+){0,2})(/|$)") @receiver(setting_changed) def reset_cache(*, setting, **kwargs): """ Reset global state when LANGUAGES setting has been changed, as some languages should no longer be accepted. """ if setting in ("LANGUAGES", "LANGUAGE_CODE"): check_for_language.cache_clear() get_languages.cache_clear() get_supported_language_variant.cache_clear() class TranslationCatalog: """ Simulate a dict for DjangoTranslation._catalog so as multiple catalogs with different plural equations are kept separate. """ def __init__(self, trans=None): self._catalogs = [trans._catalog.copy()] if trans else [{}] self._plurals = [trans.plural] if trans else [lambda n: int(n != 1)] def __getitem__(self, key): for cat in self._catalogs: try: return cat[key] except KeyError: pass raise KeyError(key) def __setitem__(self, key, value): self._catalogs[0][key] = value def __contains__(self, key): return any(key in cat for cat in self._catalogs) def items(self): for cat in self._catalogs: yield from cat.items() def keys(self): for cat in self._catalogs: yield from cat.keys() def update(self, trans): # Merge if plural function is the same, else prepend. for cat, plural in zip(self._catalogs, self._plurals): if trans.plural.__code__ == plural.__code__: cat.update(trans._catalog) break else: self._catalogs.insert(0, trans._catalog.copy()) self._plurals.insert(0, trans.plural) def get(self, key, default=None): missing = object() for cat in self._catalogs: result = cat.get(key, missing) if result is not missing: return result return default def plural(self, msgid, num): for cat, plural in zip(self._catalogs, self._plurals): tmsg = cat.get((msgid, plural(num))) if tmsg is not None: return tmsg raise KeyError class DjangoTranslation(gettext_module.GNUTranslations): """ Set up the GNUTranslations context with regard to output charset. This translation object will be constructed out of multiple GNUTranslations objects by merging their catalogs. It will construct an object for the requested language and add a fallback to the default language, if it's different from the requested language. """ domain = "django" def __init__(self, language, domain=None, localedirs=None): """Create a GNUTranslations() using many locale directories""" gettext_module.GNUTranslations.__init__(self) if domain is not None: self.domain = domain self.__language = language self.__to_language = to_language(language) self.__locale = to_locale(language) self._catalog = None # If a language doesn't have a catalog, use the Germanic default for # pluralization: anything except one is pluralized. self.plural = lambda n: int(n != 1) if self.domain == "django": if localedirs is not None: # A module-level cache is used for caching 'django' translations warnings.warn( "localedirs is ignored when domain is 'django'.", RuntimeWarning ) localedirs = None self._init_translation_catalog() if localedirs: for localedir in localedirs: translation = self._new_gnu_trans(localedir) self.merge(translation) else: self._add_installed_apps_translations() self._add_local_translations() if ( self.__language == settings.LANGUAGE_CODE and self.domain == "django" and self._catalog is None ): # default lang should have at least one translation file available. raise OSError( "No translation files found for default language %s." % settings.LANGUAGE_CODE ) self._add_fallback(localedirs) if self._catalog is None: # No catalogs found for this language, set an empty catalog. self._catalog = TranslationCatalog() def __repr__(self): return "<DjangoTranslation lang:%s>" % self.__language def _new_gnu_trans(self, localedir, use_null_fallback=True): """ Return a mergeable gettext.GNUTranslations instance. A convenience wrapper. By default gettext uses 'fallback=False'. Using param `use_null_fallback` to avoid confusion with any other references to 'fallback'. """ return gettext_module.translation( domain=self.domain, localedir=localedir, languages=[self.__locale], fallback=use_null_fallback, ) def _init_translation_catalog(self): """Create a base catalog using global django translations.""" settingsfile = sys.modules[settings.__module__].__file__ localedir = os.path.join(os.path.dirname(settingsfile), "locale") translation = self._new_gnu_trans(localedir) self.merge(translation) def _add_installed_apps_translations(self): """Merge translations from each installed app.""" try: app_configs = reversed(apps.get_app_configs()) except AppRegistryNotReady: raise AppRegistryNotReady( "The translation infrastructure cannot be initialized before the " "apps registry is ready. Check that you don't make non-lazy " "gettext calls at import time." ) for app_config in app_configs: localedir = os.path.join(app_config.path, "locale") if os.path.exists(localedir): translation = self._new_gnu_trans(localedir) self.merge(translation) def _add_local_translations(self): """Merge translations defined in LOCALE_PATHS.""" for localedir in reversed(settings.LOCALE_PATHS): translation = self._new_gnu_trans(localedir) self.merge(translation) def _add_fallback(self, localedirs=None): """Set the GNUTranslations() fallback with the default language.""" # Don't set a fallback for the default language or any English variant # (as it's empty, so it'll ALWAYS fall back to the default language) if self.__language == settings.LANGUAGE_CODE or self.__language.startswith( "en" ): return if self.domain == "django": # Get from cache default_translation = translation(settings.LANGUAGE_CODE) else: default_translation = DjangoTranslation( settings.LANGUAGE_CODE, domain=self.domain, localedirs=localedirs ) self.add_fallback(default_translation) def merge(self, other): """Merge another translation into this catalog.""" if not getattr(other, "_catalog", None): return # NullTranslations() has no _catalog if self._catalog is None: # Take plural and _info from first catalog found (generally Django's). self.plural = other.plural self._info = other._info.copy() self._catalog = TranslationCatalog(other) else: self._catalog.update(other) if other._fallback: self.add_fallback(other._fallback) def language(self): """Return the translation language.""" return self.__language def to_language(self): """Return the translation language name.""" return self.__to_language def ngettext(self, msgid1, msgid2, n): try: tmsg = self._catalog.plural(msgid1, n) except KeyError: if self._fallback: return self._fallback.ngettext(msgid1, msgid2, n) if n == 1: tmsg = msgid1 else: tmsg = msgid2 return tmsg def translation(language): """ Return a translation object in the default 'django' domain. """ global _translations if language not in _translations: _translations[language] = DjangoTranslation(language) return _translations[language] def activate(language): """ Fetch the translation object for a given language and install it as the current translation object for the current thread. """ if not language: return _active.value = translation(language) def deactivate(): """ Uninstall the active translation object so that further _() calls resolve to the default translation object. """ if hasattr(_active, "value"): del _active.value def deactivate_all(): """ Make the active translation object a NullTranslations() instance. This is useful when we want delayed translations to appear as the original string for some reason. """ _active.value = gettext_module.NullTranslations() _active.value.to_language = lambda *args: None def get_language(): """Return the currently selected language.""" t = getattr(_active, "value", None) if t is not None: try: return t.to_language() except AttributeError: pass # If we don't have a real translation object, assume it's the default language. return settings.LANGUAGE_CODE def get_language_bidi(): """ Return selected language's BiDi layout. * False = left-to-right layout * True = right-to-left layout """ lang = get_language() if lang is None: return False else: base_lang = get_language().split("-")[0] return base_lang in settings.LANGUAGES_BIDI def catalog(): """ Return the current active catalog for further processing. This can be used if you need to modify the catalog or want to access the whole message catalog instead of just translating one string. """ global _default t = getattr(_active, "value", None) if t is not None: return t if _default is None: _default = translation(settings.LANGUAGE_CODE) return _default def gettext(message): """ Translate the 'message' string. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object. """ global _default eol_message = message.replace("\r\n", "\n").replace("\r", "\n") if eol_message: _default = _default or translation(settings.LANGUAGE_CODE) translation_object = getattr(_active, "value", _default) result = translation_object.gettext(eol_message) else: # Return an empty value of the corresponding type if an empty message # is given, instead of metadata, which is the default gettext behavior. result = type(message)("") if isinstance(message, SafeData): return mark_safe(result) return result def pgettext(context, message): msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message) result = gettext(msg_with_ctxt) if CONTEXT_SEPARATOR in result: # Translation not found result = message elif isinstance(message, SafeData): result = mark_safe(result) return result def gettext_noop(message): """ Mark strings for translation but don't translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later. """ return message def do_ntranslate(singular, plural, number, translation_function): global _default t = getattr(_active, "value", None) if t is not None: return getattr(t, translation_function)(singular, plural, number) if _default is None: _default = translation(settings.LANGUAGE_CODE) return getattr(_default, translation_function)(singular, plural, number) def ngettext(singular, plural, number): """ Return a string of the translation of either the singular or plural, based on the number. """ return do_ntranslate(singular, plural, number, "ngettext") def npgettext(context, singular, plural, number): msgs_with_ctxt = ( "%s%s%s" % (context, CONTEXT_SEPARATOR, singular), "%s%s%s" % (context, CONTEXT_SEPARATOR, plural), number, ) result = ngettext(*msgs_with_ctxt) if CONTEXT_SEPARATOR in result: # Translation not found result = ngettext(singular, plural, number) return result def all_locale_paths(): """ Return a list of paths to user-provides languages files. """ globalpath = os.path.join( os.path.dirname(sys.modules[settings.__module__].__file__), "locale" ) app_paths = [] for app_config in apps.get_app_configs(): locale_path = os.path.join(app_config.path, "locale") if os.path.exists(locale_path): app_paths.append(locale_path) return [globalpath, *settings.LOCALE_PATHS, *app_paths] @functools.lru_cache(maxsize=1000) def check_for_language(lang_code): """ Check whether there is a global language file for the given language code. This is used to decide whether a user-provided language is available. lru_cache should have a maxsize to prevent from memory exhaustion attacks, as the provided language codes are taken from the HTTP request. See also <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>. """ # First, a quick check to make sure lang_code is well-formed (#21458) if lang_code is None or not language_code_re.search(lang_code): return False return any( gettext_module.find("django", path, [to_locale(lang_code)]) is not None for path in all_locale_paths() ) @functools.lru_cache def get_languages(): """ Cache of settings.LANGUAGES in a dictionary for easy lookups by key. Convert keys to lowercase as they should be treated as case-insensitive. """ return {key.lower(): value for key, value in dict(settings.LANGUAGES).items()} @functools.lru_cache(maxsize=1000) def get_supported_language_variant(lang_code, strict=False): """ Return the language code that's listed in supported languages, possibly selecting a more generic variant. Raise LookupError if nothing is found. If `strict` is False (the default), look for a country-specific variant when neither the language code nor its generic variant is found. lru_cache should have a maxsize to prevent from memory exhaustion attacks, as the provided language codes are taken from the HTTP request. See also <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>. """ if lang_code: # If 'zh-hant-tw' is not supported, try special fallback or subsequent # language codes i.e. 'zh-hant' and 'zh'. possible_lang_codes = [lang_code] try: possible_lang_codes.extend(LANG_INFO[lang_code]["fallback"]) except KeyError: pass i = None while (i := lang_code.rfind("-", 0, i)) > -1: possible_lang_codes.append(lang_code[:i]) generic_lang_code = possible_lang_codes[-1] supported_lang_codes = get_languages() for code in possible_lang_codes: if code.lower() in supported_lang_codes and check_for_language(code): return code if not strict: # if fr-fr is not supported, try fr-ca. for supported_code in supported_lang_codes: if supported_code.startswith(generic_lang_code + "-"): return supported_code raise LookupError(lang_code) def get_language_from_path(path, strict=False): """ Return the language code if there's a valid language code found in `path`. If `strict` is False (the default), look for a country-specific variant when neither the language code nor its generic variant is found. """ regex_match = language_code_prefix_re.match(path) if not regex_match: return None lang_code = regex_match[1] try: return get_supported_language_variant(lang_code, strict=strict) except LookupError: return None def get_language_from_request(request, check_path=False): """ Analyze the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language. If check_path is True, the URL path prefix will be checked for a language code, otherwise this is skipped for backwards compatibility. """ if check_path: lang_code = get_language_from_path(request.path_info) if lang_code is not None: return lang_code lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) if ( lang_code is not None and lang_code in get_languages() and check_for_language(lang_code) ): return lang_code try: return get_supported_language_variant(lang_code) except LookupError: pass accept = request.META.get("HTTP_ACCEPT_LANGUAGE", "") for accept_lang, unused in parse_accept_lang_header(accept): if accept_lang == "*": break if not language_code_re.search(accept_lang): continue try: return get_supported_language_variant(accept_lang) except LookupError: continue try: return get_supported_language_variant(settings.LANGUAGE_CODE) except LookupError: return settings.LANGUAGE_CODE @functools.lru_cache(maxsize=1000) def _parse_accept_lang_header(lang_string): """ Parse the lang_string, which is the body of an HTTP Accept-Language header, and return a tuple of (lang, q-value), ordered by 'q' values. Return an empty tuple if there are any format errors in lang_string. """ result = [] pieces = accept_language_re.split(lang_string.lower()) if pieces[-1]: return () for i in range(0, len(pieces) - 1, 3): first, lang, priority = pieces[i : i + 3] if first: return () if priority: priority = float(priority) else: priority = 1.0 result.append((lang, priority)) result.sort(key=lambda k: k[1], reverse=True) return tuple(result) def parse_accept_lang_header(lang_string): """ Parse the value of the Accept-Language header up to a maximum length. The value of the header is truncated to a maximum length to avoid potential denial of service and memory exhaustion attacks. Excessive memory could be used if the raw value is very large as it would be cached due to the use of functools.lru_cache() to avoid repetitive parsing of common header values. """ # If the header value doesn't exceed the maximum allowed length, parse it. if len(lang_string) <= ACCEPT_LANGUAGE_HEADER_MAX_LENGTH: return _parse_accept_lang_header(lang_string) # If there is at least one comma in the value, parse up to the last comma # before the max length, skipping any truncated parts at the end of the # header value. if (index := lang_string.rfind(",", 0, ACCEPT_LANGUAGE_HEADER_MAX_LENGTH)) > 0: return _parse_accept_lang_header(lang_string[:index]) # Don't attempt to parse if there is only one language-range value which is # longer than the maximum allowed length and so truncated. return ()
7a3a4320e1df4f9cac9fbbdde6947215496041c821fffd0f66649679c0cf2a9d
""" Various data structures used in query construction. Factored out from django.db.models.query to avoid making the main module very large and/or so that they can be used by other modules without getting into circular import difficulties. """ import functools import inspect import logging from collections import namedtuple from django.core.exceptions import FieldError from django.db import DEFAULT_DB_ALIAS, DatabaseError, connections from django.db.models.constants import LOOKUP_SEP from django.utils import tree logger = logging.getLogger("django.db.models") # PathInfo is used when converting lookups (fk__somecol). The contents # describe the relation in Model terms (model Options and Fields for both # sides of the relation. The join_field is the field backing the relation. PathInfo = namedtuple( "PathInfo", "from_opts to_opts target_fields join_field m2m direct filtered_relation", ) def subclasses(cls): yield cls for subclass in cls.__subclasses__(): yield from subclasses(subclass) class Q(tree.Node): """ Encapsulate filters as objects that can then be combined logically (using `&` and `|`). """ # Connection types AND = "AND" OR = "OR" XOR = "XOR" default = AND conditional = True def __init__(self, *args, _connector=None, _negated=False, **kwargs): super().__init__( children=[*args, *sorted(kwargs.items())], connector=_connector, negated=_negated, ) def _combine(self, other, conn): if getattr(other, "conditional", False) is False: raise TypeError(other) if not self: return other.copy() if not other and isinstance(other, Q): return self.copy() obj = self.create(connector=conn) obj.add(self, conn) obj.add(other, conn) return obj def __or__(self, other): return self._combine(other, self.OR) def __and__(self, other): return self._combine(other, self.AND) def __xor__(self, other): return self._combine(other, self.XOR) def __invert__(self): obj = self.copy() obj.negate() return obj def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): # We must promote any new joins to left outer joins so that when Q is # used as an expression, rows aren't filtered due to joins. clause, joins = query._add_q( self, reuse, allow_joins=allow_joins, split_subq=False, check_filterable=False, summarize=summarize, ) query.promote_joins(joins) return clause def flatten(self): """ Recursively yield this Q object and all subexpressions, in depth-first order. """ yield self for child in self.children: if isinstance(child, tuple): # Use the lookup. child = child[1] if hasattr(child, "flatten"): yield from child.flatten() else: yield child def check(self, against, using=DEFAULT_DB_ALIAS): """ Do a database query to check if the expressions of the Q instance matches against the expressions. """ # Avoid circular imports. from django.db.models import BooleanField, Value from django.db.models.functions import Coalesce from django.db.models.sql import Query from django.db.models.sql.constants import SINGLE query = Query(None) for name, value in against.items(): if not hasattr(value, "resolve_expression"): value = Value(value) query.add_annotation(value, name, select=False) query.add_annotation(Value(1), "_check") # This will raise a FieldError if a field is missing in "against". if connections[using].features.supports_comparing_boolean_expr: query.add_q(Q(Coalesce(self, True, output_field=BooleanField()))) else: query.add_q(self) compiler = query.get_compiler(using=using) try: return compiler.execute_sql(SINGLE) is not None except DatabaseError as e: logger.warning("Got a database error calling check() on %r: %s", self, e) return True def deconstruct(self): path = "%s.%s" % (self.__class__.__module__, self.__class__.__name__) if path.startswith("django.db.models.query_utils"): path = path.replace("django.db.models.query_utils", "django.db.models") args = tuple(self.children) kwargs = {} if self.connector != self.default: kwargs["_connector"] = self.connector if self.negated: kwargs["_negated"] = True return path, args, kwargs class DeferredAttribute: """ A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed. """ def __init__(self, field): self.field = field def __get__(self, instance, cls=None): """ Retrieve and caches the value from the datastore on the first lookup. Return the cached value. """ if instance is None: return self data = instance.__dict__ field_name = self.field.attname if field_name not in data: # Let's see if the field is part of the parent chain. If so we # might be able to reuse the already loaded value. Refs #18343. val = self._check_parent_chain(instance) if val is None: instance.refresh_from_db(fields=[field_name]) else: data[field_name] = val return data[field_name] def _check_parent_chain(self, instance): """ Check if the field value can be fetched from a parent field already loaded in the instance. This can be done if the to-be fetched field is a primary key field. """ opts = instance._meta link_field = opts.get_ancestor_link(self.field.model) if self.field.primary_key and self.field != link_field: return getattr(instance, link_field.attname) return None class class_or_instance_method: """ Hook used in RegisterLookupMixin to return partial functions depending on the caller type (instance or class of models.Field). """ def __init__(self, class_method, instance_method): self.class_method = class_method self.instance_method = instance_method def __get__(self, instance, owner): if instance is None: return functools.partial(self.class_method, owner) return functools.partial(self.instance_method, instance) class RegisterLookupMixin: def _get_lookup(self, lookup_name): return self.get_lookups().get(lookup_name, None) @functools.cache def get_class_lookups(cls): class_lookups = [ parent.__dict__.get("class_lookups", {}) for parent in inspect.getmro(cls) ] return cls.merge_dicts(class_lookups) def get_instance_lookups(self): class_lookups = self.get_class_lookups() if instance_lookups := getattr(self, "instance_lookups", None): return {**class_lookups, **instance_lookups} return class_lookups get_lookups = class_or_instance_method(get_class_lookups, get_instance_lookups) get_class_lookups = classmethod(get_class_lookups) def get_lookup(self, lookup_name): from django.db.models.lookups import Lookup found = self._get_lookup(lookup_name) if found is None and hasattr(self, "output_field"): return self.output_field.get_lookup(lookup_name) if found is not None and not issubclass(found, Lookup): return None return found def get_transform(self, lookup_name): from django.db.models.lookups import Transform found = self._get_lookup(lookup_name) if found is None and hasattr(self, "output_field"): return self.output_field.get_transform(lookup_name) if found is not None and not issubclass(found, Transform): return None return found @staticmethod def merge_dicts(dicts): """ Merge dicts in reverse to preference the order of the original list. e.g., merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'. """ merged = {} for d in reversed(dicts): merged.update(d) return merged @classmethod def _clear_cached_class_lookups(cls): for subclass in subclasses(cls): subclass.get_class_lookups.cache_clear() def register_class_lookup(cls, lookup, lookup_name=None): if lookup_name is None: lookup_name = lookup.lookup_name if "class_lookups" not in cls.__dict__: cls.class_lookups = {} cls.class_lookups[lookup_name] = lookup cls._clear_cached_class_lookups() return lookup def register_instance_lookup(self, lookup, lookup_name=None): if lookup_name is None: lookup_name = lookup.lookup_name if "instance_lookups" not in self.__dict__: self.instance_lookups = {} self.instance_lookups[lookup_name] = lookup return lookup register_lookup = class_or_instance_method( register_class_lookup, register_instance_lookup ) register_class_lookup = classmethod(register_class_lookup) def _unregister_class_lookup(cls, lookup, lookup_name=None): """ Remove given lookup from cls lookups. For use in tests only as it's not thread-safe. """ if lookup_name is None: lookup_name = lookup.lookup_name del cls.class_lookups[lookup_name] cls._clear_cached_class_lookups() def _unregister_instance_lookup(self, lookup, lookup_name=None): """ Remove given lookup from instance lookups. For use in tests only as it's not thread-safe. """ if lookup_name is None: lookup_name = lookup.lookup_name del self.instance_lookups[lookup_name] _unregister_lookup = class_or_instance_method( _unregister_class_lookup, _unregister_instance_lookup ) _unregister_class_lookup = classmethod(_unregister_class_lookup) def select_related_descend(field, restricted, requested, select_mask, reverse=False): """ Return True if this field should be used to descend deeper for select_related() purposes. Used by both the query construction code (compiler.get_related_selections()) and the model instance creation code (compiler.klass_info). Arguments: * field - the field to be checked * restricted - a boolean field, indicating if the field list has been manually restricted using a requested clause) * requested - The select_related() dictionary. * select_mask - the dictionary of selected fields. * reverse - boolean, True if we are checking a reverse select related """ if not field.remote_field: return False if field.remote_field.parent_link and not reverse: return False if restricted: if reverse and field.related_query_name() not in requested: return False if not reverse and field.name not in requested: return False if not restricted and field.null: return False if ( restricted and select_mask and field.name in requested and field not in select_mask ): raise FieldError( f"Field {field.model._meta.object_name}.{field.name} cannot be both " "deferred and traversed using select_related at the same time." ) return True def refs_expression(lookup_parts, annotations): """ Check if the lookup_parts contains references to the given annotations set. Because the LOOKUP_SEP is contained in the default annotation names, check each prefix of the lookup_parts for a match. """ for n in range(1, len(lookup_parts) + 1): level_n_lookup = LOOKUP_SEP.join(lookup_parts[0:n]) if annotations.get(level_n_lookup): return level_n_lookup, lookup_parts[n:] return None, () def check_rel_lookup_compatibility(model, target_opts, field): """ Check that self.model is compatible with target_opts. Compatibility is OK if: 1) model and opts match (where proxy inheritance is removed) 2) model is parent of opts' model or the other way around """ def check(opts): return ( model._meta.concrete_model == opts.concrete_model or opts.concrete_model in model._meta.get_parent_list() or model in opts.get_parent_list() ) # If the field is a primary key, then doing a query against the field's # model is ok, too. Consider the case: # class Restaurant(models.Model): # place = OneToOneField(Place, primary_key=True): # Restaurant.objects.filter(pk__in=Restaurant.objects.all()). # If we didn't have the primary key check, then pk__in (== place__in) would # give Place's opts as the target opts, but Restaurant isn't compatible # with that. This logic applies only to primary keys, as when doing __in=qs, # we are going to turn this into __in=qs.values('pk') later on. return check(target_opts) or ( getattr(field, "primary_key", False) and check(field.model._meta) ) class FilteredRelation: """Specify custom filtering in the ON clause of SQL joins.""" def __init__(self, relation_name, *, condition=Q()): if not relation_name: raise ValueError("relation_name cannot be empty.") self.relation_name = relation_name self.alias = None if not isinstance(condition, Q): raise ValueError("condition argument must be a Q() instance.") # .condition and .resolved_condition have to be stored independently # as the former must remain unchanged for Join.__eq__ to remain stable # and reusable even once their .filtered_relation are resolved. self.condition = condition self.resolved_condition = None def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return ( self.relation_name == other.relation_name and self.alias == other.alias and self.condition == other.condition ) def clone(self): clone = FilteredRelation(self.relation_name, condition=self.condition) clone.alias = self.alias if (resolved_condition := self.resolved_condition) is not None: clone.resolved_condition = resolved_condition.clone() return clone def relabeled_clone(self, change_map): clone = self.clone() if resolved_condition := clone.resolved_condition: clone.resolved_condition = resolved_condition.relabeled_clone(change_map) return clone def resolve_expression(self, query, reuse, *args, **kwargs): clone = self.clone() clone.resolved_condition = query.build_filter( self.condition, can_reuse=reuse, allow_joins=True, split_subq=False, update_join_types=False, )[0] return clone def as_sql(self, compiler, connection): return compiler.compile(self.resolved_condition)
55ed33e0e5686210ef3b5dba811bcc8c7f42641b2dd4071d04960ed5d0622f88
from django.db import models from django.db.migrations.operations.base import Operation from django.db.migrations.state import ModelState from django.db.migrations.utils import field_references, resolve_relation from django.db.models.options import normalize_together from django.utils.functional import cached_property from .fields import AddField, AlterField, FieldOperation, RemoveField, RenameField def _check_for_duplicates(arg_name, objs): used_vals = set() for val in objs: if val in used_vals: raise ValueError( "Found duplicate value %s in CreateModel %s argument." % (val, arg_name) ) used_vals.add(val) class ModelOperation(Operation): def __init__(self, name): self.name = name @cached_property def name_lower(self): return self.name.lower() def references_model(self, name, app_label): return name.lower() == self.name_lower def reduce(self, operation, app_label): return super().reduce(operation, app_label) or self.can_reduce_through( operation, app_label ) def can_reduce_through(self, operation, app_label): return not operation.references_model(self.name, app_label) class CreateModel(ModelOperation): """Create a model's table.""" serialization_expand_args = ["fields", "options", "managers"] def __init__(self, name, fields, options=None, bases=None, managers=None): self.fields = fields self.options = options or {} self.bases = bases or (models.Model,) self.managers = managers or [] super().__init__(name) # Sanity-check that there are no duplicated field names, bases, or # manager names _check_for_duplicates("fields", (name for name, _ in self.fields)) _check_for_duplicates( "bases", ( base._meta.label_lower if hasattr(base, "_meta") else base.lower() if isinstance(base, str) else base for base in self.bases ), ) _check_for_duplicates("managers", (name for name, _ in self.managers)) def deconstruct(self): kwargs = { "name": self.name, "fields": self.fields, } if self.options: kwargs["options"] = self.options if self.bases and self.bases != (models.Model,): kwargs["bases"] = self.bases if self.managers and self.managers != [("objects", models.Manager())]: kwargs["managers"] = self.managers return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.add_model( ModelState( app_label, self.name, list(self.fields), dict(self.options), tuple(self.bases), list(self.managers), ) ) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.create_model(model) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.delete_model(model) def describe(self): return "Create %smodel %s" % ( "proxy " if self.options.get("proxy", False) else "", self.name, ) @property def migration_name_fragment(self): return self.name_lower def references_model(self, name, app_label): name_lower = name.lower() if name_lower == self.name_lower: return True # Check we didn't inherit from the model reference_model_tuple = (app_label, name_lower) for base in self.bases: if ( base is not models.Model and isinstance(base, (models.base.ModelBase, str)) and resolve_relation(base, app_label) == reference_model_tuple ): return True # Check we have no FKs/M2Ms with it for _name, field in self.fields: if field_references( (app_label, self.name_lower), field, reference_model_tuple ): return True return False def reduce(self, operation, app_label): if ( isinstance(operation, DeleteModel) and self.name_lower == operation.name_lower and not self.options.get("proxy", False) ): return [] elif ( isinstance(operation, RenameModel) and self.name_lower == operation.old_name_lower ): return [ CreateModel( operation.new_name, fields=self.fields, options=self.options, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, AlterModelOptions) and self.name_lower == operation.name_lower ): options = {**self.options, **operation.options} for key in operation.ALTER_OPTION_KEYS: if key not in operation.options: options.pop(key, None) return [ CreateModel( self.name, fields=self.fields, options=options, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, AlterModelManagers) and self.name_lower == operation.name_lower ): return [ CreateModel( self.name, fields=self.fields, options=self.options, bases=self.bases, managers=operation.managers, ), ] elif ( isinstance(operation, AlterTogetherOptionOperation) and self.name_lower == operation.name_lower ): return [ CreateModel( self.name, fields=self.fields, options={ **self.options, **{operation.option_name: operation.option_value}, }, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, AlterOrderWithRespectTo) and self.name_lower == operation.name_lower ): return [ CreateModel( self.name, fields=self.fields, options={ **self.options, "order_with_respect_to": operation.order_with_respect_to, }, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, FieldOperation) and self.name_lower == operation.model_name_lower ): if isinstance(operation, AddField): return [ CreateModel( self.name, fields=self.fields + [(operation.name, operation.field)], options=self.options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, AlterField): return [ CreateModel( self.name, fields=[ (n, operation.field if n == operation.name else v) for n, v in self.fields ], options=self.options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, RemoveField): options = self.options.copy() for option_name in ("unique_together", "index_together"): option = options.pop(option_name, None) if option: option = set( filter( bool, ( tuple( f for f in fields if f != operation.name_lower ) for fields in option ), ) ) if option: options[option_name] = option order_with_respect_to = options.get("order_with_respect_to") if order_with_respect_to == operation.name_lower: del options["order_with_respect_to"] return [ CreateModel( self.name, fields=[ (n, v) for n, v in self.fields if n.lower() != operation.name_lower ], options=options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, RenameField): options = self.options.copy() for option_name in ("unique_together", "index_together"): option = options.get(option_name) if option: options[option_name] = { tuple( operation.new_name if f == operation.old_name else f for f in fields ) for fields in option } order_with_respect_to = options.get("order_with_respect_to") if order_with_respect_to == operation.old_name: options["order_with_respect_to"] = operation.new_name return [ CreateModel( self.name, fields=[ (operation.new_name if n == operation.old_name else n, v) for n, v in self.fields ], options=options, bases=self.bases, managers=self.managers, ), ] return super().reduce(operation, app_label) class DeleteModel(ModelOperation): """Drop a model's table.""" def deconstruct(self): kwargs = { "name": self.name, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.remove_model(app_label, self.name_lower) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.delete_model(model) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.create_model(model) def references_model(self, name, app_label): # The deleted model could be referencing the specified model through # related fields. return True def describe(self): return "Delete model %s" % self.name @property def migration_name_fragment(self): return "delete_%s" % self.name_lower class RenameModel(ModelOperation): """Rename a model.""" def __init__(self, old_name, new_name): self.old_name = old_name self.new_name = new_name super().__init__(old_name) @cached_property def old_name_lower(self): return self.old_name.lower() @cached_property def new_name_lower(self): return self.new_name.lower() def deconstruct(self): kwargs = { "old_name": self.old_name, "new_name": self.new_name, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.rename_model(app_label, self.old_name, self.new_name) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.new_name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.old_name) # Move the main table schema_editor.alter_db_table( new_model, old_model._meta.db_table, new_model._meta.db_table, ) # Alter the fields pointing to us for related_object in old_model._meta.related_objects: if related_object.related_model == old_model: model = new_model related_key = (app_label, self.new_name_lower) else: model = related_object.related_model related_key = ( related_object.related_model._meta.app_label, related_object.related_model._meta.model_name, ) to_field = to_state.apps.get_model(*related_key)._meta.get_field( related_object.field.name ) schema_editor.alter_field( model, related_object.field, to_field, ) # Rename M2M fields whose name is based on this model's name. fields = zip( old_model._meta.local_many_to_many, new_model._meta.local_many_to_many ) for old_field, new_field in fields: # Skip self-referential fields as these are renamed above. if ( new_field.model == new_field.related_model or not new_field.remote_field.through._meta.auto_created ): continue # Rename columns and the M2M table. schema_editor._alter_many_to_many( new_model, old_field, new_field, strict=False, ) def database_backwards(self, app_label, schema_editor, from_state, to_state): self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name self.database_forwards(app_label, schema_editor, from_state, to_state) self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name def references_model(self, name, app_label): return ( name.lower() == self.old_name_lower or name.lower() == self.new_name_lower ) def describe(self): return "Rename model %s to %s" % (self.old_name, self.new_name) @property def migration_name_fragment(self): return "rename_%s_%s" % (self.old_name_lower, self.new_name_lower) def reduce(self, operation, app_label): if ( isinstance(operation, RenameModel) and self.new_name_lower == operation.old_name_lower ): return [ RenameModel( self.old_name, operation.new_name, ), ] # Skip `ModelOperation.reduce` as we want to run `references_model` # against self.new_name. return super(ModelOperation, self).reduce( operation, app_label ) or not operation.references_model(self.new_name, app_label) class ModelOptionOperation(ModelOperation): def reduce(self, operation, app_label): if ( isinstance(operation, (self.__class__, DeleteModel)) and self.name_lower == operation.name_lower ): return [operation] return super().reduce(operation, app_label) class AlterModelTable(ModelOptionOperation): """Rename a model's table.""" def __init__(self, name, table): self.table = table super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "table": self.table, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options(app_label, self.name_lower, {"db_table": self.table}) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.name) schema_editor.alter_db_table( new_model, old_model._meta.db_table, new_model._meta.db_table, ) # Rename M2M fields whose name is based on this model's db_table for old_field, new_field in zip( old_model._meta.local_many_to_many, new_model._meta.local_many_to_many ): if new_field.remote_field.through._meta.auto_created: schema_editor.alter_db_table( new_field.remote_field.through, old_field.remote_field.through._meta.db_table, new_field.remote_field.through._meta.db_table, ) def database_backwards(self, app_label, schema_editor, from_state, to_state): return self.database_forwards(app_label, schema_editor, from_state, to_state) def describe(self): return "Rename table for %s to %s" % ( self.name, self.table if self.table is not None else "(default)", ) @property def migration_name_fragment(self): return "alter_%s_table" % self.name_lower class AlterModelTableComment(ModelOptionOperation): def __init__(self, name, table_comment): self.table_comment = table_comment super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "table_comment": self.table_comment, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options( app_label, self.name_lower, {"db_table_comment": self.table_comment} ) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.name) schema_editor.alter_db_table_comment( new_model, old_model._meta.db_table_comment, new_model._meta.db_table_comment, ) def database_backwards(self, app_label, schema_editor, from_state, to_state): return self.database_forwards(app_label, schema_editor, from_state, to_state) def describe(self): return f"Alter {self.name} table comment" @property def migration_name_fragment(self): return f"alter_{self.name_lower}_table_comment" class AlterTogetherOptionOperation(ModelOptionOperation): option_name = None def __init__(self, name, option_value): if option_value: option_value = set(normalize_together(option_value)) setattr(self, self.option_name, option_value) super().__init__(name) @cached_property def option_value(self): return getattr(self, self.option_name) def deconstruct(self): kwargs = { "name": self.name, self.option_name: self.option_value, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options( app_label, self.name_lower, {self.option_name: self.option_value}, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.name) alter_together = getattr(schema_editor, "alter_%s" % self.option_name) alter_together( new_model, getattr(old_model._meta, self.option_name, set()), getattr(new_model._meta, self.option_name, set()), ) def database_backwards(self, app_label, schema_editor, from_state, to_state): return self.database_forwards(app_label, schema_editor, from_state, to_state) def references_field(self, model_name, name, app_label): return self.references_model(model_name, app_label) and ( not self.option_value or any((name in fields) for fields in self.option_value) ) def describe(self): return "Alter %s for %s (%s constraint(s))" % ( self.option_name, self.name, len(self.option_value or ""), ) @property def migration_name_fragment(self): return "alter_%s_%s" % (self.name_lower, self.option_name) def can_reduce_through(self, operation, app_label): return super().can_reduce_through(operation, app_label) or ( isinstance(operation, AlterTogetherOptionOperation) and type(operation) is not type(self) ) class AlterUniqueTogether(AlterTogetherOptionOperation): """ Change the value of unique_together to the target one. Input value of unique_together must be a set of tuples. """ option_name = "unique_together" def __init__(self, name, unique_together): super().__init__(name, unique_together) class AlterIndexTogether(AlterTogetherOptionOperation): """ Change the value of index_together to the target one. Input value of index_together must be a set of tuples. """ option_name = "index_together" def __init__(self, name, index_together): super().__init__(name, index_together) class AlterOrderWithRespectTo(ModelOptionOperation): """Represent a change with the order_with_respect_to option.""" option_name = "order_with_respect_to" def __init__(self, name, order_with_respect_to): self.order_with_respect_to = order_with_respect_to super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "order_with_respect_to": self.order_with_respect_to, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options( app_label, self.name_lower, {self.option_name: self.order_with_respect_to}, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): to_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, to_model): from_model = from_state.apps.get_model(app_label, self.name) # Remove a field if we need to if ( from_model._meta.order_with_respect_to and not to_model._meta.order_with_respect_to ): schema_editor.remove_field( from_model, from_model._meta.get_field("_order") ) # Add a field if we need to (altering the column is untouched as # it's likely a rename) elif ( to_model._meta.order_with_respect_to and not from_model._meta.order_with_respect_to ): field = to_model._meta.get_field("_order") if not field.has_default(): field.default = 0 schema_editor.add_field( from_model, field, ) def database_backwards(self, app_label, schema_editor, from_state, to_state): self.database_forwards(app_label, schema_editor, from_state, to_state) def references_field(self, model_name, name, app_label): return self.references_model(model_name, app_label) and ( self.order_with_respect_to is None or name == self.order_with_respect_to ) def describe(self): return "Set order_with_respect_to on %s to %s" % ( self.name, self.order_with_respect_to, ) @property def migration_name_fragment(self): return "alter_%s_order_with_respect_to" % self.name_lower class AlterModelOptions(ModelOptionOperation): """ Set new model options that don't directly affect the database schema (like verbose_name, permissions, ordering). Python code in migrations may still need them. """ # Model options we want to compare and preserve in an AlterModelOptions op ALTER_OPTION_KEYS = [ "base_manager_name", "default_manager_name", "default_related_name", "get_latest_by", "managed", "ordering", "permissions", "default_permissions", "select_on_save", "verbose_name", "verbose_name_plural", ] def __init__(self, name, options): self.options = options super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "options": self.options, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options( app_label, self.name_lower, self.options, self.ALTER_OPTION_KEYS, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass def describe(self): return "Change Meta options on %s" % self.name @property def migration_name_fragment(self): return "alter_%s_options" % self.name_lower class AlterModelManagers(ModelOptionOperation): """Alter the model's managers.""" serialization_expand_args = ["managers"] def __init__(self, name, managers): self.managers = managers super().__init__(name) def deconstruct(self): return (self.__class__.__qualname__, [self.name, self.managers], {}) def state_forwards(self, app_label, state): state.alter_model_managers(app_label, self.name_lower, self.managers) def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass def describe(self): return "Change managers on %s" % self.name @property def migration_name_fragment(self): return "alter_%s_managers" % self.name_lower class IndexOperation(Operation): option_name = "indexes" @cached_property def model_name_lower(self): return self.model_name.lower() class AddIndex(IndexOperation): """Add an index on a model.""" def __init__(self, model_name, index): self.model_name = model_name if not index.name: raise ValueError( "Indexes passed to AddIndex operations require a name " "argument. %r doesn't have one." % index ) self.index = index def state_forwards(self, app_label, state): state.add_index(app_label, self.model_name_lower, self.index) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.add_index(model, self.index) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.remove_index(model, self.index) def deconstruct(self): kwargs = { "model_name": self.model_name, "index": self.index, } return ( self.__class__.__qualname__, [], kwargs, ) def describe(self): if self.index.expressions: return "Create index %s on %s on model %s" % ( self.index.name, ", ".join([str(expression) for expression in self.index.expressions]), self.model_name, ) return "Create index %s on field(s) %s of model %s" % ( self.index.name, ", ".join(self.index.fields), self.model_name, ) @property def migration_name_fragment(self): return "%s_%s" % (self.model_name_lower, self.index.name.lower()) def reduce(self, operation, app_label): if isinstance(operation, RemoveIndex) and self.index.name == operation.name: return [] return super().reduce(operation, app_label) class RemoveIndex(IndexOperation): """Remove an index from a model.""" def __init__(self, model_name, name): self.model_name = model_name self.name = name def state_forwards(self, app_label, state): state.remove_index(app_label, self.model_name_lower, self.name) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): from_model_state = from_state.models[app_label, self.model_name_lower] index = from_model_state.get_index_by_name(self.name) schema_editor.remove_index(model, index) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): to_model_state = to_state.models[app_label, self.model_name_lower] index = to_model_state.get_index_by_name(self.name) schema_editor.add_index(model, index) def deconstruct(self): kwargs = { "model_name": self.model_name, "name": self.name, } return ( self.__class__.__qualname__, [], kwargs, ) def describe(self): return "Remove index %s from %s" % (self.name, self.model_name) @property def migration_name_fragment(self): return "remove_%s_%s" % (self.model_name_lower, self.name.lower()) class RenameIndex(IndexOperation): """Rename an index.""" def __init__(self, model_name, new_name, old_name=None, old_fields=None): if not old_name and not old_fields: raise ValueError( "RenameIndex requires one of old_name and old_fields arguments to be " "set." ) if old_name and old_fields: raise ValueError( "RenameIndex.old_name and old_fields are mutually exclusive." ) self.model_name = model_name self.new_name = new_name self.old_name = old_name self.old_fields = old_fields @cached_property def old_name_lower(self): return self.old_name.lower() @cached_property def new_name_lower(self): return self.new_name.lower() def deconstruct(self): kwargs = { "model_name": self.model_name, "new_name": self.new_name, } if self.old_name: kwargs["old_name"] = self.old_name if self.old_fields: kwargs["old_fields"] = self.old_fields return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): if self.old_fields: state.add_index( app_label, self.model_name_lower, models.Index(fields=self.old_fields, name=self.new_name), ) state.remove_model_options( app_label, self.model_name_lower, AlterIndexTogether.option_name, self.old_fields, ) else: state.rename_index( app_label, self.model_name_lower, self.old_name, self.new_name ) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if not self.allow_migrate_model(schema_editor.connection.alias, model): return if self.old_fields: from_model = from_state.apps.get_model(app_label, self.model_name) columns = [ from_model._meta.get_field(field).column for field in self.old_fields ] matching_index_name = schema_editor._constraint_names( from_model, column_names=columns, index=True ) if len(matching_index_name) != 1: raise ValueError( "Found wrong number (%s) of indexes for %s(%s)." % ( len(matching_index_name), from_model._meta.db_table, ", ".join(columns), ) ) old_index = models.Index( fields=self.old_fields, name=matching_index_name[0], ) else: from_model_state = from_state.models[app_label, self.model_name_lower] old_index = from_model_state.get_index_by_name(self.old_name) # Don't alter when the index name is not changed. if old_index.name == self.new_name: return to_model_state = to_state.models[app_label, self.model_name_lower] new_index = to_model_state.get_index_by_name(self.new_name) schema_editor.rename_index(model, old_index, new_index) def database_backwards(self, app_label, schema_editor, from_state, to_state): if self.old_fields: # Backward operation with unnamed index is a no-op. return self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name self.database_forwards(app_label, schema_editor, from_state, to_state) self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name def describe(self): if self.old_name: return ( f"Rename index {self.old_name} on {self.model_name} to {self.new_name}" ) return ( f"Rename unnamed index for {self.old_fields} on {self.model_name} to " f"{self.new_name}" ) @property def migration_name_fragment(self): if self.old_name: return "rename_%s_%s" % (self.old_name_lower, self.new_name_lower) return "rename_%s_%s_%s" % ( self.model_name_lower, "_".join(self.old_fields), self.new_name_lower, ) def reduce(self, operation, app_label): if ( isinstance(operation, RenameIndex) and self.model_name_lower == operation.model_name_lower and operation.old_name and self.new_name_lower == operation.old_name_lower ): return [ RenameIndex( self.model_name, new_name=operation.new_name, old_name=self.old_name, old_fields=self.old_fields, ) ] return super().reduce(operation, app_label) class AddConstraint(IndexOperation): option_name = "constraints" def __init__(self, model_name, constraint): self.model_name = model_name self.constraint = constraint def state_forwards(self, app_label, state): state.add_constraint(app_label, self.model_name_lower, self.constraint) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.add_constraint(model, self.constraint) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.remove_constraint(model, self.constraint) def deconstruct(self): return ( self.__class__.__name__, [], { "model_name": self.model_name, "constraint": self.constraint, }, ) def describe(self): return "Create constraint %s on model %s" % ( self.constraint.name, self.model_name, ) @property def migration_name_fragment(self): return "%s_%s" % (self.model_name_lower, self.constraint.name.lower()) class RemoveConstraint(IndexOperation): option_name = "constraints" def __init__(self, model_name, name): self.model_name = model_name self.name = name def state_forwards(self, app_label, state): state.remove_constraint(app_label, self.model_name_lower, self.name) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): from_model_state = from_state.models[app_label, self.model_name_lower] constraint = from_model_state.get_constraint_by_name(self.name) schema_editor.remove_constraint(model, constraint) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): to_model_state = to_state.models[app_label, self.model_name_lower] constraint = to_model_state.get_constraint_by_name(self.name) schema_editor.add_constraint(model, constraint) def deconstruct(self): return ( self.__class__.__name__, [], { "model_name": self.model_name, "name": self.name, }, ) def describe(self): return "Remove constraint %s from model %s" % (self.name, self.model_name) @property def migration_name_fragment(self): return "remove_%s_%s" % (self.model_name_lower, self.name.lower())
3abb74897899c6e9519292af0c466416ad3fafdc9fa307d6edd0e00dc71ba786
import collections.abc import copy import datetime import decimal import operator import uuid import warnings from base64 import b64decode, b64encode from functools import partialmethod, total_ordering from django import forms from django.apps import apps from django.conf import settings from django.core import checks, exceptions, validators from django.db import connection, connections, router from django.db.models.constants import LOOKUP_SEP from django.db.models.enums import ChoicesMeta from django.db.models.query_utils import DeferredAttribute, RegisterLookupMixin from django.utils import timezone from django.utils.datastructures import DictWrapper from django.utils.dateparse import ( parse_date, parse_datetime, parse_duration, parse_time, ) from django.utils.duration import duration_microseconds, duration_string from django.utils.functional import Promise, cached_property from django.utils.ipv6 import clean_ipv6_address from django.utils.itercompat import is_iterable from django.utils.text import capfirst from django.utils.translation import gettext_lazy as _ __all__ = [ "AutoField", "BLANK_CHOICE_DASH", "BigAutoField", "BigIntegerField", "BinaryField", "BooleanField", "CharField", "CommaSeparatedIntegerField", "DateField", "DateTimeField", "DecimalField", "DurationField", "EmailField", "Empty", "Field", "FilePathField", "FloatField", "GenericIPAddressField", "IPAddressField", "IntegerField", "NOT_PROVIDED", "NullBooleanField", "PositiveBigIntegerField", "PositiveIntegerField", "PositiveSmallIntegerField", "SlugField", "SmallAutoField", "SmallIntegerField", "TextField", "TimeField", "URLField", "UUIDField", ] class Empty: pass class NOT_PROVIDED: pass # The values to use for "blank" in SelectFields. Will be appended to the start # of most "choices" lists. BLANK_CHOICE_DASH = [("", "---------")] def _load_field(app_label, model_name, field_name): return apps.get_model(app_label, model_name)._meta.get_field(field_name) # A guide to Field parameters: # # * name: The name of the field specified in the model. # * attname: The attribute to use on the model object. This is the same as # "name", except in the case of ForeignKeys, where "_id" is # appended. # * db_column: The db_column specified in the model (or None). # * column: The database column for this field. This is the same as # "attname", except if db_column is specified. # # Code that introspects values, or does other dynamic things, should use # attname. For example, this gets the primary key value of object "obj": # # getattr(obj, opts.pk.attname) def _empty(of_cls): new = Empty() new.__class__ = of_cls return new def return_None(): return None @total_ordering class Field(RegisterLookupMixin): """Base class for all field types""" # Designates whether empty strings fundamentally are allowed at the # database level. empty_strings_allowed = True empty_values = list(validators.EMPTY_VALUES) # These track each time a Field instance is created. Used to retain order. # The auto_creation_counter is used for fields that Django implicitly # creates, creation_counter is used for all user-specified fields. creation_counter = 0 auto_creation_counter = -1 default_validators = [] # Default set of validators default_error_messages = { "invalid_choice": _("Value %(value)r is not a valid choice."), "null": _("This field cannot be null."), "blank": _("This field cannot be blank."), "unique": _("%(model_name)s with this %(field_label)s already exists."), "unique_for_date": _( # Translators: The 'lookup_type' is one of 'date', 'year' or # 'month'. Eg: "Title must be unique for pub_date year" "%(field_label)s must be unique for " "%(date_field_label)s %(lookup_type)s." ), } system_check_deprecated_details = None system_check_removed_details = None # Attributes that don't affect a column definition. # These attributes are ignored when altering the field. non_db_attrs = ( "blank", "choices", "db_column", "editable", "error_messages", "help_text", "limit_choices_to", # Database-level options are not supported, see #21961. "on_delete", "related_name", "related_query_name", "validators", "verbose_name", ) # Field flags hidden = False many_to_many = None many_to_one = None one_to_many = None one_to_one = None related_model = None descriptor_class = DeferredAttribute # Generic field type description, usually overridden by subclasses def _description(self): return _("Field of type: %(field_type)s") % { "field_type": self.__class__.__name__ } description = property(_description) def __init__( self, verbose_name=None, name=None, primary_key=False, max_length=None, unique=False, blank=False, null=False, db_index=False, rel=None, default=NOT_PROVIDED, editable=True, serialize=True, unique_for_date=None, unique_for_month=None, unique_for_year=None, choices=None, help_text="", db_column=None, db_tablespace=None, auto_created=False, validators=(), error_messages=None, db_comment=None, ): self.name = name self.verbose_name = verbose_name # May be set by set_attributes_from_name self._verbose_name = verbose_name # Store original for deconstruction self.primary_key = primary_key self.max_length, self._unique = max_length, unique self.blank, self.null = blank, null self.remote_field = rel self.is_relation = self.remote_field is not None self.default = default self.editable = editable self.serialize = serialize self.unique_for_date = unique_for_date self.unique_for_month = unique_for_month self.unique_for_year = unique_for_year if isinstance(choices, ChoicesMeta): choices = choices.choices if isinstance(choices, collections.abc.Iterator): choices = list(choices) self.choices = choices self.help_text = help_text self.db_index = db_index self.db_column = db_column self.db_comment = db_comment self._db_tablespace = db_tablespace self.auto_created = auto_created # Adjust the appropriate creation counter, and save our local copy. if auto_created: self.creation_counter = Field.auto_creation_counter Field.auto_creation_counter -= 1 else: self.creation_counter = Field.creation_counter Field.creation_counter += 1 self._validators = list(validators) # Store for deconstruction later self._error_messages = error_messages # Store for deconstruction later def __str__(self): """ Return "app_label.model_label.field_name" for fields attached to models. """ if not hasattr(self, "model"): return super().__str__() model = self.model return "%s.%s" % (model._meta.label, self.name) def __repr__(self): """Display the module, class, and name of the field.""" path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__) name = getattr(self, "name", None) if name is not None: return "<%s: %s>" % (path, name) return "<%s>" % path def check(self, **kwargs): return [ *self._check_field_name(), *self._check_choices(), *self._check_db_index(), *self._check_db_comment(**kwargs), *self._check_null_allowed_for_primary_keys(), *self._check_backend_specific_checks(**kwargs), *self._check_validators(), *self._check_deprecation_details(), ] def _check_field_name(self): """ Check if field name is valid, i.e. 1) does not end with an underscore, 2) does not contain "__" and 3) is not "pk". """ if self.name.endswith("_"): return [ checks.Error( "Field names must not end with an underscore.", obj=self, id="fields.E001", ) ] elif LOOKUP_SEP in self.name: return [ checks.Error( 'Field names must not contain "%s".' % LOOKUP_SEP, obj=self, id="fields.E002", ) ] elif self.name == "pk": return [ checks.Error( "'pk' is a reserved word that cannot be used as a field name.", obj=self, id="fields.E003", ) ] else: return [] @classmethod def _choices_is_value(cls, value): return isinstance(value, (str, Promise)) or not is_iterable(value) def _check_choices(self): if not self.choices: return [] if not is_iterable(self.choices) or isinstance(self.choices, str): return [ checks.Error( "'choices' must be an iterable (e.g., a list or tuple).", obj=self, id="fields.E004", ) ] choice_max_length = 0 # Expect [group_name, [value, display]] for choices_group in self.choices: try: group_name, group_choices = choices_group except (TypeError, ValueError): # Containing non-pairs break try: if not all( self._choices_is_value(value) and self._choices_is_value(human_name) 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 self._choices_is_value(value) or not self._choices_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 [ checks.Error( "'choices' must be an iterable containing " "(actual value, human readable name) tuples.", obj=self, id="fields.E005", ) ] def _check_db_index(self): if self.db_index not in (None, True, False): return [ checks.Error( "'db_index' must be None, True or False.", obj=self, id="fields.E006", ) ] else: return [] def _check_db_comment(self, databases=None, **kwargs): if not self.db_comment or not databases: return [] errors = [] for db in databases: if not router.allow_migrate_model(db, self.model): continue connection = connections[db] if not ( connection.features.supports_comments or "supports_comments" in self.model._meta.required_db_features ): errors.append( checks.Warning( f"{connection.display_name} does not support comments on " f"columns (db_comment).", obj=self, id="fields.W163", ) ) return errors def _check_null_allowed_for_primary_keys(self): if ( self.primary_key and self.null and not connection.features.interprets_empty_strings_as_nulls ): # We cannot reliably check this for backends like Oracle which # consider NULL and '' to be equal (and thus set up # character-based fields a little differently). return [ checks.Error( "Primary keys must not have null=True.", hint=( "Set null=False on the field, or " "remove primary_key=True argument." ), obj=self, id="fields.E007", ) ] else: return [] def _check_backend_specific_checks(self, databases=None, **kwargs): if databases is None: return [] errors = [] for alias in databases: if router.allow_migrate_model(alias, self.model): errors.extend(connections[alias].validation.check_field(self, **kwargs)) return errors def _check_validators(self): errors = [] for i, validator in enumerate(self.validators): if not callable(validator): errors.append( checks.Error( "All 'validators' must be callable.", hint=( "validators[{i}] ({repr}) isn't a function or " "instance of a validator class.".format( i=i, repr=repr(validator), ) ), obj=self, id="fields.E008", ) ) return errors def _check_deprecation_details(self): if self.system_check_removed_details is not None: return [ checks.Error( self.system_check_removed_details.get( "msg", "%s has been removed except for support in historical " "migrations." % self.__class__.__name__, ), hint=self.system_check_removed_details.get("hint"), obj=self, id=self.system_check_removed_details.get("id", "fields.EXXX"), ) ] elif self.system_check_deprecated_details is not None: return [ checks.Warning( self.system_check_deprecated_details.get( "msg", "%s has been deprecated." % self.__class__.__name__ ), hint=self.system_check_deprecated_details.get("hint"), obj=self, id=self.system_check_deprecated_details.get("id", "fields.WXXX"), ) ] return [] def get_col(self, alias, output_field=None): if alias == self.model._meta.db_table and ( output_field is None or output_field == self ): return self.cached_col from django.db.models.expressions import Col return Col(alias, self, output_field) @cached_property def cached_col(self): from django.db.models.expressions import Col return Col(self.model._meta.db_table, self) def select_format(self, compiler, sql, params): """ Custom format for select clauses. For example, GIS columns need to be selected as AsText(table.col) on MySQL as the table.col data can't be used by Django. """ return sql, params def deconstruct(self): """ Return enough information to recreate the field as a 4-tuple: * The name of the field on the model, if contribute_to_class() has been run. * The import path of the field, including the class, e.g. django.db.models.IntegerField. This should be the most portable version, so less specific may be better. * A list of positional arguments. * A dict of keyword arguments. Note that the positional or keyword arguments must contain values of the following types (including inner values of collection types): * None, bool, str, int, float, complex, set, frozenset, list, tuple, dict * UUID * datetime.datetime (naive), datetime.date * top-level classes, top-level functions - will be referenced by their full import path * Storage instances - these have their own deconstruct() method This is because the values here must be serialized into a text format (possibly new Python code, possibly JSON) and these are the only types with encoding handlers defined. There's no need to return the exact way the field was instantiated this time, just ensure that the resulting field is the same - prefer keyword arguments over positional ones, and omit parameters with their default values. """ # Short-form way of fetching all the default parameters keywords = {} possibles = { "verbose_name": None, "primary_key": False, "max_length": None, "unique": False, "blank": False, "null": False, "db_index": False, "default": NOT_PROVIDED, "editable": True, "serialize": True, "unique_for_date": None, "unique_for_month": None, "unique_for_year": None, "choices": None, "help_text": "", "db_column": None, "db_comment": None, "db_tablespace": None, "auto_created": False, "validators": [], "error_messages": None, } attr_overrides = { "unique": "_unique", "error_messages": "_error_messages", "validators": "_validators", "verbose_name": "_verbose_name", "db_tablespace": "_db_tablespace", } equals_comparison = {"choices", "validators"} for name, default in possibles.items(): value = getattr(self, attr_overrides.get(name, name)) # Unroll anything iterable for choices into a concrete list if name == "choices" and isinstance(value, collections.abc.Iterable): value = list(value) # Do correct kind of comparison if name in equals_comparison: if value != default: keywords[name] = value else: if value is not default: keywords[name] = value # Work out path - we shorten it for known Django core fields path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__) if path.startswith("django.db.models.fields.related"): path = path.replace("django.db.models.fields.related", "django.db.models") elif path.startswith("django.db.models.fields.files"): path = path.replace("django.db.models.fields.files", "django.db.models") elif path.startswith("django.db.models.fields.json"): path = path.replace("django.db.models.fields.json", "django.db.models") elif path.startswith("django.db.models.fields.proxy"): path = path.replace("django.db.models.fields.proxy", "django.db.models") elif path.startswith("django.db.models.fields"): path = path.replace("django.db.models.fields", "django.db.models") # Return basic info - other fields should override this. return (self.name, path, [], keywords) def clone(self): """ Uses deconstruct() to clone a new copy of this Field. Will not preserve any class attachments/attribute names. """ name, path, args, kwargs = self.deconstruct() return self.__class__(*args, **kwargs) def __eq__(self, other): # Needed for @total_ordering if isinstance(other, Field): return self.creation_counter == other.creation_counter and getattr( self, "model", None ) == getattr(other, "model", None) return NotImplemented def __lt__(self, other): # This is needed because bisect does not take a comparison function. # Order by creation_counter first for backward compatibility. if isinstance(other, Field): if ( self.creation_counter != other.creation_counter or not hasattr(self, "model") and not hasattr(other, "model") ): return self.creation_counter < other.creation_counter elif hasattr(self, "model") != hasattr(other, "model"): return not hasattr(self, "model") # Order no-model fields first else: # creation_counter's are equal, compare only models. return (self.model._meta.app_label, self.model._meta.model_name) < ( other.model._meta.app_label, other.model._meta.model_name, ) return NotImplemented def __hash__(self): return hash(self.creation_counter) def __deepcopy__(self, memodict): # We don't have to deepcopy very much here, since most things are not # intended to be altered after initial creation. obj = copy.copy(self) if self.remote_field: obj.remote_field = copy.copy(self.remote_field) if hasattr(self.remote_field, "field") and self.remote_field.field is self: obj.remote_field.field = obj memodict[id(self)] = obj return obj def __copy__(self): # We need to avoid hitting __reduce__, so define this # slightly weird copy construct. obj = Empty() obj.__class__ = self.__class__ obj.__dict__ = self.__dict__.copy() return obj def __reduce__(self): """ Pickling should return the model._meta.fields instance of the field, not a new copy of that field. So, use the app registry to load the model and then the field back. """ if not hasattr(self, "model"): # Fields are sometimes used without attaching them to models (for # example in aggregation). In this case give back a plain field # instance. The code below will create a new empty instance of # class self.__class__, then update its dict with self.__dict__ # values - so, this is very close to normal pickle. state = self.__dict__.copy() # The _get_default cached_property can't be pickled due to lambda # usage. state.pop("_get_default", None) return _empty, (self.__class__,), state return _load_field, ( self.model._meta.app_label, self.model._meta.object_name, self.name, ) def get_pk_value_on_save(self, instance): """ Hook to generate new PK values on save. This method is called when saving instances with no primary key value set. If this method returns something else than None, then the returned value is used when saving the new instance. """ if self.default: return self.get_default() return None def to_python(self, value): """ Convert the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Return the converted value. Subclasses should override this. """ return value @cached_property def error_messages(self): messages = {} for c in reversed(self.__class__.__mro__): messages.update(getattr(c, "default_error_messages", {})) messages.update(self._error_messages or {}) return messages @cached_property def validators(self): """ Some validators can't be created at field initialization time. This method provides a way to delay their creation until required. """ return [*self.default_validators, *self._validators] def run_validators(self, value): if value in self.empty_values: return errors = [] for v in self.validators: try: v(value) except exceptions.ValidationError as e: if hasattr(e, "code") and e.code in self.error_messages: e.message = self.error_messages[e.code] errors.extend(e.error_list) if errors: raise exceptions.ValidationError(errors) def validate(self, value, model_instance): """ Validate value and raise ValidationError if necessary. Subclasses should override this to provide validation logic. """ if not self.editable: # Skip validation for non-editable fields. return if self.choices is not None and value not in self.empty_values: for option_key, option_value in self.choices: if isinstance(option_value, (list, tuple)): # This is an optgroup, so look inside the group for # options. for optgroup_key, optgroup_value in option_value: if value == optgroup_key: return elif value == option_key: return raise exceptions.ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}, ) if value is None and not self.null: raise exceptions.ValidationError(self.error_messages["null"], code="null") if not self.blank and value in self.empty_values: raise exceptions.ValidationError(self.error_messages["blank"], code="blank") def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ value = self.to_python(value) self.validate(value, model_instance) self.run_validators(value) return value def db_type_parameters(self, connection): return DictWrapper(self.__dict__, connection.ops.quote_name, "qn_") def db_check(self, connection): """ Return the database column check constraint for this field, for the provided connection. Works the same way as db_type() for the case that get_internal_type() does not map to a preexisting model field. """ data = self.db_type_parameters(connection) try: return ( connection.data_type_check_constraints[self.get_internal_type()] % data ) except KeyError: return None def db_type(self, connection): """ Return the database column data type for this field, for the provided connection. """ # The default implementation of this method looks at the # backend-specific data_types dictionary, looking up the field by its # "internal type". # # A Field class can implement the get_internal_type() method to specify # which *preexisting* Django Field class it's most similar to -- i.e., # a custom field might be represented by a TEXT column type, which is # the same as the TextField Django field type, which means the custom # field's get_internal_type() returns 'TextField'. # # But the limitation of the get_internal_type() / data_types approach # is that it cannot handle database column types that aren't already # mapped to one of the built-in Django field types. In this case, you # can implement db_type() instead of get_internal_type() to specify # exactly which wacky database column type you want to use. data = self.db_type_parameters(connection) try: column_type = connection.data_types[self.get_internal_type()] except KeyError: return None else: # column_type is either a single-parameter function or a string. if callable(column_type): return column_type(data) return column_type % data def rel_db_type(self, connection): """ Return the data type that a related field pointing to this field should use. For example, this method is called by ForeignKey and OneToOneField to determine its data type. """ return self.db_type(connection) def cast_db_type(self, connection): """Return the data type to use in the Cast() function.""" db_type = connection.ops.cast_data_types.get(self.get_internal_type()) if db_type: return db_type % self.db_type_parameters(connection) return self.db_type(connection) def db_parameters(self, connection): """ Extension of db_type(), providing a range of different return values (type, checks). This will look at db_type(), allowing custom model fields to override it. """ type_string = self.db_type(connection) check_string = self.db_check(connection) return { "type": type_string, "check": check_string, } def db_type_suffix(self, connection): return connection.data_types_suffix.get(self.get_internal_type()) def get_db_converters(self, connection): if hasattr(self, "from_db_value"): return [self.from_db_value] return [] @property def unique(self): return self._unique or self.primary_key @property def db_tablespace(self): return self._db_tablespace or settings.DEFAULT_INDEX_TABLESPACE @property def db_returning(self): """ Private API intended only to be used by Django itself. Currently only the PostgreSQL backend supports returning multiple fields on a model. """ return False def set_attributes_from_name(self, name): self.name = self.name or name self.attname, self.column = self.get_attname_column() self.concrete = self.column is not None if self.verbose_name is None and self.name: self.verbose_name = self.name.replace("_", " ") def contribute_to_class(self, cls, name, private_only=False): """ Register the field with the model class it belongs to. If private_only is True, create a separate instance of this field for every subclass of cls, even if cls is not an abstract model. """ self.set_attributes_from_name(name) self.model = cls cls._meta.add_field(self, private=private_only) if self.column: setattr(cls, self.attname, self.descriptor_class(self)) if self.choices is not None: # Don't override a get_FOO_display() method defined explicitly on # this class, but don't check methods derived from inheritance, to # allow overriding inherited choices. For more complex inheritance # structures users should override contribute_to_class(). if "get_%s_display" % self.name not in cls.__dict__: setattr( cls, "get_%s_display" % self.name, partialmethod(cls._get_FIELD_display, field=self), ) def get_filter_kwargs_for_object(self, obj): """ Return a dict that when passed as kwargs to self.model.filter(), would yield all instances having the same value for this field as obj has. """ return {self.name: getattr(obj, self.attname)} def get_attname(self): return self.name def get_attname_column(self): attname = self.get_attname() column = self.db_column or attname return attname, column def get_internal_type(self): return self.__class__.__name__ def pre_save(self, model_instance, add): """Return field's value just before saving.""" return getattr(model_instance, self.attname) def get_prep_value(self, value): """Perform preliminary non-db specific value checks and conversions.""" if isinstance(value, Promise): value = value._proxy____cast() return value def get_db_prep_value(self, value, connection, prepared=False): """ Return field's value prepared for interacting with the database backend. Used by the default implementations of get_db_prep_save(). """ if not prepared: value = self.get_prep_value(value) return value def get_db_prep_save(self, value, connection): """Return field's value prepared for saving into a database.""" if hasattr(value, "as_sql"): return value return self.get_db_prep_value(value, connection=connection, prepared=False) def has_default(self): """Return a boolean of whether this field has a default value.""" return self.default is not NOT_PROVIDED def get_default(self): """Return the default value for this field.""" return self._get_default() @cached_property def _get_default(self): if self.has_default(): if callable(self.default): return self.default return lambda: self.default if ( not self.empty_strings_allowed or self.null and not connection.features.interprets_empty_strings_as_nulls ): return return_None return str # return empty string def get_choices( self, include_blank=True, blank_choice=BLANK_CHOICE_DASH, limit_choices_to=None, ordering=(), ): """ Return choices with a default blank choices included, for use as <select> choices for this field. """ if self.choices is not None: choices = list(self.choices) if include_blank: blank_defined = any( choice in ("", None) for choice, _ in self.flatchoices ) if not blank_defined: choices = blank_choice + choices return choices rel_model = self.remote_field.model limit_choices_to = limit_choices_to or self.get_limit_choices_to() choice_func = operator.attrgetter( self.remote_field.get_related_field().attname if hasattr(self.remote_field, "get_related_field") else "pk" ) qs = rel_model._default_manager.complex_filter(limit_choices_to) if ordering: qs = qs.order_by(*ordering) return (blank_choice if include_blank else []) + [ (choice_func(x), str(x)) for x in qs ] def value_to_string(self, obj): """ Return a string value of this field from the passed obj. This is used by the serialization framework. """ return str(self.value_from_object(obj)) def _get_flatchoices(self): """Flattened version of choices tuple.""" if self.choices is None: return [] flat = [] for choice, value in self.choices: if isinstance(value, (list, tuple)): flat.extend(value) else: flat.append((choice, value)) return flat flatchoices = property(_get_flatchoices) def save_form_data(self, instance, data): setattr(instance, self.name, data) def formfield(self, form_class=None, choices_form_class=None, **kwargs): """Return a django.forms.Field instance for this field.""" defaults = { "required": not self.blank, "label": capfirst(self.verbose_name), "help_text": self.help_text, } if self.has_default(): if callable(self.default): defaults["initial"] = self.default defaults["show_hidden_initial"] = True else: defaults["initial"] = self.get_default() if self.choices is not None: # Fields with choices get special treatment. include_blank = self.blank or not ( self.has_default() or "initial" in kwargs ) defaults["choices"] = self.get_choices(include_blank=include_blank) defaults["coerce"] = self.to_python if self.null: defaults["empty_value"] = None if choices_form_class is not None: form_class = choices_form_class else: form_class = forms.TypedChoiceField # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that TypedChoiceField will understand. for k in list(kwargs): if k not in ( "coerce", "empty_value", "choices", "required", "widget", "label", "initial", "help_text", "error_messages", "show_hidden_initial", "disabled", ): del kwargs[k] defaults.update(kwargs) if form_class is None: form_class = forms.CharField return form_class(**defaults) def value_from_object(self, obj): """Return the value of this field in the given model instance.""" return getattr(obj, self.attname) class BooleanField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be either True or False."), "invalid_nullable": _("“%(value)s” value must be either True, False, or None."), } description = _("Boolean (Either True or False)") def get_internal_type(self): return "BooleanField" def to_python(self, value): if self.null and value in self.empty_values: return None if value in (True, False): # 1/0 are equal to True/False. bool() converts former to latter. return bool(value) if value in ("t", "True", "1"): return True if value in ("f", "False", "0"): return False raise exceptions.ValidationError( self.error_messages["invalid_nullable" if self.null else "invalid"], code="invalid", params={"value": value}, ) def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return self.to_python(value) def formfield(self, **kwargs): if self.choices is not None: include_blank = not (self.has_default() or "initial" in kwargs) defaults = {"choices": self.get_choices(include_blank=include_blank)} else: form_class = forms.NullBooleanField if self.null else forms.BooleanField # In HTML checkboxes, 'required' means "must be checked" which is # different from the choices case ("must select some value"). # required=False allows unchecked checkboxes. defaults = {"form_class": form_class, "required": False} return super().formfield(**{**defaults, **kwargs}) class CharField(Field): def __init__(self, *args, db_collation=None, **kwargs): super().__init__(*args, **kwargs) self.db_collation = db_collation if self.max_length is not None: self.validators.append(validators.MaxLengthValidator(self.max_length)) @property def description(self): if self.max_length is not None: return _("String (up to %(max_length)s)") else: return _("String (unlimited)") def check(self, **kwargs): databases = kwargs.get("databases") or [] return [ *super().check(**kwargs), *self._check_db_collation(databases), *self._check_max_length_attribute(**kwargs), ] def _check_max_length_attribute(self, **kwargs): if self.max_length is None: if ( connection.features.supports_unlimited_charfield or "supports_unlimited_charfield" in self.model._meta.required_db_features ): return [] return [ checks.Error( "CharFields must define a 'max_length' attribute.", obj=self, id="fields.E120", ) ] elif ( not isinstance(self.max_length, int) or isinstance(self.max_length, bool) or self.max_length <= 0 ): return [ checks.Error( "'max_length' must be a positive integer.", obj=self, id="fields.E121", ) ] else: return [] def _check_db_collation(self, databases): errors = [] for db in databases: if not router.allow_migrate_model(db, self.model): continue connection = connections[db] if not ( self.db_collation is None or "supports_collation_on_charfield" in self.model._meta.required_db_features or connection.features.supports_collation_on_charfield ): errors.append( checks.Error( "%s does not support a database collation on " "CharFields." % connection.display_name, obj=self, id="fields.E190", ), ) return errors def cast_db_type(self, connection): if self.max_length is None: return connection.ops.cast_char_field_without_max_length return super().cast_db_type(connection) def db_parameters(self, connection): db_params = super().db_parameters(connection) db_params["collation"] = self.db_collation return db_params def get_internal_type(self): return "CharField" def to_python(self, value): if isinstance(value, str) or value is None: return value return str(value) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): # Passing max_length to forms.CharField means that the value's length # will be validated twice. This is considered acceptable since we want # the value in the form field (to pass into widget for example). defaults = {"max_length": self.max_length} # TODO: Handle multiple backends with different feature flags. if self.null and not connection.features.interprets_empty_strings_as_nulls: defaults["empty_value"] = None defaults.update(kwargs) return super().formfield(**defaults) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.db_collation: kwargs["db_collation"] = self.db_collation return name, path, args, kwargs class CommaSeparatedIntegerField(CharField): default_validators = [validators.validate_comma_separated_integer_list] description = _("Comma-separated integers") system_check_removed_details = { "msg": ( "CommaSeparatedIntegerField is removed except for support in " "historical migrations." ), "hint": ( "Use CharField(validators=[validate_comma_separated_integer_list]) " "instead." ), "id": "fields.E901", } def _to_naive(value): if timezone.is_aware(value): value = timezone.make_naive(value, datetime.timezone.utc) return value def _get_naive_now(): return _to_naive(timezone.now()) class DateTimeCheckMixin: def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_mutually_exclusive_options(), *self._check_fix_default_value(), ] def _check_mutually_exclusive_options(self): # auto_now, auto_now_add, and default are mutually exclusive # options. The use of more than one of these options together # will trigger an Error mutually_exclusive_options = [ self.auto_now_add, self.auto_now, self.has_default(), ] enabled_options = [ option not in (None, False) for option in mutually_exclusive_options ].count(True) if enabled_options > 1: return [ checks.Error( "The options auto_now, auto_now_add, and default " "are mutually exclusive. Only one of these options " "may be present.", obj=self, id="fields.E160", ) ] else: return [] def _check_fix_default_value(self): return [] # Concrete subclasses use this in their implementations of # _check_fix_default_value(). def _check_if_value_fixed(self, value, now=None): """ Check if the given value appears to have been provided as a "fixed" time value, and include a warning in the returned list if it does. The value argument must be a date object or aware/naive datetime object. If now is provided, it must be a naive datetime object. """ if now is None: now = _get_naive_now() offset = datetime.timedelta(seconds=10) lower = now - offset upper = now + offset if isinstance(value, datetime.datetime): value = _to_naive(value) else: assert isinstance(value, datetime.date) lower = lower.date() upper = upper.date() if lower <= value <= upper: return [ checks.Warning( "Fixed default value provided.", hint=( "It seems you set a fixed date / time / datetime " "value as default for this field. This may not be " "what you want. If you want to have the current date " "as default, use `django.utils.timezone.now`" ), obj=self, id="fields.W161", ) ] return [] class DateField(DateTimeCheckMixin, Field): empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid date format. It must be " "in YYYY-MM-DD format." ), "invalid_date": _( "“%(value)s” value has the correct format (YYYY-MM-DD) " "but it is an invalid date." ), } description = _("Date (without time)") def __init__( self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs ): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs["editable"] = False kwargs["blank"] = True super().__init__(verbose_name, name, **kwargs) def _check_fix_default_value(self): """ Warn that using an actual date or datetime value is probably wrong; it's only evaluated on server startup. """ if not self.has_default(): return [] value = self.default if isinstance(value, datetime.datetime): value = _to_naive(value).date() elif isinstance(value, datetime.date): pass else: # No explicit date / datetime value -- no checks necessary return [] # At this point, value is a date object. return self._check_if_value_fixed(value) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.auto_now: kwargs["auto_now"] = True if self.auto_now_add: kwargs["auto_now_add"] = True if self.auto_now or self.auto_now_add: del kwargs["editable"] del kwargs["blank"] return name, path, args, kwargs def get_internal_type(self): return "DateField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): if settings.USE_TZ and timezone.is_aware(value): # Convert aware datetimes to the default time zone # before casting them to dates (#17742). default_timezone = timezone.get_default_timezone() value = timezone.make_naive(value, default_timezone) return value.date() if isinstance(value, datetime.date): return value try: parsed = parse_date(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_date"], code="invalid_date", params={"value": value}, ) raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.date.today() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) def contribute_to_class(self, cls, name, **kwargs): super().contribute_to_class(cls, name, **kwargs) if not self.null: setattr( cls, "get_next_by_%s" % self.name, partialmethod( cls._get_next_or_previous_by_FIELD, field=self, is_next=True ), ) setattr( cls, "get_previous_by_%s" % self.name, partialmethod( cls._get_next_or_previous_by_FIELD, field=self, is_next=False ), ) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts dates into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_datefield_value(value) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else val.isoformat() def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.DateField, **kwargs, } ) class DateTimeField(DateField): empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid format. It must be in " "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format." ), "invalid_date": _( "“%(value)s” value has the correct format " "(YYYY-MM-DD) but it is an invalid date." ), "invalid_datetime": _( "“%(value)s” value has the correct format " "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) " "but it is an invalid date/time." ), } description = _("Date (with time)") # __init__ is inherited from DateField def _check_fix_default_value(self): """ Warn that using an actual date or datetime value is probably wrong; it's only evaluated on server startup. """ if not self.has_default(): return [] value = self.default if isinstance(value, (datetime.datetime, datetime.date)): return self._check_if_value_fixed(value) # No explicit date / datetime value -- no checks necessary. return [] def get_internal_type(self): return "DateTimeField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): value = datetime.datetime(value.year, value.month, value.day) if settings.USE_TZ: # For backwards compatibility, interpret naive datetimes in # local time. This won't work during DST change, but we can't # do much about it, so we let the exceptions percolate up the # call stack. warnings.warn( "DateTimeField %s.%s received a naive datetime " "(%s) while time zone support is active." % (self.model.__name__, self.name, value), RuntimeWarning, ) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value try: parsed = parse_datetime(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_datetime"], code="invalid_datetime", params={"value": value}, ) try: parsed = parse_date(value) if parsed is not None: return datetime.datetime(parsed.year, parsed.month, parsed.day) except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_date"], code="invalid_date", params={"value": value}, ) raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = timezone.now() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) # contribute_to_class is inherited from DateField, it registers # get_next_by_FOO and get_prev_by_FOO def get_prep_value(self, value): value = super().get_prep_value(value) value = self.to_python(value) if value is not None and settings.USE_TZ and timezone.is_naive(value): # For backwards compatibility, interpret naive datetimes in local # time. This won't work during DST change, but we can't do much # about it, so we let the exceptions percolate up the call stack. try: name = "%s.%s" % (self.model.__name__, self.name) except AttributeError: name = "(unbound)" warnings.warn( "DateTimeField %s received a naive datetime (%s)" " while time zone support is active." % (name, value), RuntimeWarning, ) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value def get_db_prep_value(self, value, connection, prepared=False): # Casts datetimes into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_datetimefield_value(value) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else val.isoformat() def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.DateTimeField, **kwargs, } ) class DecimalField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be a decimal number."), } description = _("Decimal number") def __init__( self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs, ): self.max_digits, self.decimal_places = max_digits, decimal_places super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): errors = super().check(**kwargs) digits_errors = [ *self._check_decimal_places(), *self._check_max_digits(), ] if not digits_errors: errors.extend(self._check_decimal_places_and_max_digits(**kwargs)) else: errors.extend(digits_errors) return errors def _check_decimal_places(self): try: decimal_places = int(self.decimal_places) if decimal_places < 0: raise ValueError() except TypeError: return [ checks.Error( "DecimalFields must define a 'decimal_places' attribute.", obj=self, id="fields.E130", ) ] except ValueError: return [ checks.Error( "'decimal_places' must be a non-negative integer.", obj=self, id="fields.E131", ) ] else: return [] def _check_max_digits(self): try: max_digits = int(self.max_digits) if max_digits <= 0: raise ValueError() except TypeError: return [ checks.Error( "DecimalFields must define a 'max_digits' attribute.", obj=self, id="fields.E132", ) ] except ValueError: return [ checks.Error( "'max_digits' must be a positive integer.", obj=self, id="fields.E133", ) ] else: return [] def _check_decimal_places_and_max_digits(self, **kwargs): if int(self.decimal_places) > int(self.max_digits): return [ checks.Error( "'max_digits' must be greater or equal to 'decimal_places'.", obj=self, id="fields.E134", ) ] return [] @cached_property def validators(self): return super().validators + [ validators.DecimalValidator(self.max_digits, self.decimal_places) ] @cached_property def context(self): return decimal.Context(prec=self.max_digits) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.max_digits is not None: kwargs["max_digits"] = self.max_digits if self.decimal_places is not None: kwargs["decimal_places"] = self.decimal_places return name, path, args, kwargs def get_internal_type(self): return "DecimalField" def to_python(self, value): if value is None: return value try: if isinstance(value, float): decimal_value = self.context.create_decimal_from_float(value) else: decimal_value = decimal.Decimal(value) except (decimal.InvalidOperation, TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) if not decimal_value.is_finite(): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) return decimal_value def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) if hasattr(value, "as_sql"): return value return connection.ops.adapt_decimalfield_value( value, self.max_digits, self.decimal_places ) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): return super().formfield( **{ "max_digits": self.max_digits, "decimal_places": self.decimal_places, "form_class": forms.DecimalField, **kwargs, } ) class DurationField(Field): """ Store timedelta objects. Use interval on PostgreSQL, INTERVAL DAY TO SECOND on Oracle, and bigint of microseconds on other databases. """ empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid format. It must be in " "[DD] [[HH:]MM:]ss[.uuuuuu] format." ) } description = _("Duration") def get_internal_type(self): return "DurationField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.timedelta): return value try: parsed = parse_duration(value) except ValueError: pass else: if parsed is not None: return parsed raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def get_db_prep_value(self, value, connection, prepared=False): if connection.features.has_native_duration_field: return value if value is None: return None return duration_microseconds(value) def get_db_converters(self, connection): converters = [] if not connection.features.has_native_duration_field: converters.append(connection.ops.convert_durationfield_value) return converters + super().get_db_converters(connection) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else duration_string(val) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.DurationField, **kwargs, } ) class EmailField(CharField): default_validators = [validators.validate_email] description = _("Email address") def __init__(self, *args, **kwargs): # max_length=254 to be compliant with RFCs 3696 and 5321 kwargs.setdefault("max_length", 254) super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() # We do not exclude max_length if it matches default as we want to change # the default in future. return name, path, args, kwargs def formfield(self, **kwargs): # As with CharField, this will cause email validation to be performed # twice. return super().formfield( **{ "form_class": forms.EmailField, **kwargs, } ) class FilePathField(Field): description = _("File path") def __init__( self, verbose_name=None, name=None, path="", match=None, recursive=False, allow_files=True, allow_folders=False, **kwargs, ): self.path, self.match, self.recursive = path, match, recursive self.allow_files, self.allow_folders = allow_files, allow_folders kwargs.setdefault("max_length", 100) super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_allowing_files_or_folders(**kwargs), ] def _check_allowing_files_or_folders(self, **kwargs): if not self.allow_files and not self.allow_folders: return [ checks.Error( "FilePathFields must have either 'allow_files' or 'allow_folders' " "set to True.", obj=self, id="fields.E140", ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.path != "": kwargs["path"] = self.path if self.match is not None: kwargs["match"] = self.match if self.recursive is not False: kwargs["recursive"] = self.recursive if self.allow_files is not True: kwargs["allow_files"] = self.allow_files if self.allow_folders is not False: kwargs["allow_folders"] = self.allow_folders if kwargs.get("max_length") == 100: del kwargs["max_length"] return name, path, args, kwargs def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return str(value) def formfield(self, **kwargs): return super().formfield( **{ "path": self.path() if callable(self.path) else self.path, "match": self.match, "recursive": self.recursive, "form_class": forms.FilePathField, "allow_files": self.allow_files, "allow_folders": self.allow_folders, **kwargs, } ) def get_internal_type(self): return "FilePathField" class FloatField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be a float."), } description = _("Floating point number") def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None try: return float(value) except (TypeError, ValueError) as e: raise e.__class__( "Field '%s' expected a number but got %r." % (self.name, value), ) from e def get_internal_type(self): return "FloatField" def to_python(self, value): if value is None: return value try: return float(value) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.FloatField, **kwargs, } ) class IntegerField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be an integer."), } description = _("Integer") def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_max_length_warning(), ] def _check_max_length_warning(self): if self.max_length is not None: return [ checks.Warning( "'max_length' is ignored when used with %s." % self.__class__.__name__, hint="Remove 'max_length' from field", obj=self, id="fields.W122", ) ] return [] @cached_property def validators(self): # These validators can't be added at field initialization time since # they're based on values retrieved from `connection`. validators_ = super().validators internal_type = self.get_internal_type() min_value, max_value = connection.ops.integer_field_range(internal_type) if min_value is not None and not any( ( isinstance(validator, validators.MinValueValidator) and ( validator.limit_value() if callable(validator.limit_value) else validator.limit_value ) >= min_value ) for validator in validators_ ): validators_.append(validators.MinValueValidator(min_value)) if max_value is not None and not any( ( isinstance(validator, validators.MaxValueValidator) and ( validator.limit_value() if callable(validator.limit_value) else validator.limit_value ) <= max_value ) for validator in validators_ ): validators_.append(validators.MaxValueValidator(max_value)) return validators_ def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None try: return int(value) except (TypeError, ValueError) as e: raise e.__class__( "Field '%s' expected a number but got %r." % (self.name, value), ) from e def get_db_prep_value(self, value, connection, prepared=False): value = super().get_db_prep_value(value, connection, prepared) return connection.ops.adapt_integerfield_value(value, self.get_internal_type()) def get_internal_type(self): return "IntegerField" def to_python(self, value): if value is None: return value try: return int(value) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.IntegerField, **kwargs, } ) class BigIntegerField(IntegerField): description = _("Big (8 byte) integer") MAX_BIGINT = 9223372036854775807 def get_internal_type(self): return "BigIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": -BigIntegerField.MAX_BIGINT - 1, "max_value": BigIntegerField.MAX_BIGINT, **kwargs, } ) class SmallIntegerField(IntegerField): description = _("Small integer") def get_internal_type(self): return "SmallIntegerField" class IPAddressField(Field): empty_strings_allowed = False description = _("IPv4 address") system_check_removed_details = { "msg": ( "IPAddressField has been removed except for support in " "historical migrations." ), "hint": "Use GenericIPAddressField instead.", "id": "fields.E900", } def __init__(self, *args, **kwargs): kwargs["max_length"] = 15 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return str(value) def get_internal_type(self): return "IPAddressField" class GenericIPAddressField(Field): empty_strings_allowed = False description = _("IP address") default_error_messages = {} def __init__( self, verbose_name=None, name=None, protocol="both", unpack_ipv4=False, *args, **kwargs, ): self.unpack_ipv4 = unpack_ipv4 self.protocol = protocol ( self.default_validators, invalid_error_message, ) = validators.ip_address_validators(protocol, unpack_ipv4) self.default_error_messages["invalid"] = invalid_error_message kwargs["max_length"] = 39 super().__init__(verbose_name, name, *args, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_blank_and_null_values(**kwargs), ] def _check_blank_and_null_values(self, **kwargs): if not getattr(self, "null", False) and getattr(self, "blank", False): return [ checks.Error( "GenericIPAddressFields cannot have blank=True if null=False, " "as blank values are stored as nulls.", obj=self, id="fields.E150", ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.unpack_ipv4 is not False: kwargs["unpack_ipv4"] = self.unpack_ipv4 if self.protocol != "both": kwargs["protocol"] = self.protocol if kwargs.get("max_length") == 39: del kwargs["max_length"] return name, path, args, kwargs def get_internal_type(self): return "GenericIPAddressField" def to_python(self, value): if value is None: return None if not isinstance(value, str): value = str(value) value = value.strip() if ":" in value: return clean_ipv6_address( value, self.unpack_ipv4, self.error_messages["invalid"] ) return value def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_ipaddressfield_value(value) def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None if value and ":" in value: try: return clean_ipv6_address(value, self.unpack_ipv4) except exceptions.ValidationError: pass return str(value) def formfield(self, **kwargs): return super().formfield( **{ "protocol": self.protocol, "form_class": forms.GenericIPAddressField, **kwargs, } ) class NullBooleanField(BooleanField): default_error_messages = { "invalid": _("“%(value)s” value must be either None, True or False."), "invalid_nullable": _("“%(value)s” value must be either None, True or False."), } description = _("Boolean (Either True, False or None)") system_check_removed_details = { "msg": ( "NullBooleanField is removed except for support in historical " "migrations." ), "hint": "Use BooleanField(null=True, blank=True) instead.", "id": "fields.E903", } def __init__(self, *args, **kwargs): kwargs["null"] = True kwargs["blank"] = True super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["null"] del kwargs["blank"] return name, path, args, kwargs class PositiveIntegerRelDbTypeMixin: def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) if not hasattr(cls, "integer_field_class"): cls.integer_field_class = next( ( parent for parent in cls.__mro__[1:] if issubclass(parent, IntegerField) ), None, ) def rel_db_type(self, connection): """ Return the data type that a related field pointing to this field should use. In most cases, a foreign key pointing to a positive integer primary key will have an integer column data type but some databases (e.g. MySQL) have an unsigned integer type. In that case (related_fields_match_type=True), the primary key should return its db_type. """ if connection.features.related_fields_match_type: return self.db_type(connection) else: return self.integer_field_class().db_type(connection=connection) class PositiveBigIntegerField(PositiveIntegerRelDbTypeMixin, BigIntegerField): description = _("Positive big integer") def get_internal_type(self): return "PositiveBigIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": 0, **kwargs, } ) class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField): description = _("Positive integer") def get_internal_type(self): return "PositiveIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": 0, **kwargs, } ) class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, SmallIntegerField): description = _("Positive small integer") def get_internal_type(self): return "PositiveSmallIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": 0, **kwargs, } ) class SlugField(CharField): default_validators = [validators.validate_slug] description = _("Slug (up to %(max_length)s)") def __init__( self, *args, max_length=50, db_index=True, allow_unicode=False, **kwargs ): self.allow_unicode = allow_unicode if self.allow_unicode: self.default_validators = [validators.validate_unicode_slug] super().__init__(*args, max_length=max_length, db_index=db_index, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 50: del kwargs["max_length"] if self.db_index is False: kwargs["db_index"] = False else: del kwargs["db_index"] if self.allow_unicode is not False: kwargs["allow_unicode"] = self.allow_unicode return name, path, args, kwargs def get_internal_type(self): return "SlugField" def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.SlugField, "allow_unicode": self.allow_unicode, **kwargs, } ) class TextField(Field): description = _("Text") def __init__(self, *args, db_collation=None, **kwargs): super().__init__(*args, **kwargs) self.db_collation = db_collation def check(self, **kwargs): databases = kwargs.get("databases") or [] return [ *super().check(**kwargs), *self._check_db_collation(databases), ] def _check_db_collation(self, databases): errors = [] for db in databases: if not router.allow_migrate_model(db, self.model): continue connection = connections[db] if not ( self.db_collation is None or "supports_collation_on_textfield" in self.model._meta.required_db_features or connection.features.supports_collation_on_textfield ): errors.append( checks.Error( "%s does not support a database collation on " "TextFields." % connection.display_name, obj=self, id="fields.E190", ), ) return errors def db_parameters(self, connection): db_params = super().db_parameters(connection) db_params["collation"] = self.db_collation return db_params def get_internal_type(self): return "TextField" def to_python(self, value): if isinstance(value, str) or value is None: return value return str(value) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): # Passing max_length to forms.CharField means that the value's length # will be validated twice. This is considered acceptable since we want # the value in the form field (to pass into widget for example). return super().formfield( **{ "max_length": self.max_length, **({} if self.choices is not None else {"widget": forms.Textarea}), **kwargs, } ) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.db_collation: kwargs["db_collation"] = self.db_collation return name, path, args, kwargs class TimeField(DateTimeCheckMixin, Field): empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid format. It must be in " "HH:MM[:ss[.uuuuuu]] format." ), "invalid_time": _( "“%(value)s” value has the correct format " "(HH:MM[:ss[.uuuuuu]]) but it is an invalid time." ), } description = _("Time") def __init__( self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs ): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs["editable"] = False kwargs["blank"] = True super().__init__(verbose_name, name, **kwargs) def _check_fix_default_value(self): """ Warn that using an actual date or datetime value is probably wrong; it's only evaluated on server startup. """ if not self.has_default(): return [] value = self.default if isinstance(value, datetime.datetime): now = None elif isinstance(value, datetime.time): now = _get_naive_now() # This will not use the right date in the race condition where now # is just before the date change and value is just past 0:00. value = datetime.datetime.combine(now.date(), value) else: # No explicit time / datetime value -- no checks necessary return [] # At this point, value is a datetime object. return self._check_if_value_fixed(value, now=now) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.auto_now is not False: kwargs["auto_now"] = self.auto_now if self.auto_now_add is not False: kwargs["auto_now_add"] = self.auto_now_add if self.auto_now or self.auto_now_add: del kwargs["blank"] del kwargs["editable"] return name, path, args, kwargs def get_internal_type(self): return "TimeField" def to_python(self, value): if value is None: return None if isinstance(value, datetime.time): return value if isinstance(value, datetime.datetime): # Not usually a good idea to pass in a datetime here (it loses # information), but this can be a side-effect of interacting with a # database backend (e.g. Oracle), so we'll be accommodating. return value.time() try: parsed = parse_time(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_time"], code="invalid_time", params={"value": value}, ) raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.datetime.now().time() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts times into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_timefield_value(value) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else val.isoformat() def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.TimeField, **kwargs, } ) class URLField(CharField): default_validators = [validators.URLValidator()] description = _("URL") def __init__(self, verbose_name=None, name=None, **kwargs): kwargs.setdefault("max_length", 200) super().__init__(verbose_name, name, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 200: del kwargs["max_length"] return name, path, args, kwargs def formfield(self, **kwargs): # As with CharField, this will cause URL validation to be performed # twice. return super().formfield( **{ "form_class": forms.URLField, **kwargs, } ) class BinaryField(Field): description = _("Raw binary data") empty_values = [None, b""] def __init__(self, *args, **kwargs): kwargs.setdefault("editable", False) super().__init__(*args, **kwargs) if self.max_length is not None: self.validators.append(validators.MaxLengthValidator(self.max_length)) def check(self, **kwargs): return [*super().check(**kwargs), *self._check_str_default_value()] def _check_str_default_value(self): if self.has_default() and isinstance(self.default, str): return [ checks.Error( "BinaryField's default cannot be a string. Use bytes " "content instead.", obj=self, id="fields.E170", ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.editable: kwargs["editable"] = True else: del kwargs["editable"] return name, path, args, kwargs def get_internal_type(self): return "BinaryField" def get_placeholder(self, value, compiler, connection): return connection.ops.binary_placeholder_sql(value) def get_default(self): if self.has_default() and not callable(self.default): return self.default default = super().get_default() if default == "": return b"" return default def get_db_prep_value(self, value, connection, prepared=False): value = super().get_db_prep_value(value, connection, prepared) if value is not None: return connection.Database.Binary(value) return value def value_to_string(self, obj): """Binary data is serialized as base64""" return b64encode(self.value_from_object(obj)).decode("ascii") def to_python(self, value): # If it's a string, it should be base64-encoded data if isinstance(value, str): return memoryview(b64decode(value.encode("ascii"))) return value class UUIDField(Field): default_error_messages = { "invalid": _("“%(value)s” is not a valid UUID."), } description = _("Universally unique identifier") empty_strings_allowed = False def __init__(self, verbose_name=None, **kwargs): kwargs["max_length"] = 32 super().__init__(verbose_name, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs def get_internal_type(self): return "UUIDField" def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): if value is None: return None if not isinstance(value, uuid.UUID): value = self.to_python(value) if connection.features.has_native_uuid_field: return value return value.hex def to_python(self, value): if value is not None and not isinstance(value, uuid.UUID): input_form = "int" if isinstance(value, int) else "hex" try: return uuid.UUID(**{input_form: value}) except (AttributeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) return value def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.UUIDField, **kwargs, } ) class AutoFieldMixin: db_returning = True def __init__(self, *args, **kwargs): kwargs["blank"] = True super().__init__(*args, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_primary_key(), ] def _check_primary_key(self): if not self.primary_key: return [ checks.Error( "AutoFields must set primary_key=True.", obj=self, id="fields.E100", ), ] else: return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["blank"] kwargs["primary_key"] = True return name, path, args, kwargs def validate(self, value, model_instance): pass def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) value = connection.ops.validate_autopk_value(value) return value def contribute_to_class(self, cls, name, **kwargs): if cls._meta.auto_field: raise ValueError( "Model %s can't have more than one auto-generated field." % cls._meta.label ) super().contribute_to_class(cls, name, **kwargs) cls._meta.auto_field = self def formfield(self, **kwargs): return None class AutoFieldMeta(type): """ Metaclass to maintain backward inheritance compatibility for AutoField. It is intended that AutoFieldMixin become public API when it is possible to create a non-integer automatically-generated field using column defaults stored in the database. In many areas Django also relies on using isinstance() to check for an automatically-generated field as a subclass of AutoField. A new flag needs to be implemented on Field to be used instead. When these issues have been addressed, this metaclass could be used to deprecate inheritance from AutoField and use of isinstance() with AutoField for detecting automatically-generated fields. """ @property def _subclasses(self): return (BigAutoField, SmallAutoField) def __instancecheck__(self, instance): return isinstance(instance, self._subclasses) or super().__instancecheck__( instance ) def __subclasscheck__(self, subclass): return issubclass(subclass, self._subclasses) or super().__subclasscheck__( subclass ) class AutoField(AutoFieldMixin, IntegerField, metaclass=AutoFieldMeta): def get_internal_type(self): return "AutoField" def rel_db_type(self, connection): return IntegerField().db_type(connection=connection) class BigAutoField(AutoFieldMixin, BigIntegerField): def get_internal_type(self): return "BigAutoField" def rel_db_type(self, connection): return BigIntegerField().db_type(connection=connection) class SmallAutoField(AutoFieldMixin, SmallIntegerField): def get_internal_type(self): return "SmallAutoField" def rel_db_type(self, connection): return SmallIntegerField().db_type(connection=connection)
2fa65532ade155c1756624b295ba1f3b4fb9eeff1b45ba62c715cd5487b95efe
import functools import inspect import warnings from functools import partial from django import forms from django.apps import apps from django.conf import SettingsReference, settings from django.core import checks, exceptions from django.db import connection, router from django.db.backends import utils from django.db.models import Q from django.db.models.constants import LOOKUP_SEP from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL from django.db.models.query_utils import PathInfo from django.db.models.utils import make_model_tuple from django.utils.deprecation import RemovedInDjango60Warning from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _ from . import Field from .mixins import FieldCacheMixin from .related_descriptors import ( ForeignKeyDeferredAttribute, ForwardManyToOneDescriptor, ForwardOneToOneDescriptor, ManyToManyDescriptor, ReverseManyToOneDescriptor, ReverseOneToOneDescriptor, ) from .related_lookups import ( RelatedExact, RelatedGreaterThan, RelatedGreaterThanOrEqual, RelatedIn, RelatedIsNull, RelatedLessThan, RelatedLessThanOrEqual, ) from .reverse_related import ForeignObjectRel, ManyToManyRel, ManyToOneRel, OneToOneRel RECURSIVE_RELATIONSHIP_CONSTANT = "self" def resolve_relation(scope_model, relation): """ Transform relation into a model or fully-qualified model string of the form "app_label.ModelName", relative to scope_model. The relation argument can be: * RECURSIVE_RELATIONSHIP_CONSTANT, i.e. the string "self", in which case the model argument will be returned. * A bare model name without an app_label, in which case scope_model's app_label will be prepended. * An "app_label.ModelName" string. * A model class, which will be returned unchanged. """ # Check for recursive relations if relation == RECURSIVE_RELATIONSHIP_CONSTANT: relation = scope_model # Look for an "app.Model" relation if isinstance(relation, str): if "." not in relation: relation = "%s.%s" % (scope_model._meta.app_label, relation) return relation def lazy_related_operation(function, model, *related_models, **kwargs): """ Schedule `function` to be called once `model` and all `related_models` have been imported and registered with the app registry. `function` will be called with the newly-loaded model classes as its positional arguments, plus any optional keyword arguments. The `model` argument must be a model class. Each subsequent positional argument is another model, or a reference to another model - see `resolve_relation()` for the various forms these may take. Any relative references will be resolved relative to `model`. This is a convenience wrapper for `Apps.lazy_model_operation` - the app registry model used is the one found in `model._meta.apps`. """ models = [model] + [resolve_relation(model, rel) for rel in related_models] model_keys = (make_model_tuple(m) for m in models) apps = model._meta.apps return apps.lazy_model_operation(partial(function, **kwargs), *model_keys) class RelatedField(FieldCacheMixin, Field): """Base class that all relational fields inherit from.""" # Field flags one_to_many = False one_to_one = False many_to_many = False many_to_one = False def __init__( self, related_name=None, related_query_name=None, limit_choices_to=None, **kwargs, ): self._related_name = related_name self._related_query_name = related_query_name self._limit_choices_to = limit_choices_to super().__init__(**kwargs) @cached_property def related_model(self): # Can't cache this property until all the models are loaded. apps.check_models_ready() return self.remote_field.model def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_related_name_is_valid(), *self._check_related_query_name_is_valid(), *self._check_relation_model_exists(), *self._check_referencing_to_swapped_model(), *self._check_clashes(), ] def _check_related_name_is_valid(self): import keyword related_name = self.remote_field.related_name if related_name is None: return [] is_valid_id = ( not keyword.iskeyword(related_name) and related_name.isidentifier() ) if not (is_valid_id or related_name.endswith("+")): return [ checks.Error( "The name '%s' is invalid related_name for field %s.%s" % ( self.remote_field.related_name, self.model._meta.object_name, self.name, ), hint=( "Related name must be a valid Python identifier or end with a " "'+'" ), obj=self, id="fields.E306", ) ] return [] def _check_related_query_name_is_valid(self): if self.remote_field.is_hidden(): return [] rel_query_name = self.related_query_name() errors = [] if rel_query_name.endswith("_"): errors.append( checks.Error( "Reverse query name '%s' must not end with an underscore." % rel_query_name, hint=( "Add or change a related_name or related_query_name " "argument for this field." ), obj=self, id="fields.E308", ) ) if LOOKUP_SEP in rel_query_name: errors.append( checks.Error( "Reverse query name '%s' must not contain '%s'." % (rel_query_name, LOOKUP_SEP), hint=( "Add or change a related_name or related_query_name " "argument for this field." ), obj=self, id="fields.E309", ) ) return errors def _check_relation_model_exists(self): rel_is_missing = self.remote_field.model not in self.opts.apps.get_models() rel_is_string = isinstance(self.remote_field.model, str) model_name = ( self.remote_field.model if rel_is_string else self.remote_field.model._meta.object_name ) if rel_is_missing and ( rel_is_string or not self.remote_field.model._meta.swapped ): return [ checks.Error( "Field defines a relation with model '%s', which is either " "not installed, or is abstract." % model_name, obj=self, id="fields.E300", ) ] return [] def _check_referencing_to_swapped_model(self): if ( self.remote_field.model not in self.opts.apps.get_models() and not isinstance(self.remote_field.model, str) and self.remote_field.model._meta.swapped ): return [ checks.Error( "Field defines a relation with the model '%s', which has " "been swapped out." % self.remote_field.model._meta.label, hint="Update the relation to point at 'settings.%s'." % self.remote_field.model._meta.swappable, obj=self, id="fields.E301", ) ] return [] def _check_clashes(self): """Check accessor and reverse query name clashes.""" from django.db.models.base import ModelBase errors = [] opts = self.model._meta # f.remote_field.model may be a string instead of a model. Skip if # model name is not resolved. if not isinstance(self.remote_field.model, ModelBase): return [] # Consider that we are checking field `Model.foreign` and the models # are: # # class Target(models.Model): # model = models.IntegerField() # model_set = models.IntegerField() # # class Model(models.Model): # foreign = models.ForeignKey(Target) # m2m = models.ManyToManyField(Target) # rel_opts.object_name == "Target" rel_opts = self.remote_field.model._meta # If the field doesn't install a backward relation on the target model # (so `is_hidden` returns True), then there are no clashes to check # and we can skip these fields. rel_is_hidden = self.remote_field.is_hidden() rel_name = self.remote_field.get_accessor_name() # i. e. "model_set" rel_query_name = self.related_query_name() # i. e. "model" # i.e. "app_label.Model.field". field_name = "%s.%s" % (opts.label, self.name) # Check clashes between accessor or reverse query name of `field` # and any other field name -- i.e. accessor for Model.foreign is # model_set and it clashes with Target.model_set. potential_clashes = rel_opts.fields + rel_opts.many_to_many for clash_field in potential_clashes: # i.e. "app_label.Target.model_set". clash_name = "%s.%s" % (rel_opts.label, clash_field.name) if not rel_is_hidden and clash_field.name == rel_name: errors.append( checks.Error( f"Reverse accessor '{rel_opts.object_name}.{rel_name}' " f"for '{field_name}' clashes with field name " f"'{clash_name}'.", hint=( "Rename field '%s', or add/change a related_name " "argument to the definition for field '%s'." ) % (clash_name, field_name), obj=self, id="fields.E302", ) ) if clash_field.name == rel_query_name: errors.append( checks.Error( "Reverse query name for '%s' clashes with field name '%s'." % (field_name, clash_name), hint=( "Rename field '%s', or add/change a related_name " "argument to the definition for field '%s'." ) % (clash_name, field_name), obj=self, id="fields.E303", ) ) # Check clashes between accessors/reverse query names of `field` and # any other field accessor -- i. e. Model.foreign accessor clashes with # Model.m2m accessor. potential_clashes = (r for r in rel_opts.related_objects if r.field is not self) for clash_field in potential_clashes: # i.e. "app_label.Model.m2m". clash_name = "%s.%s" % ( clash_field.related_model._meta.label, clash_field.field.name, ) if not rel_is_hidden and clash_field.get_accessor_name() == rel_name: errors.append( checks.Error( f"Reverse accessor '{rel_opts.object_name}.{rel_name}' " f"for '{field_name}' clashes with reverse accessor for " f"'{clash_name}'.", hint=( "Add or change a related_name argument " "to the definition for '%s' or '%s'." ) % (field_name, clash_name), obj=self, id="fields.E304", ) ) if clash_field.get_accessor_name() == rel_query_name: errors.append( checks.Error( "Reverse query name for '%s' clashes with reverse query name " "for '%s'." % (field_name, clash_name), hint=( "Add or change a related_name argument " "to the definition for '%s' or '%s'." ) % (field_name, clash_name), obj=self, id="fields.E305", ) ) return errors def db_type(self, connection): # By default related field will not have a column as it relates to # columns from another table. return None def contribute_to_class(self, cls, name, private_only=False, **kwargs): super().contribute_to_class(cls, name, private_only=private_only, **kwargs) self.opts = cls._meta if not cls._meta.abstract: if self.remote_field.related_name: related_name = self.remote_field.related_name else: related_name = self.opts.default_related_name if related_name: related_name %= { "class": cls.__name__.lower(), "model_name": cls._meta.model_name.lower(), "app_label": cls._meta.app_label.lower(), } self.remote_field.related_name = related_name if self.remote_field.related_query_name: related_query_name = self.remote_field.related_query_name % { "class": cls.__name__.lower(), "app_label": cls._meta.app_label.lower(), } self.remote_field.related_query_name = related_query_name def resolve_related_class(model, related, field): field.remote_field.model = related field.do_related_class(related, model) lazy_related_operation( resolve_related_class, cls, self.remote_field.model, field=self ) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self._limit_choices_to: kwargs["limit_choices_to"] = self._limit_choices_to if self._related_name is not None: kwargs["related_name"] = self._related_name if self._related_query_name is not None: kwargs["related_query_name"] = self._related_query_name return name, path, args, kwargs def get_forward_related_filter(self, obj): """ Return the keyword arguments that when supplied to self.model.object.filter(), would select all instances related through this field to the remote obj. This is used to build the querysets returned by related descriptors. obj is an instance of self.related_field.model. """ return { "%s__%s" % (self.name, rh_field.name): getattr(obj, rh_field.attname) for _, rh_field in self.related_fields } def get_reverse_related_filter(self, obj): """ Complement to get_forward_related_filter(). Return the keyword arguments that when passed to self.related_field.model.object.filter() select all instances of self.related_field.model related through this field to obj. obj is an instance of self.model. """ base_q = Q.create( [ (rh_field.attname, getattr(obj, lh_field.attname)) for lh_field, rh_field in self.related_fields ] ) descriptor_filter = self.get_extra_descriptor_filter(obj) if isinstance(descriptor_filter, dict): return base_q & Q(**descriptor_filter) elif descriptor_filter: return base_q & descriptor_filter return base_q @property def swappable_setting(self): """ Get the setting that this is powered from for swapping, or None if it's not swapped in / marked with swappable=False. """ if self.swappable: # Work out string form of "to" if isinstance(self.remote_field.model, str): to_string = self.remote_field.model else: to_string = self.remote_field.model._meta.label return apps.get_swappable_settings_name(to_string) return None def set_attributes_from_rel(self): self.name = self.name or ( self.remote_field.model._meta.model_name + "_" + self.remote_field.model._meta.pk.name ) if self.verbose_name is None: self.verbose_name = self.remote_field.model._meta.verbose_name self.remote_field.set_field_name() def do_related_class(self, other, cls): self.set_attributes_from_rel() self.contribute_to_related_class(other, self.remote_field) def get_limit_choices_to(self): """ Return ``limit_choices_to`` for this model field. If it is a callable, it will be invoked and the result will be returned. """ if callable(self.remote_field.limit_choices_to): return self.remote_field.limit_choices_to() return self.remote_field.limit_choices_to def formfield(self, **kwargs): """ Pass ``limit_choices_to`` to the field being constructed. Only passes it if there is a type that supports related fields. This is a similar strategy used to pass the ``queryset`` to the field being constructed. """ defaults = {} if hasattr(self.remote_field, "get_related_field"): # If this is a callable, do not invoke it here. Just pass # it in the defaults for when the form class will later be # instantiated. limit_choices_to = self.remote_field.limit_choices_to defaults.update( { "limit_choices_to": limit_choices_to, } ) defaults.update(kwargs) return super().formfield(**defaults) def related_query_name(self): """ Define the name that can be used to identify this related object in a table-spanning query. """ return ( self.remote_field.related_query_name or self.remote_field.related_name or self.opts.model_name ) @property def target_field(self): """ When filtering against this relation, return the field on the remote model against which the filtering should happen. """ target_fields = self.path_infos[-1].target_fields if len(target_fields) > 1: raise exceptions.FieldError( "The relation has multiple target fields, but only single target field " "was asked for" ) return target_fields[0] def get_cache_name(self): return self.name class ForeignObject(RelatedField): """ Abstraction of the ForeignKey relation to support multi-column relations. """ # Field flags many_to_many = False many_to_one = True one_to_many = False one_to_one = False requires_unique_target = True related_accessor_class = ReverseManyToOneDescriptor forward_related_accessor_class = ForwardManyToOneDescriptor rel_class = ForeignObjectRel def __init__( self, to, on_delete, from_fields, to_fields, rel=None, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, swappable=True, **kwargs, ): if rel is None: rel = self.rel_class( self, to, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, parent_link=parent_link, on_delete=on_delete, ) super().__init__( rel=rel, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, **kwargs, ) self.from_fields = from_fields self.to_fields = to_fields self.swappable = swappable def __copy__(self): obj = super().__copy__() # Remove any cached PathInfo values. obj.__dict__.pop("path_infos", None) obj.__dict__.pop("reverse_path_infos", None) return obj def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_to_fields_exist(), *self._check_unique_target(), ] def _check_to_fields_exist(self): # Skip nonexistent models. if isinstance(self.remote_field.model, str): return [] errors = [] for to_field in self.to_fields: if to_field: try: self.remote_field.model._meta.get_field(to_field) except exceptions.FieldDoesNotExist: errors.append( checks.Error( "The to_field '%s' doesn't exist on the related " "model '%s'." % (to_field, self.remote_field.model._meta.label), obj=self, id="fields.E312", ) ) return errors def _check_unique_target(self): rel_is_string = isinstance(self.remote_field.model, str) if rel_is_string or not self.requires_unique_target: return [] try: self.foreign_related_fields except exceptions.FieldDoesNotExist: return [] if not self.foreign_related_fields: return [] unique_foreign_fields = { frozenset([f.name]) for f in self.remote_field.model._meta.get_fields() if getattr(f, "unique", False) } unique_foreign_fields.update( {frozenset(ut) for ut in self.remote_field.model._meta.unique_together} ) unique_foreign_fields.update( { frozenset(uc.fields) for uc in self.remote_field.model._meta.total_unique_constraints } ) foreign_fields = {f.name for f in self.foreign_related_fields} has_unique_constraint = any(u <= foreign_fields for u in unique_foreign_fields) if not has_unique_constraint and len(self.foreign_related_fields) > 1: field_combination = ", ".join( "'%s'" % rel_field.name for rel_field in self.foreign_related_fields ) model_name = self.remote_field.model.__name__ return [ checks.Error( "No subset of the fields %s on model '%s' is unique." % (field_combination, model_name), hint=( "Mark a single field as unique=True or add a set of " "fields to a unique constraint (via unique_together " "or a UniqueConstraint (without condition) in the " "model Meta.constraints)." ), obj=self, id="fields.E310", ) ] elif not has_unique_constraint: field_name = self.foreign_related_fields[0].name model_name = self.remote_field.model.__name__ return [ checks.Error( "'%s.%s' must be unique because it is referenced by " "a foreign key." % (model_name, field_name), hint=( "Add unique=True to this field or add a " "UniqueConstraint (without condition) in the model " "Meta.constraints." ), obj=self, id="fields.E311", ) ] else: return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() kwargs["on_delete"] = self.remote_field.on_delete kwargs["from_fields"] = self.from_fields kwargs["to_fields"] = self.to_fields if self.remote_field.parent_link: kwargs["parent_link"] = self.remote_field.parent_link if isinstance(self.remote_field.model, str): if "." in self.remote_field.model: app_label, model_name = self.remote_field.model.split(".") kwargs["to"] = "%s.%s" % (app_label, model_name.lower()) else: kwargs["to"] = self.remote_field.model.lower() else: kwargs["to"] = self.remote_field.model._meta.label_lower # If swappable is True, then see if we're actually pointing to the target # of a swap. swappable_setting = self.swappable_setting if swappable_setting is not None: # If it's already a settings reference, error if hasattr(kwargs["to"], "setting_name"): if kwargs["to"].setting_name != swappable_setting: raise ValueError( "Cannot deconstruct a ForeignKey pointing to a model " "that is swapped in place of more than one model (%s and %s)" % (kwargs["to"].setting_name, swappable_setting) ) # Set it kwargs["to"] = SettingsReference( kwargs["to"], swappable_setting, ) return name, path, args, kwargs def resolve_related_fields(self): if not self.from_fields or len(self.from_fields) != len(self.to_fields): raise ValueError( "Foreign Object from and to fields must be the same non-zero length" ) if isinstance(self.remote_field.model, str): raise ValueError( "Related model %r cannot be resolved" % self.remote_field.model ) related_fields = [] for index in range(len(self.from_fields)): from_field_name = self.from_fields[index] to_field_name = self.to_fields[index] from_field = ( self if from_field_name == RECURSIVE_RELATIONSHIP_CONSTANT else self.opts.get_field(from_field_name) ) to_field = ( self.remote_field.model._meta.pk if to_field_name is None else self.remote_field.model._meta.get_field(to_field_name) ) related_fields.append((from_field, to_field)) return related_fields @cached_property def related_fields(self): return self.resolve_related_fields() @cached_property def reverse_related_fields(self): return [(rhs_field, lhs_field) for lhs_field, rhs_field in self.related_fields] @cached_property def local_related_fields(self): return tuple(lhs_field for lhs_field, rhs_field in self.related_fields) @cached_property def foreign_related_fields(self): return tuple( rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field ) def get_local_related_value(self, instance): return self.get_instance_value_for_fields(instance, self.local_related_fields) def get_foreign_related_value(self, instance): return self.get_instance_value_for_fields(instance, self.foreign_related_fields) @staticmethod def get_instance_value_for_fields(instance, fields): ret = [] opts = instance._meta for field in fields: # Gotcha: in some cases (like fixture loading) a model can have # different values in parent_ptr_id and parent's id. So, use # instance.pk (that is, parent_ptr_id) when asked for instance.id. if field.primary_key: possible_parent_link = opts.get_ancestor_link(field.model) if ( not possible_parent_link or possible_parent_link.primary_key or possible_parent_link.model._meta.abstract ): ret.append(instance.pk) continue ret.append(getattr(instance, field.attname)) return tuple(ret) def get_attname_column(self): attname, column = super().get_attname_column() return attname, None def get_joining_columns(self, reverse_join=False): warnings.warn( "ForeignObject.get_joining_columns() is deprecated. Use " "get_joining_fields() instead.", RemovedInDjango60Warning, ) source = self.reverse_related_fields if reverse_join else self.related_fields return tuple( (lhs_field.column, rhs_field.column) for lhs_field, rhs_field in source ) def get_reverse_joining_columns(self): warnings.warn( "ForeignObject.get_reverse_joining_columns() is deprecated. Use " "get_reverse_joining_fields() instead.", RemovedInDjango60Warning, ) return self.get_joining_columns(reverse_join=True) def get_joining_fields(self, reverse_join=False): return tuple( self.reverse_related_fields if reverse_join else self.related_fields ) def get_reverse_joining_fields(self): return self.get_joining_fields(reverse_join=True) def get_extra_descriptor_filter(self, instance): """ Return an extra filter condition for related object fetching when user does 'instance.fieldname', that is the extra filter is used in the descriptor of the field. The filter should be either a dict usable in .filter(**kwargs) call or a Q-object. The condition will be ANDed together with the relation's joining columns. A parallel method is get_extra_restriction() which is used in JOIN and subquery conditions. """ return {} def get_extra_restriction(self, alias, related_alias): """ Return a pair condition used for joining and subquery pushdown. The condition is something that responds to as_sql(compiler, connection) method. Note that currently referring both the 'alias' and 'related_alias' will not work in some conditions, like subquery pushdown. A parallel method is get_extra_descriptor_filter() which is used in instance.fieldname related object fetching. """ return None def get_path_info(self, filtered_relation=None): """Get path from this field to the related model.""" opts = self.remote_field.model._meta from_opts = self.model._meta return [ PathInfo( from_opts=from_opts, to_opts=opts, target_fields=self.foreign_related_fields, join_field=self, m2m=False, direct=True, filtered_relation=filtered_relation, ) ] @cached_property def path_infos(self): return self.get_path_info() def get_reverse_path_info(self, filtered_relation=None): """Get path from the related model to this field's model.""" opts = self.model._meta from_opts = self.remote_field.model._meta return [ PathInfo( from_opts=from_opts, to_opts=opts, target_fields=(opts.pk,), join_field=self.remote_field, m2m=not self.unique, direct=False, filtered_relation=filtered_relation, ) ] @cached_property def reverse_path_infos(self): return self.get_reverse_path_info() @classmethod @functools.cache def get_class_lookups(cls): bases = inspect.getmro(cls) bases = bases[: bases.index(ForeignObject) + 1] class_lookups = [parent.__dict__.get("class_lookups", {}) for parent in bases] return cls.merge_dicts(class_lookups) def contribute_to_class(self, cls, name, private_only=False, **kwargs): super().contribute_to_class(cls, name, private_only=private_only, **kwargs) setattr(cls, self.name, self.forward_related_accessor_class(self)) def contribute_to_related_class(self, cls, related): # Internal FK's - i.e., those with a related name ending with '+' - # and swapped models don't get a related descriptor. if ( not self.remote_field.is_hidden() and not related.related_model._meta.swapped ): setattr( cls._meta.concrete_model, related.get_accessor_name(), self.related_accessor_class(related), ) # While 'limit_choices_to' might be a callable, simply pass # it along for later - this is too early because it's still # model load time. if self.remote_field.limit_choices_to: cls._meta.related_fkey_lookups.append( self.remote_field.limit_choices_to ) ForeignObject.register_lookup(RelatedIn) ForeignObject.register_lookup(RelatedExact) ForeignObject.register_lookup(RelatedLessThan) ForeignObject.register_lookup(RelatedGreaterThan) ForeignObject.register_lookup(RelatedGreaterThanOrEqual) ForeignObject.register_lookup(RelatedLessThanOrEqual) ForeignObject.register_lookup(RelatedIsNull) class ForeignKey(ForeignObject): """ Provide a many-to-one relation by adding a column to the local model to hold the remote value. By default ForeignKey will target the pk of the remote model but this behavior can be changed by using the ``to_field`` argument. """ descriptor_class = ForeignKeyDeferredAttribute # Field flags many_to_many = False many_to_one = True one_to_many = False one_to_one = False rel_class = ManyToOneRel empty_strings_allowed = False default_error_messages = { "invalid": _("%(model)s instance with %(field)s %(value)r does not exist.") } description = _("Foreign Key (type determined by related field)") def __init__( self, to, on_delete, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, to_field=None, db_constraint=True, **kwargs, ): try: to._meta.model_name except AttributeError: if not isinstance(to, str): raise TypeError( "%s(%r) is invalid. First parameter to ForeignKey must be " "either a model, a model name, or the string %r" % ( self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT, ) ) else: # For backwards compatibility purposes, we need to *try* and set # the to_field during FK construction. It won't be guaranteed to # be correct until contribute_to_class is called. Refs #12190. to_field = to_field or (to._meta.pk and to._meta.pk.name) if not callable(on_delete): raise TypeError("on_delete must be callable.") kwargs["rel"] = self.rel_class( self, to, to_field, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, parent_link=parent_link, on_delete=on_delete, ) kwargs.setdefault("db_index", True) super().__init__( to, on_delete, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, from_fields=[RECURSIVE_RELATIONSHIP_CONSTANT], to_fields=[to_field], **kwargs, ) self.db_constraint = db_constraint def __class_getitem__(cls, *args, **kwargs): return cls def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_on_delete(), *self._check_unique(), ] def _check_on_delete(self): on_delete = getattr(self.remote_field, "on_delete", None) if on_delete == SET_NULL and not self.null: return [ checks.Error( "Field specifies on_delete=SET_NULL, but cannot be null.", hint=( "Set null=True argument on the field, or change the on_delete " "rule." ), obj=self, id="fields.E320", ) ] elif on_delete == SET_DEFAULT and not self.has_default(): return [ checks.Error( "Field specifies on_delete=SET_DEFAULT, but has no default value.", hint="Set a default value, or change the on_delete rule.", obj=self, id="fields.E321", ) ] else: return [] def _check_unique(self, **kwargs): return ( [ checks.Warning( "Setting unique=True on a ForeignKey has the same effect as using " "a OneToOneField.", hint=( "ForeignKey(unique=True) is usually better served by a " "OneToOneField." ), obj=self, id="fields.W342", ) ] if self.unique else [] ) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["to_fields"] del kwargs["from_fields"] # Handle the simpler arguments if self.db_index: del kwargs["db_index"] else: kwargs["db_index"] = False if self.db_constraint is not True: kwargs["db_constraint"] = self.db_constraint # Rel needs more work. to_meta = getattr(self.remote_field.model, "_meta", None) if self.remote_field.field_name and ( not to_meta or (to_meta.pk and self.remote_field.field_name != to_meta.pk.name) ): kwargs["to_field"] = self.remote_field.field_name return name, path, args, kwargs def to_python(self, value): return self.target_field.to_python(value) @property def target_field(self): return self.foreign_related_fields[0] def validate(self, value, model_instance): if self.remote_field.parent_link: return super().validate(value, model_instance) if value is None: return using = router.db_for_read(self.remote_field.model, instance=model_instance) qs = self.remote_field.model._base_manager.using(using).filter( **{self.remote_field.field_name: value} ) qs = qs.complex_filter(self.get_limit_choices_to()) if not qs.exists(): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={ "model": self.remote_field.model._meta.verbose_name, "pk": value, "field": self.remote_field.field_name, "value": value, }, # 'pk' is included for backwards compatibility ) def resolve_related_fields(self): related_fields = super().resolve_related_fields() for from_field, to_field in related_fields: if ( to_field and to_field.model != self.remote_field.model._meta.concrete_model ): raise exceptions.FieldError( "'%s.%s' refers to field '%s' which is not local to model " "'%s'." % ( self.model._meta.label, self.name, to_field.name, self.remote_field.model._meta.concrete_model._meta.label, ) ) return related_fields def get_attname(self): return "%s_id" % self.name def get_attname_column(self): attname = self.get_attname() column = self.db_column or attname return attname, column def get_default(self): """Return the to_field if the default value is an object.""" field_default = super().get_default() if isinstance(field_default, self.remote_field.model): return getattr(field_default, self.target_field.attname) return field_default def get_db_prep_save(self, value, connection): if value is None or ( value == "" and ( not self.target_field.empty_strings_allowed or connection.features.interprets_empty_strings_as_nulls ) ): return None else: return self.target_field.get_db_prep_save(value, connection=connection) def get_db_prep_value(self, value, connection, prepared=False): return self.target_field.get_db_prep_value(value, connection, prepared) def get_prep_value(self, value): return self.target_field.get_prep_value(value) def contribute_to_related_class(self, cls, related): super().contribute_to_related_class(cls, related) if self.remote_field.field_name is None: self.remote_field.field_name = cls._meta.pk.name def formfield(self, *, using=None, **kwargs): if isinstance(self.remote_field.model, str): raise ValueError( "Cannot create form field for %r yet, because " "its related model %r has not been loaded yet" % (self.name, self.remote_field.model) ) return super().formfield( **{ "form_class": forms.ModelChoiceField, "queryset": self.remote_field.model._default_manager.using(using), "to_field_name": self.remote_field.field_name, **kwargs, "blank": self.blank, } ) def db_check(self, connection): return None def db_type(self, connection): return self.target_field.rel_db_type(connection=connection) def cast_db_type(self, connection): return self.target_field.cast_db_type(connection=connection) def db_parameters(self, connection): target_db_parameters = self.target_field.db_parameters(connection) return { "type": self.db_type(connection), "check": self.db_check(connection), "collation": target_db_parameters.get("collation"), } def convert_empty_strings(self, value, expression, connection): if (not value) and isinstance(value, str): return None return value def get_db_converters(self, connection): converters = super().get_db_converters(connection) if connection.features.interprets_empty_strings_as_nulls: converters += [self.convert_empty_strings] return converters def get_col(self, alias, output_field=None): if output_field is None: output_field = self.target_field while isinstance(output_field, ForeignKey): output_field = output_field.target_field if output_field is self: raise ValueError("Cannot resolve output_field.") return super().get_col(alias, output_field) class OneToOneField(ForeignKey): """ A OneToOneField is essentially the same as a ForeignKey, with the exception that it always carries a "unique" constraint with it and the reverse relation always returns the object pointed to (since there will only ever be one), rather than returning a list. """ # Field flags many_to_many = False many_to_one = False one_to_many = False one_to_one = True related_accessor_class = ReverseOneToOneDescriptor forward_related_accessor_class = ForwardOneToOneDescriptor rel_class = OneToOneRel description = _("One-to-one relationship") def __init__(self, to, on_delete, to_field=None, **kwargs): kwargs["unique"] = True super().__init__(to, on_delete, to_field=to_field, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if "unique" in kwargs: del kwargs["unique"] return name, path, args, kwargs def formfield(self, **kwargs): if self.remote_field.parent_link: return None return super().formfield(**kwargs) def save_form_data(self, instance, data): if isinstance(data, self.remote_field.model): setattr(instance, self.name, data) else: setattr(instance, self.attname, data) # Remote field object must be cleared otherwise Model.save() # will reassign attname using the related object pk. if data is None: setattr(instance, self.name, data) def _check_unique(self, **kwargs): # Override ForeignKey since check isn't applicable here. return [] def create_many_to_many_intermediary_model(field, klass): from django.db import models def set_managed(model, related, through): through._meta.managed = model._meta.managed or related._meta.managed to_model = resolve_relation(klass, field.remote_field.model) name = "%s_%s" % (klass._meta.object_name, field.name) lazy_related_operation(set_managed, klass, to_model, name) to = make_model_tuple(to_model)[1] from_ = klass._meta.model_name if to == from_: to = "to_%s" % to from_ = "from_%s" % from_ meta = type( "Meta", (), { "db_table": field._get_m2m_db_table(klass._meta), "auto_created": klass, "app_label": klass._meta.app_label, "db_tablespace": klass._meta.db_tablespace, "unique_together": (from_, to), "verbose_name": _("%(from)s-%(to)s relationship") % {"from": from_, "to": to}, "verbose_name_plural": _("%(from)s-%(to)s relationships") % {"from": from_, "to": to}, "apps": field.model._meta.apps, }, ) # Construct and return the new class. return type( name, (models.Model,), { "Meta": meta, "__module__": klass.__module__, from_: models.ForeignKey( klass, related_name="%s+" % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ), to: models.ForeignKey( to_model, related_name="%s+" % name, db_tablespace=field.db_tablespace, db_constraint=field.remote_field.db_constraint, on_delete=CASCADE, ), }, ) class ManyToManyField(RelatedField): """ Provide a many-to-many relation by using an intermediary model that holds two ForeignKey fields pointed at the two sides of the relation. Unless a ``through`` model was provided, ManyToManyField will use the create_many_to_many_intermediary_model factory to automatically generate the intermediary model. """ # Field flags many_to_many = True many_to_one = False one_to_many = False one_to_one = False rel_class = ManyToManyRel description = _("Many-to-many relationship") def __init__( self, to, related_name=None, related_query_name=None, limit_choices_to=None, symmetrical=None, through=None, through_fields=None, db_constraint=True, db_table=None, swappable=True, **kwargs, ): try: to._meta except AttributeError: if not isinstance(to, str): raise TypeError( "%s(%r) is invalid. First parameter to ManyToManyField " "must be either a model, a model name, or the string %r" % ( self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT, ) ) if symmetrical is None: symmetrical = to == RECURSIVE_RELATIONSHIP_CONSTANT if through is not None and db_table is not None: raise ValueError( "Cannot specify a db_table if an intermediary model is used." ) kwargs["rel"] = self.rel_class( self, to, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, symmetrical=symmetrical, through=through, through_fields=through_fields, db_constraint=db_constraint, ) self.has_null_arg = "null" in kwargs super().__init__( related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, **kwargs, ) self.db_table = db_table self.swappable = swappable def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_unique(**kwargs), *self._check_relationship_model(**kwargs), *self._check_ignored_options(**kwargs), *self._check_table_uniqueness(**kwargs), ] def _check_unique(self, **kwargs): if self.unique: return [ checks.Error( "ManyToManyFields cannot be unique.", obj=self, id="fields.E330", ) ] return [] def _check_ignored_options(self, **kwargs): warnings = [] if self.has_null_arg: warnings.append( checks.Warning( "null has no effect on ManyToManyField.", obj=self, id="fields.W340", ) ) if self._validators: warnings.append( checks.Warning( "ManyToManyField does not support validators.", obj=self, id="fields.W341", ) ) if self.remote_field.symmetrical and self._related_name: warnings.append( checks.Warning( "related_name has no effect on ManyToManyField " 'with a symmetrical relationship, e.g. to "self".', obj=self, id="fields.W345", ) ) if self.db_comment: warnings.append( checks.Warning( "db_comment has no effect on ManyToManyField.", obj=self, id="fields.W346", ) ) return warnings def _check_relationship_model(self, from_model=None, **kwargs): if hasattr(self.remote_field.through, "_meta"): qualified_model_name = "%s.%s" % ( self.remote_field.through._meta.app_label, self.remote_field.through.__name__, ) else: qualified_model_name = self.remote_field.through errors = [] if self.remote_field.through not in self.opts.apps.get_models( include_auto_created=True ): # The relationship model is not installed. errors.append( checks.Error( "Field specifies a many-to-many relation through model " "'%s', which has not been installed." % qualified_model_name, obj=self, id="fields.E331", ) ) else: assert from_model is not None, ( "ManyToManyField with intermediate " "tables cannot be checked if you don't pass the model " "where the field is attached to." ) # Set some useful local variables to_model = resolve_relation(from_model, self.remote_field.model) from_model_name = from_model._meta.object_name if isinstance(to_model, str): to_model_name = to_model else: to_model_name = to_model._meta.object_name relationship_model_name = self.remote_field.through._meta.object_name self_referential = from_model == to_model # Count foreign keys in intermediate model if self_referential: seen_self = sum( from_model == getattr(field.remote_field, "model", None) for field in self.remote_field.through._meta.fields ) if seen_self > 2 and not self.remote_field.through_fields: errors.append( checks.Error( "The model is used as an intermediate model by " "'%s', but it has more than two foreign keys " "to '%s', which is ambiguous. You must specify " "which two foreign keys Django should use via the " "through_fields keyword argument." % (self, from_model_name), hint=( "Use through_fields to specify which two foreign keys " "Django should use." ), obj=self.remote_field.through, id="fields.E333", ) ) else: # Count foreign keys in relationship model seen_from = sum( from_model == getattr(field.remote_field, "model", None) for field in self.remote_field.through._meta.fields ) seen_to = sum( to_model == getattr(field.remote_field, "model", None) for field in self.remote_field.through._meta.fields ) if seen_from > 1 and not self.remote_field.through_fields: errors.append( checks.Error( ( "The model is used as an intermediate model by " "'%s', but it has more than one foreign key " "from '%s', which is ambiguous. You must specify " "which foreign key Django should use via the " "through_fields keyword argument." ) % (self, from_model_name), hint=( "If you want to create a recursive relationship, " 'use ManyToManyField("%s", through="%s").' ) % ( RECURSIVE_RELATIONSHIP_CONSTANT, relationship_model_name, ), obj=self, id="fields.E334", ) ) if seen_to > 1 and not self.remote_field.through_fields: errors.append( checks.Error( "The model is used as an intermediate model by " "'%s', but it has more than one foreign key " "to '%s', which is ambiguous. You must specify " "which foreign key Django should use via the " "through_fields keyword argument." % (self, to_model_name), hint=( "If you want to create a recursive relationship, " 'use ManyToManyField("%s", through="%s").' ) % ( RECURSIVE_RELATIONSHIP_CONSTANT, relationship_model_name, ), obj=self, id="fields.E335", ) ) if seen_from == 0 or seen_to == 0: errors.append( checks.Error( "The model is used as an intermediate model by " "'%s', but it does not have a foreign key to '%s' or '%s'." % (self, from_model_name, to_model_name), obj=self.remote_field.through, id="fields.E336", ) ) # Validate `through_fields`. if self.remote_field.through_fields is not None: # Validate that we're given an iterable of at least two items # and that none of them is "falsy". if not ( len(self.remote_field.through_fields) >= 2 and self.remote_field.through_fields[0] and self.remote_field.through_fields[1] ): errors.append( checks.Error( "Field specifies 'through_fields' but does not provide " "the names of the two link fields that should be used " "for the relation through model '%s'." % qualified_model_name, hint=( "Make sure you specify 'through_fields' as " "through_fields=('field1', 'field2')" ), obj=self, id="fields.E337", ) ) # Validate the given through fields -- they should be actual # fields on the through model, and also be foreign keys to the # expected models. else: assert from_model is not None, ( "ManyToManyField with intermediate " "tables cannot be checked if you don't pass the model " "where the field is attached to." ) source, through, target = ( from_model, self.remote_field.through, self.remote_field.model, ) source_field_name, target_field_name = self.remote_field.through_fields[ :2 ] for field_name, related_model in ( (source_field_name, source), (target_field_name, target), ): possible_field_names = [] for f in through._meta.fields: if ( hasattr(f, "remote_field") and getattr(f.remote_field, "model", None) == related_model ): possible_field_names.append(f.name) if possible_field_names: hint = ( "Did you mean one of the following foreign keys to '%s': " "%s?" % ( related_model._meta.object_name, ", ".join(possible_field_names), ) ) else: hint = None try: field = through._meta.get_field(field_name) except exceptions.FieldDoesNotExist: errors.append( checks.Error( "The intermediary model '%s' has no field '%s'." % (qualified_model_name, field_name), hint=hint, obj=self, id="fields.E338", ) ) else: if not ( hasattr(field, "remote_field") and getattr(field.remote_field, "model", None) == related_model ): errors.append( checks.Error( "'%s.%s' is not a foreign key to '%s'." % ( through._meta.object_name, field_name, related_model._meta.object_name, ), hint=hint, obj=self, id="fields.E339", ) ) return errors def _check_table_uniqueness(self, **kwargs): if ( isinstance(self.remote_field.through, str) or not self.remote_field.through._meta.managed ): return [] registered_tables = { model._meta.db_table: model for model in self.opts.apps.get_models(include_auto_created=True) if model != self.remote_field.through and model._meta.managed } m2m_db_table = self.m2m_db_table() model = registered_tables.get(m2m_db_table) # The second condition allows multiple m2m relations on a model if # some point to a through model that proxies another through model. if ( model and model._meta.concrete_model != self.remote_field.through._meta.concrete_model ): if model._meta.auto_created: def _get_field_name(model): for field in model._meta.auto_created._meta.many_to_many: if field.remote_field.through is model: return field.name opts = model._meta.auto_created._meta clashing_obj = "%s.%s" % (opts.label, _get_field_name(model)) else: clashing_obj = model._meta.label if settings.DATABASE_ROUTERS: error_class, error_id = checks.Warning, "fields.W344" error_hint = ( "You have configured settings.DATABASE_ROUTERS. Verify " "that the table of %r is correctly routed to a separate " "database." % clashing_obj ) else: error_class, error_id = checks.Error, "fields.E340" error_hint = None return [ error_class( "The field's intermediary table '%s' clashes with the " "table name of '%s'." % (m2m_db_table, clashing_obj), obj=self, hint=error_hint, id=error_id, ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() # Handle the simpler arguments. if self.db_table is not None: kwargs["db_table"] = self.db_table if self.remote_field.db_constraint is not True: kwargs["db_constraint"] = self.remote_field.db_constraint # Lowercase model names as they should be treated as case-insensitive. if isinstance(self.remote_field.model, str): if "." in self.remote_field.model: app_label, model_name = self.remote_field.model.split(".") kwargs["to"] = "%s.%s" % (app_label, model_name.lower()) else: kwargs["to"] = self.remote_field.model.lower() else: kwargs["to"] = self.remote_field.model._meta.label_lower if getattr(self.remote_field, "through", None) is not None: if isinstance(self.remote_field.through, str): kwargs["through"] = self.remote_field.through elif not self.remote_field.through._meta.auto_created: kwargs["through"] = self.remote_field.through._meta.label # If swappable is True, then see if we're actually pointing to the target # of a swap. swappable_setting = self.swappable_setting if swappable_setting is not None: # If it's already a settings reference, error. if hasattr(kwargs["to"], "setting_name"): if kwargs["to"].setting_name != swappable_setting: raise ValueError( "Cannot deconstruct a ManyToManyField pointing to a " "model that is swapped in place of more than one model " "(%s and %s)" % (kwargs["to"].setting_name, swappable_setting) ) kwargs["to"] = SettingsReference( kwargs["to"], swappable_setting, ) return name, path, args, kwargs def _get_path_info(self, direct=False, filtered_relation=None): """Called by both direct and indirect m2m traversal.""" int_model = self.remote_field.through linkfield1 = int_model._meta.get_field(self.m2m_field_name()) linkfield2 = int_model._meta.get_field(self.m2m_reverse_field_name()) if direct: join1infos = linkfield1.reverse_path_infos if filtered_relation: join2infos = linkfield2.get_path_info(filtered_relation) else: join2infos = linkfield2.path_infos else: join1infos = linkfield2.reverse_path_infos if filtered_relation: join2infos = linkfield1.get_path_info(filtered_relation) else: join2infos = linkfield1.path_infos # Get join infos between the last model of join 1 and the first model # of join 2. Assume the only reason these may differ is due to model # inheritance. join1_final = join1infos[-1].to_opts join2_initial = join2infos[0].from_opts if join1_final is join2_initial: intermediate_infos = [] elif issubclass(join1_final.model, join2_initial.model): intermediate_infos = join1_final.get_path_to_parent(join2_initial.model) else: intermediate_infos = join2_initial.get_path_from_parent(join1_final.model) return [*join1infos, *intermediate_infos, *join2infos] def get_path_info(self, filtered_relation=None): return self._get_path_info(direct=True, filtered_relation=filtered_relation) @cached_property def path_infos(self): return self.get_path_info() def get_reverse_path_info(self, filtered_relation=None): return self._get_path_info(direct=False, filtered_relation=filtered_relation) @cached_property def reverse_path_infos(self): return self.get_reverse_path_info() def _get_m2m_db_table(self, opts): """ Function that can be curried to provide the m2m table name for this relation. """ if self.remote_field.through is not None: return self.remote_field.through._meta.db_table elif self.db_table: return self.db_table else: m2m_table_name = "%s_%s" % (utils.strip_quotes(opts.db_table), self.name) return utils.truncate_name(m2m_table_name, connection.ops.max_name_length()) def _get_m2m_attr(self, related, attr): """ Function that can be curried to provide the source accessor or DB column name for the m2m table. """ cache_attr = "_m2m_%s_cache" % attr if hasattr(self, cache_attr): return getattr(self, cache_attr) if self.remote_field.through_fields is not None: link_field_name = self.remote_field.through_fields[0] else: link_field_name = None for f in self.remote_field.through._meta.fields: if ( f.is_relation and f.remote_field.model == related.related_model and (link_field_name is None or link_field_name == f.name) ): setattr(self, cache_attr, getattr(f, attr)) return getattr(self, cache_attr) def _get_m2m_reverse_attr(self, related, attr): """ Function that can be curried to provide the related accessor or DB column name for the m2m table. """ cache_attr = "_m2m_reverse_%s_cache" % attr if hasattr(self, cache_attr): return getattr(self, cache_attr) found = False if self.remote_field.through_fields is not None: link_field_name = self.remote_field.through_fields[1] else: link_field_name = None for f in self.remote_field.through._meta.fields: if f.is_relation and f.remote_field.model == related.model: if link_field_name is None and related.related_model == related.model: # If this is an m2m-intermediate to self, # the first foreign key you find will be # the source column. Keep searching for # the second foreign key. if found: setattr(self, cache_attr, getattr(f, attr)) break else: found = True elif link_field_name is None or link_field_name == f.name: setattr(self, cache_attr, getattr(f, attr)) break return getattr(self, cache_attr) def contribute_to_class(self, cls, name, **kwargs): # To support multiple relations to self, it's useful to have a non-None # related name on symmetrical relations for internal reasons. The # concept doesn't make a lot of sense externally ("you want me to # specify *what* on my non-reversible relation?!"), so we set it up # automatically. The funky name reduces the chance of an accidental # clash. if self.remote_field.symmetrical and ( self.remote_field.model == RECURSIVE_RELATIONSHIP_CONSTANT or self.remote_field.model == cls._meta.object_name ): self.remote_field.related_name = "%s_rel_+" % name elif self.remote_field.is_hidden(): # If the backwards relation is disabled, replace the original # related_name with one generated from the m2m field name. Django # still uses backwards relations internally and we need to avoid # clashes between multiple m2m fields with related_name == '+'. self.remote_field.related_name = "_%s_%s_%s_+" % ( cls._meta.app_label, cls.__name__.lower(), name, ) super().contribute_to_class(cls, name, **kwargs) # The intermediate m2m model is not auto created if: # 1) There is a manually specified intermediate, or # 2) The class owning the m2m field is abstract. # 3) The class owning the m2m field has been swapped out. if not cls._meta.abstract: if self.remote_field.through: def resolve_through_model(_, model, field): field.remote_field.through = model lazy_related_operation( resolve_through_model, cls, self.remote_field.through, field=self ) elif not cls._meta.swapped: self.remote_field.through = create_many_to_many_intermediary_model( self, cls ) # Add the descriptor for the m2m relation. setattr(cls, self.name, ManyToManyDescriptor(self.remote_field, reverse=False)) # Set up the accessor for the m2m table name for the relation. self.m2m_db_table = partial(self._get_m2m_db_table, cls._meta) def contribute_to_related_class(self, cls, related): # Internal M2Ms (i.e., those with a related name ending with '+') # and swapped models don't get a related descriptor. if ( not self.remote_field.is_hidden() and not related.related_model._meta.swapped ): setattr( cls, related.get_accessor_name(), ManyToManyDescriptor(self.remote_field, reverse=True), ) # Set up the accessors for the column names on the m2m table. self.m2m_column_name = partial(self._get_m2m_attr, related, "column") self.m2m_reverse_name = partial(self._get_m2m_reverse_attr, related, "column") self.m2m_field_name = partial(self._get_m2m_attr, related, "name") self.m2m_reverse_field_name = partial( self._get_m2m_reverse_attr, related, "name" ) get_m2m_rel = partial(self._get_m2m_attr, related, "remote_field") self.m2m_target_field_name = lambda: get_m2m_rel().field_name get_m2m_reverse_rel = partial( self._get_m2m_reverse_attr, related, "remote_field" ) self.m2m_reverse_target_field_name = lambda: get_m2m_reverse_rel().field_name def set_attributes_from_rel(self): pass def value_from_object(self, obj): return [] if obj.pk is None else list(getattr(obj, self.attname).all()) def save_form_data(self, instance, data): getattr(instance, self.attname).set(data) def formfield(self, *, using=None, **kwargs): defaults = { "form_class": forms.ModelMultipleChoiceField, "queryset": self.remote_field.model._default_manager.using(using), **kwargs, } # If initial is passed in, it's a list of related objects, but the # MultipleChoiceField takes a list of IDs. if defaults.get("initial") is not None: initial = defaults["initial"] if callable(initial): initial = initial() defaults["initial"] = [i.pk for i in initial] return super().formfield(**defaults) def db_check(self, connection): return None def db_type(self, connection): # A ManyToManyField is not represented by a single column, # so return None. return None def db_parameters(self, connection): return {"type": None, "check": None}
e8c0ef17e46995331c1ed7976c494469bb1fd2b8049401b23305158f1a162679
""" "Rel objects" for related fields. "Rel objects" (for lack of a better name) carry information about the relation modeled by a related field and provide some utility functions. They're stored in the ``remote_field`` attribute of the field. They also act as reverse fields for the purposes of the Meta API because they're the closest concept currently available. """ import warnings from django.core import exceptions from django.utils.deprecation import RemovedInDjango60Warning from django.utils.functional import cached_property from django.utils.hashable import make_hashable from . import BLANK_CHOICE_DASH from .mixins import FieldCacheMixin class ForeignObjectRel(FieldCacheMixin): """ Used by ForeignObject to store information about the relation. ``_meta.get_fields()`` returns this class to provide access to the field flags for the reverse relation. """ # Field flags auto_created = True concrete = False editable = False is_relation = True # Reverse relations are always nullable (Django can't enforce that a # foreign key on the related model points to this model). null = True empty_strings_allowed = False def __init__( self, field, to, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, on_delete=None, ): self.field = field self.model = to self.related_name = related_name self.related_query_name = related_query_name self.limit_choices_to = {} if limit_choices_to is None else limit_choices_to self.parent_link = parent_link self.on_delete = on_delete self.symmetrical = False self.multiple = True # Some of the following cached_properties can't be initialized in # __init__ as the field doesn't have its model yet. Calling these methods # before field.contribute_to_class() has been called will result in # AttributeError @cached_property def hidden(self): return self.is_hidden() @cached_property def name(self): return self.field.related_query_name() @property def remote_field(self): return self.field @property def target_field(self): """ When filtering against this relation, return the field on the remote model against which the filtering should happen. """ target_fields = self.path_infos[-1].target_fields if len(target_fields) > 1: raise exceptions.FieldError( "Can't use target_field for multicolumn relations." ) return target_fields[0] @cached_property def related_model(self): if not self.field.model: raise AttributeError( "This property can't be accessed before self.field.contribute_to_class " "has been called." ) return self.field.model @cached_property def many_to_many(self): return self.field.many_to_many @cached_property def many_to_one(self): return self.field.one_to_many @cached_property def one_to_many(self): return self.field.many_to_one @cached_property def one_to_one(self): return self.field.one_to_one def get_lookup(self, lookup_name): return self.field.get_lookup(lookup_name) def get_lookups(self): return self.field.get_lookups() def get_transform(self, name): return self.field.get_transform(name) def get_internal_type(self): return self.field.get_internal_type() @property def db_type(self): return self.field.db_type def __repr__(self): return "<%s: %s.%s>" % ( type(self).__name__, self.related_model._meta.app_label, self.related_model._meta.model_name, ) @property def identity(self): return ( self.field, self.model, self.related_name, self.related_query_name, make_hashable(self.limit_choices_to), self.parent_link, self.on_delete, self.symmetrical, self.multiple, ) def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return self.identity == other.identity def __hash__(self): return hash(self.identity) def __getstate__(self): state = self.__dict__.copy() # Delete the path_infos cached property because it can be recalculated # at first invocation after deserialization. The attribute must be # removed because subclasses like ManyToOneRel may have a PathInfo # which contains an intermediate M2M table that's been dynamically # created and doesn't exist in the .models module. # This is a reverse relation, so there is no reverse_path_infos to # delete. state.pop("path_infos", None) return state def get_choices( self, include_blank=True, blank_choice=BLANK_CHOICE_DASH, limit_choices_to=None, ordering=(), ): """ Return choices with a default blank choices included, for use as <select> choices for this field. Analog of django.db.models.fields.Field.get_choices(), provided initially for utilization by RelatedFieldListFilter. """ limit_choices_to = limit_choices_to or self.limit_choices_to qs = self.related_model._default_manager.complex_filter(limit_choices_to) if ordering: qs = qs.order_by(*ordering) return (blank_choice if include_blank else []) + [(x.pk, str(x)) for x in qs] def is_hidden(self): """Should the related object be hidden?""" return bool(self.related_name) and self.related_name[-1] == "+" def get_joining_columns(self): warnings.warn( "ForeignObjectRel.get_joining_columns() is deprecated. Use " "get_joining_fields() instead.", RemovedInDjango60Warning, ) return self.field.get_reverse_joining_columns() def get_joining_fields(self): return self.field.get_reverse_joining_fields() def get_extra_restriction(self, alias, related_alias): return self.field.get_extra_restriction(related_alias, alias) def set_field_name(self): """ Set the related field's name, this is not available until later stages of app loading, so set_field_name is called from set_attributes_from_rel() """ # By default foreign object doesn't relate to any remote field (for # example custom multicolumn joins currently have no remote field). self.field_name = None def get_accessor_name(self, model=None): # This method encapsulates the logic that decides what name to give an # accessor descriptor that retrieves related many-to-one or # many-to-many objects. It uses the lowercased object_name + "_set", # but this can be overridden with the "related_name" option. Due to # backwards compatibility ModelForms need to be able to provide an # alternate model. See BaseInlineFormSet.get_default_prefix(). opts = model._meta if model else self.related_model._meta model = model or self.related_model if self.multiple: # If this is a symmetrical m2m relation on self, there is no # reverse accessor. if self.symmetrical and model == self.model: return None if self.related_name: return self.related_name return opts.model_name + ("_set" if self.multiple else "") def get_path_info(self, filtered_relation=None): if filtered_relation: return self.field.get_reverse_path_info(filtered_relation) else: return self.field.reverse_path_infos @cached_property def path_infos(self): return self.get_path_info() def get_cache_name(self): """ Return the name of the cache key to use for storing an instance of the forward model on the reverse model. """ return self.get_accessor_name() class ManyToOneRel(ForeignObjectRel): """ Used by the ForeignKey field to store information about the relation. ``_meta.get_fields()`` returns this class to provide access to the field flags for the reverse relation. Note: Because we somewhat abuse the Rel objects by using them as reverse fields we get the funny situation where ``ManyToOneRel.many_to_one == False`` and ``ManyToOneRel.one_to_many == True``. This is unfortunate but the actual ManyToOneRel class is a private API and there is work underway to turn reverse relations into actual fields. """ def __init__( self, field, to, field_name, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, on_delete=None, ): super().__init__( field, to, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, parent_link=parent_link, on_delete=on_delete, ) self.field_name = field_name def __getstate__(self): state = super().__getstate__() state.pop("related_model", None) return state @property def identity(self): return super().identity + (self.field_name,) def get_related_field(self): """ Return the Field in the 'to' object to which this relationship is tied. """ field = self.model._meta.get_field(self.field_name) if not field.concrete: raise exceptions.FieldDoesNotExist( "No related field named '%s'" % self.field_name ) return field def set_field_name(self): self.field_name = self.field_name or self.model._meta.pk.name class OneToOneRel(ManyToOneRel): """ Used by OneToOneField to store information about the relation. ``_meta.get_fields()`` returns this class to provide access to the field flags for the reverse relation. """ def __init__( self, field, to, field_name, related_name=None, related_query_name=None, limit_choices_to=None, parent_link=False, on_delete=None, ): super().__init__( field, to, field_name, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, parent_link=parent_link, on_delete=on_delete, ) self.multiple = False class ManyToManyRel(ForeignObjectRel): """ Used by ManyToManyField to store information about the relation. ``_meta.get_fields()`` returns this class to provide access to the field flags for the reverse relation. """ def __init__( self, field, to, related_name=None, related_query_name=None, limit_choices_to=None, symmetrical=True, through=None, through_fields=None, db_constraint=True, ): super().__init__( field, to, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, ) if through and not db_constraint: raise ValueError("Can't supply a through model and db_constraint=False") self.through = through if through_fields and not through: raise ValueError("Cannot specify through_fields without a through model") self.through_fields = through_fields self.symmetrical = symmetrical self.db_constraint = db_constraint @property def identity(self): return super().identity + ( self.through, make_hashable(self.through_fields), self.db_constraint, ) def get_related_field(self): """ Return the field in the 'to' object to which this relationship is tied. Provided for symmetry with ManyToOneRel. """ opts = self.through._meta if self.through_fields: field = opts.get_field(self.through_fields[0]) else: for field in opts.fields: rel = getattr(field, "remote_field", None) if rel and rel.model == self.model: break return field.foreign_related_fields[0]
e8a652eaf9bbeb467c265cda2097f2c412d6d8802686a28f737620215ccb638f
from django.db import NotSupportedError from django.db.models.expressions import Func, Value from django.db.models.fields import CharField, IntegerField, TextField from django.db.models.functions import Cast, Coalesce from django.db.models.lookups import Transform class MySQLSHA2Mixin: def as_mysql(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, template="SHA2(%%(expressions)s, %s)" % self.function[3:], **extra_context, ) class OracleHashMixin: def as_oracle(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, template=( "LOWER(RAWTOHEX(STANDARD_HASH(UTL_I18N.STRING_TO_RAW(" "%(expressions)s, 'AL32UTF8'), '%(function)s')))" ), **extra_context, ) class PostgreSQLSHAMixin: def as_postgresql(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, template="ENCODE(DIGEST(%(expressions)s, '%(function)s'), 'hex')", function=self.function.lower(), **extra_context, ) class Chr(Transform): function = "CHR" lookup_name = "chr" output_field = CharField() def as_mysql(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, function="CHAR", template="%(function)s(%(expressions)s USING utf16)", **extra_context, ) def as_oracle(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, template="%(function)s(%(expressions)s USING NCHAR_CS)", **extra_context, ) def as_sqlite(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function="CHAR", **extra_context) class ConcatPair(Func): """ Concatenate two arguments together. This is used by `Concat` because not all backend databases support more than two arguments. """ function = "CONCAT" def as_sqlite(self, compiler, connection, **extra_context): coalesced = self.coalesce() return super(ConcatPair, coalesced).as_sql( compiler, connection, template="%(expressions)s", arg_joiner=" || ", **extra_context, ) def as_postgresql(self, compiler, connection, **extra_context): copy = self.copy() copy.set_source_expressions( [ Cast(expression, TextField()) for expression in copy.get_source_expressions() ] ) return super(ConcatPair, copy).as_sql( compiler, connection, **extra_context, ) def as_mysql(self, compiler, connection, **extra_context): # Use CONCAT_WS with an empty separator so that NULLs are ignored. return super().as_sql( compiler, connection, function="CONCAT_WS", template="%(function)s('', %(expressions)s)", **extra_context, ) def coalesce(self): # null on either side results in null for expression, wrap with coalesce c = self.copy() c.set_source_expressions( [ Coalesce(expression, Value("")) for expression in c.get_source_expressions() ] ) return c class Concat(Func): """ Concatenate text fields together. Backends that result in an entire null expression when any arguments are null will wrap each argument in coalesce functions to ensure a non-null result. """ function = None template = "%(expressions)s" def __init__(self, *expressions, **extra): if len(expressions) < 2: raise ValueError("Concat must take at least two expressions") paired = self._paired(expressions) super().__init__(paired, **extra) def _paired(self, expressions): # wrap pairs of expressions in successive concat functions # exp = [a, b, c, d] # -> ConcatPair(a, ConcatPair(b, ConcatPair(c, d)))) if len(expressions) == 2: return ConcatPair(*expressions) return ConcatPair(expressions[0], self._paired(expressions[1:])) class Left(Func): function = "LEFT" arity = 2 output_field = CharField() def __init__(self, expression, length, **extra): """ expression: the name of a field, or an expression returning a string length: the number of characters to return from the start of the string """ if not hasattr(length, "resolve_expression"): if length < 1: raise ValueError("'length' must be greater than 0.") super().__init__(expression, length, **extra) def get_substr(self): return Substr(self.source_expressions[0], Value(1), self.source_expressions[1]) def as_oracle(self, compiler, connection, **extra_context): return self.get_substr().as_oracle(compiler, connection, **extra_context) def as_sqlite(self, compiler, connection, **extra_context): return self.get_substr().as_sqlite(compiler, connection, **extra_context) class Length(Transform): """Return the number of characters in the expression.""" function = "LENGTH" lookup_name = "length" output_field = IntegerField() def as_mysql(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, function="CHAR_LENGTH", **extra_context ) class Lower(Transform): function = "LOWER" lookup_name = "lower" class LPad(Func): function = "LPAD" output_field = CharField() def __init__(self, expression, length, fill_text=Value(" "), **extra): if ( not hasattr(length, "resolve_expression") and length is not None and length < 0 ): raise ValueError("'length' must be greater or equal to 0.") super().__init__(expression, length, fill_text, **extra) class LTrim(Transform): function = "LTRIM" lookup_name = "ltrim" class MD5(OracleHashMixin, Transform): function = "MD5" lookup_name = "md5" class Ord(Transform): function = "ASCII" lookup_name = "ord" output_field = IntegerField() def as_mysql(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function="ORD", **extra_context) def as_sqlite(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function="UNICODE", **extra_context) class Repeat(Func): function = "REPEAT" output_field = CharField() def __init__(self, expression, number, **extra): if ( not hasattr(number, "resolve_expression") and number is not None and number < 0 ): raise ValueError("'number' must be greater or equal to 0.") super().__init__(expression, number, **extra) def as_oracle(self, compiler, connection, **extra_context): expression, number = self.source_expressions length = None if number is None else Length(expression) * number rpad = RPad(expression, length, expression) return rpad.as_sql(compiler, connection, **extra_context) class Replace(Func): function = "REPLACE" def __init__(self, expression, text, replacement=Value(""), **extra): super().__init__(expression, text, replacement, **extra) class Reverse(Transform): function = "REVERSE" lookup_name = "reverse" def as_oracle(self, compiler, connection, **extra_context): # REVERSE in Oracle is undocumented and doesn't support multi-byte # strings. Use a special subquery instead. return super().as_sql( compiler, connection, template=( "(SELECT LISTAGG(s) WITHIN GROUP (ORDER BY n DESC) FROM " "(SELECT LEVEL n, SUBSTR(%(expressions)s, LEVEL, 1) s " "FROM DUAL CONNECT BY LEVEL <= LENGTH(%(expressions)s)) " "GROUP BY %(expressions)s)" ), **extra_context, ) class Right(Left): function = "RIGHT" def get_substr(self): return Substr( self.source_expressions[0], self.source_expressions[1] * Value(-1) ) class RPad(LPad): function = "RPAD" class RTrim(Transform): function = "RTRIM" lookup_name = "rtrim" class SHA1(OracleHashMixin, PostgreSQLSHAMixin, Transform): function = "SHA1" lookup_name = "sha1" class SHA224(MySQLSHA2Mixin, PostgreSQLSHAMixin, Transform): function = "SHA224" lookup_name = "sha224" def as_oracle(self, compiler, connection, **extra_context): raise NotSupportedError("SHA224 is not supported on Oracle.") class SHA256(MySQLSHA2Mixin, OracleHashMixin, PostgreSQLSHAMixin, Transform): function = "SHA256" lookup_name = "sha256" class SHA384(MySQLSHA2Mixin, OracleHashMixin, PostgreSQLSHAMixin, Transform): function = "SHA384" lookup_name = "sha384" class SHA512(MySQLSHA2Mixin, OracleHashMixin, PostgreSQLSHAMixin, Transform): function = "SHA512" lookup_name = "sha512" class StrIndex(Func): """ Return a positive integer corresponding to the 1-indexed position of the first occurrence of a substring inside another string, or 0 if the substring is not found. """ function = "INSTR" arity = 2 output_field = IntegerField() def as_postgresql(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function="STRPOS", **extra_context) class Substr(Func): function = "SUBSTRING" output_field = CharField() def __init__(self, expression, pos, length=None, **extra): """ expression: the name of a field, or an expression returning a string pos: an integer > 0, or an expression returning an integer length: an optional number of characters to return """ if not hasattr(pos, "resolve_expression"): if pos < 1: raise ValueError("'pos' must be greater than 0") expressions = [expression, pos] if length is not None: expressions.append(length) super().__init__(*expressions, **extra) def as_sqlite(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function="SUBSTR", **extra_context) def as_oracle(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function="SUBSTR", **extra_context) class Trim(Transform): function = "TRIM" lookup_name = "trim" class Upper(Transform): function = "UPPER" lookup_name = "upper"
9098b0dcb3c6564e38e2d809706a9bb086c6745219d38f77e7da5b0b3fb0e7b9
""" Create SQL statements for QuerySets. The code in here encapsulates all of the SQL construction so that QuerySets themselves do not have to (and could be backed by things other than SQL databases). The abstraction barrier only works one way: this module has to know all about the internals of models in order to get the information it needs. """ import copy import difflib import functools import sys from collections import Counter, namedtuple from collections.abc import Iterator, Mapping from itertools import chain, count, product from string import ascii_uppercase from django.core.exceptions import FieldDoesNotExist, FieldError from django.db import DEFAULT_DB_ALIAS, NotSupportedError, connections from django.db.models.aggregates import Count from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import ( BaseExpression, Col, Exists, F, OuterRef, Ref, ResolvedOuterRef, Value, ) from django.db.models.fields import Field from django.db.models.fields.related_lookups import MultiColSource from django.db.models.lookups import Lookup from django.db.models.query_utils import ( Q, check_rel_lookup_compatibility, refs_expression, ) from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE from django.db.models.sql.datastructures import BaseTable, Empty, Join, MultiJoin from django.db.models.sql.where import AND, OR, ExtraWhere, NothingNode, WhereNode from django.utils.functional import cached_property from django.utils.regex_helper import _lazy_re_compile from django.utils.tree import Node __all__ = ["Query", "RawQuery"] # Quotation marks ('"`[]), whitespace characters, semicolons, or inline # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(r"['`\"\]\[;\s]|--|/\*|\*/") # Inspired from # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS EXPLAIN_OPTIONS_PATTERN = _lazy_re_compile(r"[\w\-]+") def get_field_names_from_opts(opts): if opts is None: return set() return set( chain.from_iterable( (f.name, f.attname) if f.concrete else (f.name,) for f in opts.get_fields() ) ) def get_children_from_q(q): for child in q.children: if isinstance(child, Node): yield from get_children_from_q(child) else: yield child def rename_prefix_from_q(prefix, replacement, q): return Q.create( [ rename_prefix_from_q(prefix, replacement, c) if isinstance(c, Node) else (c[0].replace(prefix, replacement, 1), c[1]) for c in q.children ], q.connector, q.negated, ) JoinInfo = namedtuple( "JoinInfo", ("final_field", "targets", "opts", "joins", "path", "transform_function"), ) class RawQuery: """A single raw SQL query.""" def __init__(self, sql, using, params=()): self.params = params self.sql = sql self.using = using self.cursor = None # Mirror some properties of a normal query so that # the compiler can be used to process results. self.low_mark, self.high_mark = 0, None # Used for offset/limit self.extra_select = {} self.annotation_select = {} def chain(self, using): return self.clone(using) def clone(self, using): return RawQuery(self.sql, using, params=self.params) def get_columns(self): if self.cursor is None: self._execute_query() converter = connections[self.using].introspection.identifier_converter return [converter(column_meta[0]) for column_meta in self.cursor.description] def __iter__(self): # Always execute a new query for a new iterator. # This could be optimized with a cache at the expense of RAM. self._execute_query() if not connections[self.using].features.can_use_chunked_reads: # If the database can't use chunked reads we need to make sure we # evaluate the entire query up front. result = list(self.cursor) else: result = self.cursor return iter(result) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) @property def params_type(self): if self.params is None: return None return dict if isinstance(self.params, Mapping) else tuple def __str__(self): if self.params_type is None: return self.sql return self.sql % self.params_type(self.params) def _execute_query(self): connection = connections[self.using] # Adapt parameters to the database, as much as possible considering # that the target type isn't known. See #17755. params_type = self.params_type adapter = connection.ops.adapt_unknown_value if params_type is tuple: params = tuple(adapter(val) for val in self.params) elif params_type is dict: params = {key: adapter(val) for key, val in self.params.items()} elif params_type is None: params = None else: raise RuntimeError("Unexpected params type: %s" % params_type) self.cursor = connection.cursor() self.cursor.execute(self.sql, params) ExplainInfo = namedtuple("ExplainInfo", ("format", "options")) class Query(BaseExpression): """A single SQL query.""" alias_prefix = "T" empty_result_set_value = None subq_aliases = frozenset([alias_prefix]) compiler = "SQLCompiler" base_table_class = BaseTable join_class = Join default_cols = True default_ordering = True standard_ordering = True filter_is_sticky = False subquery = False # SQL-related attributes. # Select and related select clauses are expressions to use in the SELECT # clause of the query. The select is used for cases where we want to set up # the select clause to contain other than default fields (values(), # subqueries...). Note that annotations go to annotations dictionary. select = () # The group_by attribute can have one of the following forms: # - None: no group by at all in the query # - A tuple of expressions: group by (at least) those expressions. # String refs are also allowed for now. # - True: group by all select fields of the model # See compiler.get_group_by() for details. group_by = None order_by = () low_mark = 0 # Used for offset/limit. high_mark = None # Used for offset/limit. distinct = False distinct_fields = () select_for_update = False select_for_update_nowait = False select_for_update_skip_locked = False select_for_update_of = () select_for_no_key_update = False select_related = False has_select_fields = False # Arbitrary limit for select_related to prevents infinite recursion. max_depth = 5 # Holds the selects defined by a call to values() or values_list() # excluding annotation_select and extra_select. values_select = () # SQL annotation-related attributes. annotation_select_mask = None _annotation_select_cache = None # Set combination attributes. combinator = None combinator_all = False combined_queries = () # These are for extensions. The contents are more or less appended verbatim # to the appropriate clause. extra_select_mask = None _extra_select_cache = None extra_tables = () extra_order_by = () # A tuple that is a set of model field names and either True, if these are # the fields to defer, or False if these are the only fields to load. deferred_loading = (frozenset(), True) explain_info = None def __init__(self, model, alias_cols=True): self.model = model self.alias_refcount = {} # alias_map is the most important data structure regarding joins. # It's used for recording which joins exist in the query and what # types they are. The key is the alias of the joined table (possibly # the table name) and the value is a Join-like object (see # sql.datastructures.Join for more information). self.alias_map = {} # Whether to provide alias to columns during reference resolving. self.alias_cols = alias_cols # Sometimes the query contains references to aliases in outer queries (as # a result of split_exclude). Correct alias quoting needs to know these # aliases too. # Map external tables to whether they are aliased. self.external_aliases = {} self.table_map = {} # Maps table names to list of aliases. self.used_aliases = set() self.where = WhereNode() # Maps alias -> Annotation Expression. self.annotations = {} # These are for extensions. The contents are more or less appended # verbatim to the appropriate clause. self.extra = {} # Maps col_alias -> (col_sql, params). self._filtered_relations = {} @property def output_field(self): if len(self.select) == 1: select = self.select[0] return getattr(select, "target", None) or select.field elif len(self.annotation_select) == 1: return next(iter(self.annotation_select.values())).output_field @cached_property def base_table(self): for alias in self.alias_map: return alias def __str__(self): """ Return the query as a string of SQL with the parameter values substituted in (use sql_with_params() to see the unsubstituted string). Parameter values won't necessarily be quoted correctly, since that is done by the database interface at execution time. """ sql, params = self.sql_with_params() return sql % params def sql_with_params(self): """ Return the query as an SQL string and the parameters that will be substituted into the query. """ return self.get_compiler(DEFAULT_DB_ALIAS).as_sql() def __deepcopy__(self, memo): """Limit the amount of work when a Query is deepcopied.""" result = self.clone() memo[id(self)] = result return result def get_compiler(self, using=None, connection=None, elide_empty=True): if using is None and connection is None: raise ValueError("Need either using or connection") if using: connection = connections[using] return connection.ops.compiler(self.compiler)( self, connection, using, elide_empty ) def get_meta(self): """ Return the Options instance (the model._meta) from which to start processing. Normally, this is self.model._meta, but it can be changed by subclasses. """ if self.model: return self.model._meta def clone(self): """ Return a copy of the current Query. A lightweight alternative to deepcopy(). """ obj = Empty() obj.__class__ = self.__class__ # Copy references to everything. obj.__dict__ = self.__dict__.copy() # Clone attributes that can't use shallow copy. obj.alias_refcount = self.alias_refcount.copy() obj.alias_map = self.alias_map.copy() obj.external_aliases = self.external_aliases.copy() obj.table_map = self.table_map.copy() obj.where = self.where.clone() obj.annotations = self.annotations.copy() if self.annotation_select_mask is not None: obj.annotation_select_mask = self.annotation_select_mask.copy() if self.combined_queries: obj.combined_queries = tuple( [query.clone() for query in self.combined_queries] ) # _annotation_select_cache cannot be copied, as doing so breaks the # (necessary) state in which both annotations and # _annotation_select_cache point to the same underlying objects. # It will get re-populated in the cloned queryset the next time it's # used. obj._annotation_select_cache = None obj.extra = self.extra.copy() if self.extra_select_mask is not None: obj.extra_select_mask = self.extra_select_mask.copy() if self._extra_select_cache is not None: obj._extra_select_cache = self._extra_select_cache.copy() if self.select_related is not False: # Use deepcopy because select_related stores fields in nested # dicts. obj.select_related = copy.deepcopy(obj.select_related) if "subq_aliases" in self.__dict__: obj.subq_aliases = self.subq_aliases.copy() obj.used_aliases = self.used_aliases.copy() obj._filtered_relations = self._filtered_relations.copy() # Clear the cached_property, if it exists. obj.__dict__.pop("base_table", None) return obj def chain(self, klass=None): """ Return a copy of the current Query that's ready for another operation. The klass argument changes the type of the Query, e.g. UpdateQuery. """ obj = self.clone() if klass and obj.__class__ != klass: obj.__class__ = klass if not obj.filter_is_sticky: obj.used_aliases = set() obj.filter_is_sticky = False if hasattr(obj, "_setup_query"): obj._setup_query() return obj def relabeled_clone(self, change_map): clone = self.clone() clone.change_aliases(change_map) return clone def _get_col(self, target, field, alias): if not self.alias_cols: alias = None return target.get_col(alias, field) def get_aggregation(self, using, aggregate_exprs): """ Return the dictionary with the values of the existing aggregations. """ if not aggregate_exprs: return {} aggregates = {} for alias, aggregate_expr in aggregate_exprs.items(): self.check_alias(alias) aggregate = aggregate_expr.resolve_expression( self, allow_joins=True, reuse=None, summarize=True ) if not aggregate.contains_aggregate: raise TypeError("%s is not an aggregate expression" % alias) aggregates[alias] = aggregate # Existing usage of aggregation can be determined by the presence of # selected aggregates but also by filters against aliased aggregates. _, having, qualify = self.where.split_having_qualify() has_existing_aggregation = ( any( getattr(annotation, "contains_aggregate", True) for annotation in self.annotations.values() ) or having ) # Decide if we need to use a subquery. # # Existing aggregations would cause incorrect results as # get_aggregation() must produce just one result and thus must not use # GROUP BY. # # If the query has limit or distinct, or uses set operations, then # those operations must be done in a subquery so that the query # aggregates on the limit and/or distinct results instead of applying # the distinct and limit after the aggregation. if ( isinstance(self.group_by, tuple) or self.is_sliced or has_existing_aggregation or qualify or self.distinct or self.combinator ): from django.db.models.sql.subqueries import AggregateQuery inner_query = self.clone() inner_query.subquery = True outer_query = AggregateQuery(self.model, inner_query) inner_query.select_for_update = False inner_query.select_related = False inner_query.set_annotation_mask(self.annotation_select) # Queries with distinct_fields need ordering and when a limit is # applied we must take the slice from the ordered query. Otherwise # no need for ordering. inner_query.clear_ordering(force=False) if not inner_query.distinct: # If the inner query uses default select and it has some # aggregate annotations, then we must make sure the inner # query is grouped by the main model's primary key. However, # clearing the select clause can alter results if distinct is # used. if inner_query.default_cols and has_existing_aggregation: inner_query.group_by = ( self.model._meta.pk.get_col(inner_query.get_initial_alias()), ) inner_query.default_cols = False if not qualify: # Mask existing annotations that are not referenced by # aggregates to be pushed to the outer query unless # filtering against window functions is involved as it # requires complex realising. annotation_mask = set() if isinstance(self.group_by, tuple): for expr in self.group_by: annotation_mask |= expr.get_refs() for aggregate in aggregates.values(): annotation_mask |= aggregate.get_refs() inner_query.set_annotation_mask(annotation_mask) # Add aggregates to the outer AggregateQuery. This requires making # sure all columns referenced by the aggregates are selected in the # inner query. It is achieved by retrieving all column references # by the aggregates, explicitly selecting them in the inner query, # and making sure the aggregates are repointed to them. col_refs = {} for alias, aggregate in aggregates.items(): replacements = {} for col in self._gen_cols([aggregate], resolve_refs=False): if not (col_ref := col_refs.get(col)): index = len(col_refs) + 1 col_alias = f"__col{index}" col_ref = Ref(col_alias, col) col_refs[col] = col_ref inner_query.annotations[col_alias] = col inner_query.append_annotation_mask([col_alias]) replacements[col] = col_ref outer_query.annotations[alias] = aggregate.replace_expressions( replacements ) if ( inner_query.select == () and not inner_query.default_cols and not inner_query.annotation_select_mask ): # In case of Model.objects[0:3].count(), there would be no # field selected in the inner query, yet we must use a subquery. # So, make sure at least one field is selected. inner_query.select = ( self.model._meta.pk.get_col(inner_query.get_initial_alias()), ) else: outer_query = self self.select = () self.default_cols = False self.extra = {} if self.annotations: # Inline reference to existing annotations and mask them as # they are unnecessary given only the summarized aggregations # are requested. replacements = { Ref(alias, annotation): annotation for alias, annotation in self.annotations.items() } self.annotations = { alias: aggregate.replace_expressions(replacements) for alias, aggregate in aggregates.items() } else: self.annotations = aggregates self.set_annotation_mask(aggregates) empty_set_result = [ expression.empty_result_set_value for expression in outer_query.annotation_select.values() ] elide_empty = not any(result is NotImplemented for result in empty_set_result) outer_query.clear_ordering(force=True) outer_query.clear_limits() outer_query.select_for_update = False outer_query.select_related = False compiler = outer_query.get_compiler(using, elide_empty=elide_empty) result = compiler.execute_sql(SINGLE) if result is None: result = empty_set_result else: converters = compiler.get_converters(outer_query.annotation_select.values()) result = next(compiler.apply_converters((result,), converters)) return dict(zip(outer_query.annotation_select, result)) def get_count(self, using): """ Perform a COUNT() query using the current filter constraints. """ obj = self.clone() return obj.get_aggregation(using, {"__count": Count("*")})["__count"] def has_filters(self): return self.where def exists(self, limit=True): q = self.clone() if not (q.distinct and q.is_sliced): if q.group_by is True: q.add_fields( (f.attname for f in self.model._meta.concrete_fields), False ) # Disable GROUP BY aliases to avoid orphaning references to the # SELECT clause which is about to be cleared. q.set_group_by(allow_aliases=False) q.clear_select_clause() if q.combined_queries and q.combinator == "union": q.combined_queries = tuple( combined_query.exists(limit=False) for combined_query in q.combined_queries ) q.clear_ordering(force=True) if limit: q.set_limits(high=1) q.add_annotation(Value(1), "a") return q def has_results(self, using): q = self.exists(using) compiler = q.get_compiler(using=using) return compiler.has_results() def explain(self, using, format=None, **options): q = self.clone() for option_name in options: if ( not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name) or "--" in option_name ): raise ValueError(f"Invalid option name: {option_name!r}.") q.explain_info = ExplainInfo(format, options) compiler = q.get_compiler(using=using) return "\n".join(compiler.explain_query()) def combine(self, rhs, connector): """ Merge the 'rhs' query into the current one (with any 'rhs' effects being applied *after* (that is, "to the right of") anything in the current query. 'rhs' is not modified during a call to this function. The 'connector' parameter describes how to connect filters from the 'rhs' query. """ if self.model != rhs.model: raise TypeError("Cannot combine queries on two different base models.") if self.is_sliced: raise TypeError("Cannot combine queries once a slice has been taken.") if self.distinct != rhs.distinct: raise TypeError("Cannot combine a unique query with a non-unique query.") if self.distinct_fields != rhs.distinct_fields: raise TypeError("Cannot combine queries with different distinct fields.") # If lhs and rhs shares the same alias prefix, it is possible to have # conflicting alias changes like T4 -> T5, T5 -> T6, which might end up # as T4 -> T6 while combining two querysets. To prevent this, change an # alias prefix of the rhs and update current aliases accordingly, # except if the alias is the base table since it must be present in the # query on both sides. initial_alias = self.get_initial_alias() rhs.bump_prefix(self, exclude={initial_alias}) # Work out how to relabel the rhs aliases, if necessary. change_map = {} conjunction = connector == AND # Determine which existing joins can be reused. When combining the # query with AND we must recreate all joins for m2m filters. When # combining with OR we can reuse joins. The reason is that in AND # case a single row can't fulfill a condition like: # revrel__col=1 & revrel__col=2 # But, there might be two different related rows matching this # condition. In OR case a single True is enough, so single row is # enough, too. # # Note that we will be creating duplicate joins for non-m2m joins in # the AND case. The results will be correct but this creates too many # joins. This is something that could be fixed later on. reuse = set() if conjunction else set(self.alias_map) joinpromoter = JoinPromoter(connector, 2, False) joinpromoter.add_votes( j for j in self.alias_map if self.alias_map[j].join_type == INNER ) rhs_votes = set() # Now, add the joins from rhs query into the new query (skipping base # table). rhs_tables = list(rhs.alias_map)[1:] for alias in rhs_tables: join = rhs.alias_map[alias] # If the left side of the join was already relabeled, use the # updated alias. join = join.relabeled_clone(change_map) new_alias = self.join(join, reuse=reuse) if join.join_type == INNER: rhs_votes.add(new_alias) # We can't reuse the same join again in the query. If we have two # distinct joins for the same connection in rhs query, then the # combined query must have two joins, too. reuse.discard(new_alias) if alias != new_alias: change_map[alias] = new_alias if not rhs.alias_refcount[alias]: # The alias was unused in the rhs query. Unref it so that it # will be unused in the new query, too. We have to add and # unref the alias so that join promotion has information of # the join type for the unused alias. self.unref_alias(new_alias) joinpromoter.add_votes(rhs_votes) joinpromoter.update_join_types(self) # Combine subqueries aliases to ensure aliases relabelling properly # handle subqueries when combining where and select clauses. self.subq_aliases |= rhs.subq_aliases # Now relabel a copy of the rhs where-clause and add it to the current # one. w = rhs.where.clone() w.relabel_aliases(change_map) self.where.add(w, connector) # Selection columns and extra extensions are those provided by 'rhs'. if rhs.select: self.set_select([col.relabeled_clone(change_map) for col in rhs.select]) else: self.select = () if connector == OR: # It would be nice to be able to handle this, but the queries don't # really make sense (or return consistent value sets). Not worth # the extra complexity when you can write a real query instead. if self.extra and rhs.extra: raise ValueError( "When merging querysets using 'or', you cannot have " "extra(select=...) on both sides." ) self.extra.update(rhs.extra) extra_select_mask = set() if self.extra_select_mask is not None: extra_select_mask.update(self.extra_select_mask) if rhs.extra_select_mask is not None: extra_select_mask.update(rhs.extra_select_mask) if extra_select_mask: self.set_extra_mask(extra_select_mask) self.extra_tables += rhs.extra_tables # Ordering uses the 'rhs' ordering, unless it has none, in which case # the current ordering is used. self.order_by = rhs.order_by or self.order_by self.extra_order_by = rhs.extra_order_by or self.extra_order_by def _get_defer_select_mask(self, opts, mask, select_mask=None): if select_mask is None: select_mask = {} select_mask[opts.pk] = {} # All concrete fields that are not part of the defer mask must be # loaded. If a relational field is encountered it gets added to the # mask for it be considered if `select_related` and the cycle continues # by recursively calling this function. for field in opts.concrete_fields: field_mask = mask.pop(field.name, None) field_att_mask = mask.pop(field.attname, None) if field_mask is None and field_att_mask is None: select_mask.setdefault(field, {}) elif field_mask: if not field.is_relation: raise FieldError(next(iter(field_mask))) field_select_mask = select_mask.setdefault(field, {}) related_model = field.remote_field.model._meta.concrete_model self._get_defer_select_mask( related_model._meta, field_mask, field_select_mask ) # Remaining defer entries must be references to reverse relationships. # The following code is expected to raise FieldError if it encounters # a malformed defer entry. for field_name, field_mask in mask.items(): if filtered_relation := self._filtered_relations.get(field_name): relation = opts.get_field(filtered_relation.relation_name) field_select_mask = select_mask.setdefault((field_name, relation), {}) field = relation.field else: field = opts.get_field(field_name).field field_select_mask = select_mask.setdefault(field, {}) related_model = field.model._meta.concrete_model self._get_defer_select_mask( related_model._meta, field_mask, field_select_mask ) return select_mask def _get_only_select_mask(self, opts, mask, select_mask=None): if select_mask is None: select_mask = {} select_mask[opts.pk] = {} # Only include fields mentioned in the mask. for field_name, field_mask in mask.items(): field = opts.get_field(field_name) field_select_mask = select_mask.setdefault(field, {}) if field_mask: if not field.is_relation: raise FieldError(next(iter(field_mask))) related_model = field.remote_field.model._meta.concrete_model self._get_only_select_mask( related_model._meta, field_mask, field_select_mask ) return select_mask def get_select_mask(self): """ Convert the self.deferred_loading data structure to an alternate data structure, describing the field that *will* be loaded. This is used to compute the columns to select from the database and also by the QuerySet class to work out which fields are being initialized on each model. Models that have all their fields included aren't mentioned in the result, only those that have field restrictions in place. """ field_names, defer = self.deferred_loading if not field_names: return {} mask = {} for field_name in field_names: part_mask = mask for part in field_name.split(LOOKUP_SEP): part_mask = part_mask.setdefault(part, {}) opts = self.get_meta() if defer: return self._get_defer_select_mask(opts, mask) return self._get_only_select_mask(opts, mask) def table_alias(self, table_name, create=False, filtered_relation=None): """ Return a table alias for the given table_name and whether this is a new alias or not. If 'create' is true, a new alias is always created. Otherwise, the most recently created alias for the table (if one exists) is reused. """ alias_list = self.table_map.get(table_name) if not create and alias_list: alias = alias_list[0] self.alias_refcount[alias] += 1 return alias, False # Create a new alias for this table. if alias_list: alias = "%s%d" % (self.alias_prefix, len(self.alias_map) + 1) alias_list.append(alias) else: # The first occurrence of a table uses the table name directly. alias = ( filtered_relation.alias if filtered_relation is not None else table_name ) self.table_map[table_name] = [alias] self.alias_refcount[alias] = 1 return alias, True def ref_alias(self, alias): """Increases the reference count for this alias.""" self.alias_refcount[alias] += 1 def unref_alias(self, alias, amount=1): """Decreases the reference count for this alias.""" self.alias_refcount[alias] -= amount def promote_joins(self, aliases): """ Promote recursively the join type of given aliases and its children to an outer join. If 'unconditional' is False, only promote the join if it is nullable or the parent join is an outer join. The children promotion is done to avoid join chains that contain a LOUTER b INNER c. So, if we have currently a INNER b INNER c and a->b is promoted, then we must also promote b->c automatically, or otherwise the promotion of a->b doesn't actually change anything in the query results. """ aliases = list(aliases) while aliases: alias = aliases.pop(0) if self.alias_map[alias].join_type is None: # This is the base table (first FROM entry) - this table # isn't really joined at all in the query, so we should not # alter its join type. continue # Only the first alias (skipped above) should have None join_type assert self.alias_map[alias].join_type is not None parent_alias = self.alias_map[alias].parent_alias parent_louter = ( parent_alias and self.alias_map[parent_alias].join_type == LOUTER ) already_louter = self.alias_map[alias].join_type == LOUTER if (self.alias_map[alias].nullable or parent_louter) and not already_louter: self.alias_map[alias] = self.alias_map[alias].promote() # Join type of 'alias' changed, so re-examine all aliases that # refer to this one. aliases.extend( join for join in self.alias_map if self.alias_map[join].parent_alias == alias and join not in aliases ) def demote_joins(self, aliases): """ Change join type from LOUTER to INNER for all joins in aliases. Similarly to promote_joins(), this method must ensure no join chains containing first an outer, then an inner join are generated. If we are demoting b->c join in chain a LOUTER b LOUTER c then we must demote a->b automatically, or otherwise the demotion of b->c doesn't actually change anything in the query results. . """ aliases = list(aliases) while aliases: alias = aliases.pop(0) if self.alias_map[alias].join_type == LOUTER: self.alias_map[alias] = self.alias_map[alias].demote() parent_alias = self.alias_map[alias].parent_alias if self.alias_map[parent_alias].join_type == INNER: aliases.append(parent_alias) def reset_refcounts(self, to_counts): """ Reset reference counts for aliases so that they match the value passed in `to_counts`. """ for alias, cur_refcount in self.alias_refcount.copy().items(): unref_amount = cur_refcount - to_counts.get(alias, 0) self.unref_alias(alias, unref_amount) def change_aliases(self, change_map): """ Change the aliases in change_map (which maps old-alias -> new-alias), relabelling any references to them in select columns and the where clause. """ # If keys and values of change_map were to intersect, an alias might be # updated twice (e.g. T4 -> T5, T5 -> T6, so also T4 -> T6) depending # on their order in change_map. assert set(change_map).isdisjoint(change_map.values()) # 1. Update references in "select" (normal columns plus aliases), # "group by" and "where". self.where.relabel_aliases(change_map) if isinstance(self.group_by, tuple): self.group_by = tuple( [col.relabeled_clone(change_map) for col in self.group_by] ) self.select = tuple([col.relabeled_clone(change_map) for col in self.select]) self.annotations = self.annotations and { key: col.relabeled_clone(change_map) for key, col in self.annotations.items() } # 2. Rename the alias in the internal table/alias datastructures. for old_alias, new_alias in change_map.items(): if old_alias not in self.alias_map: continue alias_data = self.alias_map[old_alias].relabeled_clone(change_map) self.alias_map[new_alias] = alias_data self.alias_refcount[new_alias] = self.alias_refcount[old_alias] del self.alias_refcount[old_alias] del self.alias_map[old_alias] table_aliases = self.table_map[alias_data.table_name] for pos, alias in enumerate(table_aliases): if alias == old_alias: table_aliases[pos] = new_alias break self.external_aliases = { # Table is aliased or it's being changed and thus is aliased. change_map.get(alias, alias): (aliased or alias in change_map) for alias, aliased in self.external_aliases.items() } def bump_prefix(self, other_query, exclude=None): """ Change the alias prefix to the next letter in the alphabet in a way that the other query's aliases and this query's aliases will not conflict. Even tables that previously had no alias will get an alias after this call. To prevent changing aliases use the exclude parameter. """ def prefix_gen(): """ Generate a sequence of characters in alphabetical order: -> 'A', 'B', 'C', ... When the alphabet is finished, the sequence will continue with the Cartesian product: -> 'AA', 'AB', 'AC', ... """ alphabet = ascii_uppercase prefix = chr(ord(self.alias_prefix) + 1) yield prefix for n in count(1): seq = alphabet[alphabet.index(prefix) :] if prefix else alphabet for s in product(seq, repeat=n): yield "".join(s) prefix = None if self.alias_prefix != other_query.alias_prefix: # No clashes between self and outer query should be possible. return # Explicitly avoid infinite loop. The constant divider is based on how # much depth recursive subquery references add to the stack. This value # might need to be adjusted when adding or removing function calls from # the code path in charge of performing these operations. local_recursion_limit = sys.getrecursionlimit() // 16 for pos, prefix in enumerate(prefix_gen()): if prefix not in self.subq_aliases: self.alias_prefix = prefix break if pos > local_recursion_limit: raise RecursionError( "Maximum recursion depth exceeded: too many subqueries." ) self.subq_aliases = self.subq_aliases.union([self.alias_prefix]) other_query.subq_aliases = other_query.subq_aliases.union(self.subq_aliases) if exclude is None: exclude = {} self.change_aliases( { alias: "%s%d" % (self.alias_prefix, pos) for pos, alias in enumerate(self.alias_map) if alias not in exclude } ) def get_initial_alias(self): """ Return the first alias for this query, after increasing its reference count. """ if self.alias_map: alias = self.base_table self.ref_alias(alias) elif self.model: alias = self.join(self.base_table_class(self.get_meta().db_table, None)) else: alias = None return alias def count_active_tables(self): """ Return the number of tables in this query with a non-zero reference count. After execution, the reference counts are zeroed, so tables added in compiler will not be seen by this method. """ return len([1 for count in self.alias_refcount.values() if count]) def join(self, join, reuse=None): """ Return an alias for the 'join', either reusing an existing alias for that join or creating a new one. 'join' is either a base_table_class or join_class. The 'reuse' parameter can be either None which means all joins are reusable, or it can be a set containing the aliases that can be reused. A join is always created as LOUTER if the lhs alias is LOUTER to make sure chains like t1 LOUTER t2 INNER t3 aren't generated. All new joins are created as LOUTER if the join is nullable. """ reuse_aliases = [ a for a, j in self.alias_map.items() if (reuse is None or a in reuse) and j == join ] if reuse_aliases: if join.table_alias in reuse_aliases: reuse_alias = join.table_alias else: # Reuse the most recent alias of the joined table # (a many-to-many relation may be joined multiple times). reuse_alias = reuse_aliases[-1] self.ref_alias(reuse_alias) return reuse_alias # No reuse is possible, so we need a new alias. alias, _ = self.table_alias( join.table_name, create=True, filtered_relation=join.filtered_relation ) if join.join_type: if self.alias_map[join.parent_alias].join_type == LOUTER or join.nullable: join_type = LOUTER else: join_type = INNER join.join_type = join_type join.table_alias = alias self.alias_map[alias] = join if filtered_relation := join.filtered_relation: resolve_reuse = reuse if resolve_reuse is not None: resolve_reuse = set(reuse) | {alias} joins_len = len(self.alias_map) join.filtered_relation = filtered_relation.resolve_expression( self, reuse=resolve_reuse ) # Some joins were during expression resolving, they must be present # before the one we just added. if joins_len < len(self.alias_map): self.alias_map[alias] = self.alias_map.pop(alias) return alias def join_parent_model(self, opts, model, alias, seen): """ Make sure the given 'model' is joined in the query. If 'model' isn't a parent of 'opts' or if it is None this method is a no-op. The 'alias' is the root alias for starting the join, 'seen' is a dict of model -> alias of existing joins. It must also contain a mapping of None -> some alias. This will be returned in the no-op case. """ if model in seen: return seen[model] chain = opts.get_base_chain(model) if not chain: return alias curr_opts = opts for int_model in chain: if int_model in seen: curr_opts = int_model._meta alias = seen[int_model] continue # Proxy model have elements in base chain # with no parents, assign the new options # object and skip to the next base in that # case if not curr_opts.parents[int_model]: curr_opts = int_model._meta continue link_field = curr_opts.get_ancestor_link(int_model) join_info = self.setup_joins([link_field.name], curr_opts, alias) curr_opts = int_model._meta alias = seen[int_model] = join_info.joins[-1] return alias or seen[None] def check_alias(self, alias): if FORBIDDEN_ALIAS_PATTERN.search(alias): raise ValueError( "Column aliases cannot contain whitespace characters, quotation marks, " "semicolons, or SQL comments." ) def add_annotation(self, annotation, alias, select=True): """Add a single annotation expression to the Query.""" self.check_alias(alias) annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None) if select: self.append_annotation_mask([alias]) else: annotation_mask = ( value for value in dict.fromkeys(self.annotation_select) if value != alias ) self.set_annotation_mask(annotation_mask) self.annotations[alias] = annotation def resolve_expression(self, query, *args, **kwargs): clone = self.clone() # Subqueries need to use a different set of aliases than the outer query. clone.bump_prefix(query) clone.subquery = True clone.where.resolve_expression(query, *args, **kwargs) # Resolve combined queries. if clone.combinator: clone.combined_queries = tuple( [ combined_query.resolve_expression(query, *args, **kwargs) for combined_query in clone.combined_queries ] ) for key, value in clone.annotations.items(): resolved = value.resolve_expression(query, *args, **kwargs) if hasattr(resolved, "external_aliases"): resolved.external_aliases.update(clone.external_aliases) clone.annotations[key] = resolved # Outer query's aliases are considered external. for alias, table in query.alias_map.items(): clone.external_aliases[alias] = ( isinstance(table, Join) and table.join_field.related_model._meta.db_table != alias ) or ( isinstance(table, BaseTable) and table.table_name != table.table_alias ) return clone def get_external_cols(self): exprs = chain(self.annotations.values(), self.where.children) return [ col for col in self._gen_cols(exprs, include_external=True) if col.alias in self.external_aliases ] def get_group_by_cols(self, wrapper=None): # If wrapper is referenced by an alias for an explicit GROUP BY through # values() a reference to this expression and not the self must be # returned to ensure external column references are not grouped against # as well. external_cols = self.get_external_cols() if any(col.possibly_multivalued for col in external_cols): return [wrapper or self] return external_cols def as_sql(self, compiler, connection): # Some backends (e.g. Oracle) raise an error when a subquery contains # unnecessary ORDER BY clause. if ( self.subquery and not connection.features.ignores_unnecessary_order_by_in_subqueries ): self.clear_ordering(force=False) for query in self.combined_queries: query.clear_ordering(force=False) sql, params = self.get_compiler(connection=connection).as_sql() if self.subquery: sql = "(%s)" % sql return sql, params def resolve_lookup_value(self, value, can_reuse, allow_joins): if hasattr(value, "resolve_expression"): value = value.resolve_expression( self, reuse=can_reuse, allow_joins=allow_joins, ) elif isinstance(value, (list, tuple)): # The items of the iterable may be expressions and therefore need # to be resolved independently. values = ( self.resolve_lookup_value(sub_value, can_reuse, allow_joins) for sub_value in value ) type_ = type(value) if hasattr(type_, "_make"): # namedtuple return type_(*values) return type_(values) return value def solve_lookup_type(self, lookup, summarize=False): """ Solve the lookup type from the lookup (e.g.: 'foobar__id__icontains'). """ lookup_splitted = lookup.split(LOOKUP_SEP) if self.annotations: annotation, expression_lookups = refs_expression( lookup_splitted, self.annotations ) if annotation: expression = self.annotations[annotation] if summarize: expression = Ref(annotation, expression) return expression_lookups, (), expression _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) field_parts = lookup_splitted[0 : len(lookup_splitted) - len(lookup_parts)] if len(lookup_parts) > 1 and not field_parts: raise FieldError( 'Invalid lookup "%s" for model %s".' % (lookup, self.get_meta().model.__name__) ) return lookup_parts, field_parts, False def check_query_object_type(self, value, opts, field): """ Check whether the object passed while querying is of the correct type. If not, raise a ValueError specifying the wrong object. """ if hasattr(value, "_meta"): if not check_rel_lookup_compatibility(value._meta.model, opts, field): raise ValueError( 'Cannot query "%s": Must be "%s" instance.' % (value, opts.object_name) ) def check_related_objects(self, field, value, opts): """Check the type of object passed to query relations.""" if field.is_relation: # Check that the field and the queryset use the same model in a # query like .filter(author=Author.objects.all()). For example, the # opts would be Author's (from the author field) and value.model # would be Author.objects.all() queryset's .model (Author also). # The field is the related field on the lhs side. if ( isinstance(value, Query) and not value.has_select_fields and not check_rel_lookup_compatibility(value.model, opts, field) ): raise ValueError( 'Cannot use QuerySet for "%s": Use a QuerySet for "%s".' % (value.model._meta.object_name, opts.object_name) ) elif hasattr(value, "_meta"): self.check_query_object_type(value, opts, field) elif hasattr(value, "__iter__"): for v in value: self.check_query_object_type(v, opts, field) def check_filterable(self, expression): """Raise an error if expression cannot be used in a WHERE clause.""" if hasattr(expression, "resolve_expression") and not getattr( expression, "filterable", True ): raise NotSupportedError( expression.__class__.__name__ + " is disallowed in the filter " "clause." ) if hasattr(expression, "get_source_expressions"): for expr in expression.get_source_expressions(): self.check_filterable(expr) def build_lookup(self, lookups, lhs, rhs): """ Try to extract transforms and lookup from given lhs. The lhs value is something that works like SQLExpression. The rhs value is what the lookup is going to compare against. The lookups is a list of names to extract using get_lookup() and get_transform(). """ # __exact is the default lookup if one isn't given. *transforms, lookup_name = lookups or ["exact"] for name in transforms: lhs = self.try_transform(lhs, name) # First try get_lookup() so that the lookup takes precedence if the lhs # supports both transform and lookup for the name. lookup_class = lhs.get_lookup(lookup_name) if not lookup_class: # A lookup wasn't found. Try to interpret the name as a transform # and do an Exact lookup against it. lhs = self.try_transform(lhs, lookup_name) lookup_name = "exact" lookup_class = lhs.get_lookup(lookup_name) if not lookup_class: return lookup = lookup_class(lhs, rhs) # Interpret '__exact=None' as the sql 'is NULL'; otherwise, reject all # uses of None as a query value unless the lookup supports it. if lookup.rhs is None and not lookup.can_use_none_as_rhs: if lookup_name not in ("exact", "iexact"): raise ValueError("Cannot use None as a query value") return lhs.get_lookup("isnull")(lhs, True) # For Oracle '' is equivalent to null. The check must be done at this # stage because join promotion can't be done in the compiler. Using # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here. # A similar thing is done in is_nullable(), too. if ( lookup_name == "exact" and lookup.rhs == "" and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls ): return lhs.get_lookup("isnull")(lhs, True) return lookup def try_transform(self, lhs, name): """ Helper method for build_lookup(). Try to fetch and initialize a transform for name parameter from lhs. """ transform_class = lhs.get_transform(name) if transform_class: return transform_class(lhs) else: output_field = lhs.output_field.__class__ suggested_lookups = difflib.get_close_matches( name, lhs.output_field.get_lookups() ) if suggested_lookups: suggestion = ", perhaps you meant %s?" % " or ".join(suggested_lookups) else: suggestion = "." raise FieldError( "Unsupported lookup '%s' for %s or join on the field not " "permitted%s" % (name, output_field.__name__, suggestion) ) def build_filter( self, filter_expr, branch_negated=False, current_negated=False, can_reuse=None, allow_joins=True, split_subq=True, check_filterable=True, summarize=False, update_join_types=True, ): """ Build a WhereNode for a single filter clause but don't add it to this Query. Query.add_q() will then add this filter to the where Node. The 'branch_negated' tells us if the current branch contains any negations. This will be used to determine if subqueries are needed. The 'current_negated' is used to determine if the current filter is negated or not and this will be used to determine if IS NULL filtering is needed. The difference between current_negated and branch_negated is that branch_negated is set on first negation, but current_negated is flipped for each negation. Note that add_filter will not do any negating itself, that is done upper in the code by add_q(). The 'can_reuse' is a set of reusable joins for multijoins. The method will create a filter clause that can be added to the current query. However, if the filter isn't added to the query then the caller is responsible for unreffing the joins used. """ if isinstance(filter_expr, dict): raise FieldError("Cannot parse keyword query as dict") if isinstance(filter_expr, Q): return self._add_q( filter_expr, branch_negated=branch_negated, current_negated=current_negated, used_aliases=can_reuse, allow_joins=allow_joins, split_subq=split_subq, check_filterable=check_filterable, summarize=summarize, update_join_types=update_join_types, ) if hasattr(filter_expr, "resolve_expression"): if not getattr(filter_expr, "conditional", False): raise TypeError("Cannot filter against a non-conditional expression.") condition = filter_expr.resolve_expression( self, allow_joins=allow_joins, reuse=can_reuse, summarize=summarize ) if not isinstance(condition, Lookup): condition = self.build_lookup(["exact"], condition, True) return WhereNode([condition], connector=AND), [] arg, value = filter_expr if not arg: raise FieldError("Cannot parse keyword query %r" % arg) lookups, parts, reffed_expression = self.solve_lookup_type(arg, summarize) if check_filterable: self.check_filterable(reffed_expression) if not allow_joins and len(parts) > 1: raise FieldError("Joined field references are not permitted in this query") pre_joins = self.alias_refcount.copy() value = self.resolve_lookup_value(value, can_reuse, allow_joins) used_joins = { k for k, v in self.alias_refcount.items() if v > pre_joins.get(k, 0) } if check_filterable: self.check_filterable(value) if reffed_expression: condition = self.build_lookup(lookups, reffed_expression, value) return WhereNode([condition], connector=AND), [] opts = self.get_meta() alias = self.get_initial_alias() allow_many = not branch_negated or not split_subq try: join_info = self.setup_joins( parts, opts, alias, can_reuse=can_reuse, allow_many=allow_many, ) # Prevent iterator from being consumed by check_related_objects() if isinstance(value, Iterator): value = list(value) self.check_related_objects(join_info.final_field, value, join_info.opts) # split_exclude() needs to know which joins were generated for the # lookup parts self._lookup_joins = join_info.joins except MultiJoin as e: return self.split_exclude(filter_expr, can_reuse, e.names_with_path) # Update used_joins before trimming since they are reused to determine # which joins could be later promoted to INNER. used_joins.update(join_info.joins) targets, alias, join_list = self.trim_joins( join_info.targets, join_info.joins, join_info.path ) if can_reuse is not None: can_reuse.update(join_list) if join_info.final_field.is_relation: if len(targets) == 1: col = self._get_col(targets[0], join_info.final_field, alias) else: col = MultiColSource( alias, targets, join_info.targets, join_info.final_field ) else: col = self._get_col(targets[0], join_info.final_field, alias) condition = self.build_lookup(lookups, col, value) lookup_type = condition.lookup_name clause = WhereNode([condition], connector=AND) require_outer = ( lookup_type == "isnull" and condition.rhs is True and not current_negated ) if ( current_negated and (lookup_type != "isnull" or condition.rhs is False) and condition.rhs is not None ): require_outer = True if lookup_type != "isnull": # The condition added here will be SQL like this: # NOT (col IS NOT NULL), where the first NOT is added in # upper layers of code. The reason for addition is that if col # is null, then col != someval will result in SQL "unknown" # which isn't the same as in Python. The Python None handling # is wanted, and it can be gotten by # (col IS NULL OR col != someval) # <=> # NOT (col IS NOT NULL AND col = someval). if ( self.is_nullable(targets[0]) or self.alias_map[join_list[-1]].join_type == LOUTER ): lookup_class = targets[0].get_lookup("isnull") col = self._get_col(targets[0], join_info.targets[0], alias) clause.add(lookup_class(col, False), AND) # If someval is a nullable column, someval IS NOT NULL is # added. if isinstance(value, Col) and self.is_nullable(value.target): lookup_class = value.target.get_lookup("isnull") clause.add(lookup_class(value, False), AND) return clause, used_joins if not require_outer else () def add_filter(self, filter_lhs, filter_rhs): self.add_q(Q((filter_lhs, filter_rhs))) def add_q(self, q_object): """ A preprocessor for the internal _add_q(). Responsible for doing final join promotion. """ # For join promotion this case is doing an AND for the added q_object # and existing conditions. So, any existing inner join forces the join # type to remain inner. Existing outer joins can however be demoted. # (Consider case where rel_a is LOUTER and rel_a__col=1 is added - if # rel_a doesn't produce any rows, then the whole condition must fail. # So, demotion is OK. existing_inner = { a for a in self.alias_map if self.alias_map[a].join_type == INNER } clause, _ = self._add_q(q_object, self.used_aliases) if clause: self.where.add(clause, AND) self.demote_joins(existing_inner) def build_where(self, filter_expr): return self.build_filter(filter_expr, allow_joins=False)[0] def clear_where(self): self.where = WhereNode() def _add_q( self, q_object, used_aliases, branch_negated=False, current_negated=False, allow_joins=True, split_subq=True, check_filterable=True, summarize=False, update_join_types=True, ): """Add a Q-object to the current filter.""" connector = q_object.connector current_negated ^= q_object.negated branch_negated = branch_negated or q_object.negated target_clause = WhereNode(connector=connector, negated=q_object.negated) joinpromoter = JoinPromoter( q_object.connector, len(q_object.children), current_negated ) for child in q_object.children: child_clause, needed_inner = self.build_filter( child, can_reuse=used_aliases, branch_negated=branch_negated, current_negated=current_negated, allow_joins=allow_joins, split_subq=split_subq, check_filterable=check_filterable, summarize=summarize, update_join_types=update_join_types, ) joinpromoter.add_votes(needed_inner) if child_clause: target_clause.add(child_clause, connector) if update_join_types: needed_inner = joinpromoter.update_join_types(self) else: needed_inner = [] return target_clause, needed_inner def add_filtered_relation(self, filtered_relation, alias): filtered_relation.alias = alias lookups = dict(get_children_from_q(filtered_relation.condition)) relation_lookup_parts, relation_field_parts, _ = self.solve_lookup_type( filtered_relation.relation_name ) if relation_lookup_parts: raise ValueError( "FilteredRelation's relation_name cannot contain lookups " "(got %r)." % filtered_relation.relation_name ) for lookup in chain(lookups): lookup_parts, lookup_field_parts, _ = self.solve_lookup_type(lookup) shift = 2 if not lookup_parts else 1 lookup_field_path = lookup_field_parts[:-shift] for idx, lookup_field_part in enumerate(lookup_field_path): if len(relation_field_parts) > idx: if relation_field_parts[idx] != lookup_field_part: raise ValueError( "FilteredRelation's condition doesn't support " "relations outside the %r (got %r)." % (filtered_relation.relation_name, lookup) ) else: raise ValueError( "FilteredRelation's condition doesn't support nested " "relations deeper than the relation_name (got %r for " "%r)." % (lookup, filtered_relation.relation_name) ) filtered_relation.condition = rename_prefix_from_q( filtered_relation.relation_name, alias, filtered_relation.condition, ) self._filtered_relations[filtered_relation.alias] = filtered_relation def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False): """ Walk the list of names and turns them into PathInfo tuples. A single name in 'names' can generate multiple PathInfos (m2m, for example). 'names' is the path of names to travel, 'opts' is the model Options we start the name resolving from, 'allow_many' is as for setup_joins(). If fail_on_missing is set to True, then a name that can't be resolved will generate a FieldError. Return a list of PathInfo tuples. In addition return the final field (the last used join field) and target (which is a field guaranteed to contain the same value as the final field). Finally, return those names that weren't found (which are likely transforms and the final lookup). """ path, names_with_path = [], [] for pos, name in enumerate(names): cur_names_with_path = (name, []) if name == "pk": name = opts.pk.name field = None filtered_relation = None try: if opts is None: raise FieldDoesNotExist field = opts.get_field(name) except FieldDoesNotExist: if name in self.annotation_select: field = self.annotation_select[name].output_field elif name in self._filtered_relations and pos == 0: filtered_relation = self._filtered_relations[name] if LOOKUP_SEP in filtered_relation.relation_name: parts = filtered_relation.relation_name.split(LOOKUP_SEP) filtered_relation_path, field, _, _ = self.names_to_path( parts, opts, allow_many, fail_on_missing, ) path.extend(filtered_relation_path[:-1]) else: field = opts.get_field(filtered_relation.relation_name) if field is not None: # Fields that contain one-to-many relations with a generic # model (like a GenericForeignKey) cannot generate reverse # relations and therefore cannot be used for reverse querying. if field.is_relation and not field.related_model: raise FieldError( "Field %r does not generate an automatic reverse " "relation and therefore cannot be used for reverse " "querying. If it is a GenericForeignKey, consider " "adding a GenericRelation." % name ) try: model = field.model._meta.concrete_model except AttributeError: # QuerySet.annotate() may introduce fields that aren't # attached to a model. model = None else: # We didn't find the current field, so move position back # one step. pos -= 1 if pos == -1 or fail_on_missing: available = sorted( [ *get_field_names_from_opts(opts), *self.annotation_select, *self._filtered_relations, ] ) raise FieldError( "Cannot resolve keyword '%s' into field. " "Choices are: %s" % (name, ", ".join(available)) ) break # Check if we need any joins for concrete inheritance cases (the # field lives in parent, but we are currently in one of its # children) if opts is not None and model is not opts.model: path_to_parent = opts.get_path_to_parent(model) if path_to_parent: path.extend(path_to_parent) cur_names_with_path[1].extend(path_to_parent) opts = path_to_parent[-1].to_opts if hasattr(field, "path_infos"): if filtered_relation: pathinfos = field.get_path_info(filtered_relation) else: pathinfos = field.path_infos if not allow_many: for inner_pos, p in enumerate(pathinfos): if p.m2m: cur_names_with_path[1].extend(pathinfos[0 : inner_pos + 1]) names_with_path.append(cur_names_with_path) raise MultiJoin(pos + 1, names_with_path) last = pathinfos[-1] path.extend(pathinfos) final_field = last.join_field opts = last.to_opts targets = last.target_fields cur_names_with_path[1].extend(pathinfos) names_with_path.append(cur_names_with_path) else: # Local non-relational field. final_field = field targets = (field,) if fail_on_missing and pos + 1 != len(names): raise FieldError( "Cannot resolve keyword %r into field. Join on '%s'" " not permitted." % (names[pos + 1], name) ) break return path, final_field, targets, names[pos + 1 :] def setup_joins( self, names, opts, alias, can_reuse=None, allow_many=True, ): """ Compute the necessary table joins for the passage through the fields given in 'names'. 'opts' is the Options class for the current model (which gives the table we are starting from), 'alias' is the alias for the table to start the joining from. The 'can_reuse' defines the reverse foreign key joins we can reuse. It can be None in which case all joins are reusable or a set of aliases that can be reused. Note that non-reverse foreign keys are always reusable when using setup_joins(). If 'allow_many' is False, then any reverse foreign key seen will generate a MultiJoin exception. Return the final field involved in the joins, the target field (used for any 'where' constraint), the final 'opts' value, the joins, the field path traveled to generate the joins, and a transform function that takes a field and alias and is equivalent to `field.get_col(alias)` in the simple case but wraps field transforms if they were included in names. The target field is the field containing the concrete value. Final field can be something different, for example foreign key pointing to that value. Final field is needed for example in some value conversions (convert 'obj' in fk__id=obj to pk val using the foreign key field for example). """ joins = [alias] # The transform can't be applied yet, as joins must be trimmed later. # To avoid making every caller of this method look up transforms # directly, compute transforms here and create a partial that converts # fields to the appropriate wrapped version. def final_transformer(field, alias): if not self.alias_cols: alias = None return field.get_col(alias) # Try resolving all the names as fields first. If there's an error, # treat trailing names as lookups until a field can be resolved. last_field_exception = None for pivot in range(len(names), 0, -1): try: path, final_field, targets, rest = self.names_to_path( names[:pivot], opts, allow_many, fail_on_missing=True, ) except FieldError as exc: if pivot == 1: # The first item cannot be a lookup, so it's safe # to raise the field error here. raise else: last_field_exception = exc else: # The transforms are the remaining items that couldn't be # resolved into fields. transforms = names[pivot:] break for name in transforms: def transform(field, alias, *, name, previous): try: wrapped = previous(field, alias) return self.try_transform(wrapped, name) except FieldError: # FieldError is raised if the transform doesn't exist. if isinstance(final_field, Field) and last_field_exception: raise last_field_exception else: raise final_transformer = functools.partial( transform, name=name, previous=final_transformer ) final_transformer.has_transforms = True # Then, add the path to the query's joins. Note that we can't trim # joins at this stage - we will need the information about join type # of the trimmed joins. for join in path: if join.filtered_relation: filtered_relation = join.filtered_relation.clone() table_alias = filtered_relation.alias else: filtered_relation = None table_alias = None opts = join.to_opts if join.direct: nullable = self.is_nullable(join.join_field) else: nullable = True connection = self.join_class( opts.db_table, alias, table_alias, INNER, join.join_field, nullable, filtered_relation=filtered_relation, ) reuse = can_reuse if join.m2m else None alias = self.join(connection, reuse=reuse) joins.append(alias) return JoinInfo(final_field, targets, opts, joins, path, final_transformer) def trim_joins(self, targets, joins, path): """ The 'target' parameter is the final field being joined to, 'joins' is the full list of join aliases. The 'path' contain the PathInfos used to create the joins. Return the final target field and table alias and the new active joins. Always trim any direct join if the target column is already in the previous table. Can't trim reverse joins as it's unknown if there's anything on the other side of the join. """ joins = joins[:] for pos, info in enumerate(reversed(path)): if len(joins) == 1 or not info.direct: break if info.filtered_relation: break join_targets = {t.column for t in info.join_field.foreign_related_fields} cur_targets = {t.column for t in targets} if not cur_targets.issubset(join_targets): break targets_dict = { r[1].column: r[0] for r in info.join_field.related_fields if r[1].column in cur_targets } targets = tuple(targets_dict[t.column] for t in targets) self.unref_alias(joins.pop()) return targets, joins[-1], joins @classmethod def _gen_cols(cls, exprs, include_external=False, resolve_refs=True): for expr in exprs: if isinstance(expr, Col): yield expr elif include_external and callable( getattr(expr, "get_external_cols", None) ): yield from expr.get_external_cols() elif hasattr(expr, "get_source_expressions"): if not resolve_refs and isinstance(expr, Ref): continue yield from cls._gen_cols( expr.get_source_expressions(), include_external=include_external, resolve_refs=resolve_refs, ) @classmethod def _gen_col_aliases(cls, exprs): yield from (expr.alias for expr in cls._gen_cols(exprs)) def resolve_ref(self, name, allow_joins=True, reuse=None, summarize=False): annotation = self.annotations.get(name) if annotation is not None: if not allow_joins: for alias in self._gen_col_aliases([annotation]): if isinstance(self.alias_map[alias], Join): raise FieldError( "Joined field references are not permitted in this query" ) if summarize: # Summarize currently means we are doing an aggregate() query # which is executed as a wrapped subquery if any of the # aggregate() elements reference an existing annotation. In # that case we need to return a Ref to the subquery's annotation. if name not in self.annotation_select: raise FieldError( "Cannot aggregate over the '%s' alias. Use annotate() " "to promote it." % name ) return Ref(name, self.annotation_select[name]) else: return annotation else: field_list = name.split(LOOKUP_SEP) annotation = self.annotations.get(field_list[0]) if annotation is not None: for transform in field_list[1:]: annotation = self.try_transform(annotation, transform) return annotation join_info = self.setup_joins( field_list, self.get_meta(), self.get_initial_alias(), can_reuse=reuse ) targets, final_alias, join_list = self.trim_joins( join_info.targets, join_info.joins, join_info.path ) if not allow_joins and len(join_list) > 1: raise FieldError( "Joined field references are not permitted in this query" ) if len(targets) > 1: raise FieldError( "Referencing multicolumn fields with F() objects isn't supported" ) # Verify that the last lookup in name is a field or a transform: # transform_function() raises FieldError if not. transform = join_info.transform_function(targets[0], final_alias) if reuse is not None: reuse.update(join_list) return transform def split_exclude(self, filter_expr, can_reuse, names_with_path): """ When doing an exclude against any kind of N-to-many relation, we need to use a subquery. This method constructs the nested query, given the original exclude filter (filter_expr) and the portion up to the first N-to-many relation field. For example, if the origin filter is ~Q(child__name='foo'), filter_expr is ('child__name', 'foo') and can_reuse is a set of joins usable for filters in the original query. We will turn this into equivalent of: WHERE NOT EXISTS( SELECT 1 FROM child WHERE name = 'foo' AND child.parent_id = parent.id LIMIT 1 ) """ # Generate the inner query. query = self.__class__(self.model) query._filtered_relations = self._filtered_relations filter_lhs, filter_rhs = filter_expr if isinstance(filter_rhs, OuterRef): filter_rhs = OuterRef(filter_rhs) elif isinstance(filter_rhs, F): filter_rhs = OuterRef(filter_rhs.name) query.add_filter(filter_lhs, filter_rhs) query.clear_ordering(force=True) # Try to have as simple as possible subquery -> trim leading joins from # the subquery. trimmed_prefix, contains_louter = query.trim_start(names_with_path) col = query.select[0] select_field = col.target alias = col.alias if alias in can_reuse: pk = select_field.model._meta.pk # Need to add a restriction so that outer query's filters are in effect for # the subquery, too. query.bump_prefix(self) lookup_class = select_field.get_lookup("exact") # Note that the query.select[0].alias is different from alias # due to bump_prefix above. lookup = lookup_class(pk.get_col(query.select[0].alias), pk.get_col(alias)) query.where.add(lookup, AND) query.external_aliases[alias] = True lookup_class = select_field.get_lookup("exact") lookup = lookup_class(col, ResolvedOuterRef(trimmed_prefix)) query.where.add(lookup, AND) condition, needed_inner = self.build_filter(Exists(query)) if contains_louter: or_null_condition, _ = self.build_filter( ("%s__isnull" % trimmed_prefix, True), current_negated=True, branch_negated=True, can_reuse=can_reuse, ) condition.add(or_null_condition, OR) # Note that the end result will be: # (outercol NOT IN innerq AND outercol IS NOT NULL) OR outercol IS NULL. # This might look crazy but due to how IN works, this seems to be # correct. If the IS NOT NULL check is removed then outercol NOT # IN will return UNKNOWN. If the IS NULL check is removed, then if # outercol IS NULL we will not match the row. return condition, needed_inner def set_empty(self): self.where.add(NothingNode(), AND) for query in self.combined_queries: query.set_empty() def is_empty(self): return any(isinstance(c, NothingNode) for c in self.where.children) def set_limits(self, low=None, high=None): """ Adjust the limits on the rows retrieved. Use low/high to set these, as it makes it more Pythonic to read and write. When the SQL query is created, convert them to the appropriate offset and limit values. Apply any limits passed in here to the existing constraints. Add low to the current low value and clamp both to any existing high value. """ if high is not None: if self.high_mark is not None: self.high_mark = min(self.high_mark, self.low_mark + high) else: self.high_mark = self.low_mark + high if low is not None: if self.high_mark is not None: self.low_mark = min(self.high_mark, self.low_mark + low) else: self.low_mark = self.low_mark + low if self.low_mark == self.high_mark: self.set_empty() def clear_limits(self): """Clear any existing limits.""" self.low_mark, self.high_mark = 0, None @property def is_sliced(self): return self.low_mark != 0 or self.high_mark is not None def has_limit_one(self): return self.high_mark is not None and (self.high_mark - self.low_mark) == 1 def can_filter(self): """ Return True if adding filters to this instance is still possible. Typically, this means no limits or offsets have been put on the results. """ return not self.is_sliced def clear_select_clause(self): """Remove all fields from SELECT clause.""" self.select = () self.default_cols = False self.select_related = False self.set_extra_mask(()) self.set_annotation_mask(()) def clear_select_fields(self): """ Clear the list of fields to select (but not extra_select columns). Some queryset types completely replace any existing list of select columns. """ self.select = () self.values_select = () def add_select_col(self, col, name): self.select += (col,) self.values_select += (name,) def set_select(self, cols): self.default_cols = False self.select = tuple(cols) def add_distinct_fields(self, *field_names): """ Add and resolve the given fields to the query's "distinct on" clause. """ self.distinct_fields = field_names self.distinct = True def add_fields(self, field_names, allow_m2m=True): """ Add the given (model) fields to the select set. Add the field names in the order specified. """ alias = self.get_initial_alias() opts = self.get_meta() try: cols = [] for name in field_names: # Join promotion note - we must not remove any rows here, so # if there is no existing joins, use outer join. join_info = self.setup_joins( name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m ) targets, final_alias, joins = self.trim_joins( join_info.targets, join_info.joins, join_info.path, ) for target in targets: cols.append(join_info.transform_function(target, final_alias)) if cols: self.set_select(cols) except MultiJoin: raise FieldError("Invalid field name: '%s'" % name) except FieldError: if LOOKUP_SEP in name: # For lookups spanning over relationships, show the error # from the model on which the lookup failed. raise else: names = sorted( [ *get_field_names_from_opts(opts), *self.extra, *self.annotation_select, *self._filtered_relations, ] ) raise FieldError( "Cannot resolve keyword %r into field. " "Choices are: %s" % (name, ", ".join(names)) ) def add_ordering(self, *ordering): """ Add items from the 'ordering' sequence to the query's "order by" clause. These items are either field names (not column names) -- possibly with a direction prefix ('-' or '?') -- or OrderBy expressions. If 'ordering' is empty, clear all ordering from the query. """ errors = [] for item in ordering: if isinstance(item, str): if item == "?": continue item = item.removeprefix("-") if item in self.annotations: continue if self.extra and item in self.extra: continue # names_to_path() validates the lookup. A descriptive # FieldError will be raise if it's not. self.names_to_path(item.split(LOOKUP_SEP), self.model._meta) elif not hasattr(item, "resolve_expression"): errors.append(item) if getattr(item, "contains_aggregate", False): raise FieldError( "Using an aggregate in order_by() without also including " "it in annotate() is not allowed: %s" % item ) if errors: raise FieldError("Invalid order_by arguments: %s" % errors) if ordering: self.order_by += ordering else: self.default_ordering = False def clear_ordering(self, force=False, clear_default=True): """ Remove any ordering settings if the current query allows it without side effects, set 'force' to True to clear the ordering regardless. If 'clear_default' is True, there will be no ordering in the resulting query (not even the model's default). """ if not force and ( self.is_sliced or self.distinct_fields or self.select_for_update ): return self.order_by = () self.extra_order_by = () if clear_default: self.default_ordering = False def set_group_by(self, allow_aliases=True): """ Expand the GROUP BY clause required by the query. This will usually be the set of all non-aggregate fields in the return data. If the database backend supports grouping by the primary key, and the query would be equivalent, the optimization will be made automatically. """ if allow_aliases and self.values_select: # If grouping by aliases is allowed assign selected value aliases # by moving them to annotations. group_by_annotations = {} values_select = {} for alias, expr in zip(self.values_select, self.select): if isinstance(expr, Col): values_select[alias] = expr else: group_by_annotations[alias] = expr self.annotations = {**group_by_annotations, **self.annotations} self.append_annotation_mask(group_by_annotations) self.select = tuple(values_select.values()) self.values_select = tuple(values_select) group_by = list(self.select) for alias, annotation in self.annotation_select.items(): if not (group_by_cols := annotation.get_group_by_cols()): continue if allow_aliases and not annotation.contains_aggregate: group_by.append(Ref(alias, annotation)) else: group_by.extend(group_by_cols) self.group_by = tuple(group_by) def add_select_related(self, fields): """ Set up the select_related data structure so that we only select certain related models (as opposed to all models, when self.select_related=True). """ if isinstance(self.select_related, bool): field_dict = {} else: field_dict = self.select_related for field in fields: d = field_dict for part in field.split(LOOKUP_SEP): d = d.setdefault(part, {}) self.select_related = field_dict def add_extra(self, select, select_params, where, params, tables, order_by): """ Add data to the various extra_* attributes for user-created additions to the query. """ if select: # We need to pair any placeholder markers in the 'select' # dictionary with their parameters in 'select_params' so that # subsequent updates to the select dictionary also adjust the # parameters appropriately. select_pairs = {} if select_params: param_iter = iter(select_params) else: param_iter = iter([]) for name, entry in select.items(): self.check_alias(name) entry = str(entry) entry_params = [] pos = entry.find("%s") while pos != -1: if pos == 0 or entry[pos - 1] != "%": entry_params.append(next(param_iter)) pos = entry.find("%s", pos + 2) select_pairs[name] = (entry, entry_params) self.extra.update(select_pairs) if where or params: self.where.add(ExtraWhere(where, params), AND) if tables: self.extra_tables += tuple(tables) if order_by: self.extra_order_by = order_by def clear_deferred_loading(self): """Remove any fields from the deferred loading set.""" self.deferred_loading = (frozenset(), True) def add_deferred_loading(self, field_names): """ Add the given list of model field names to the set of fields to exclude from loading from the database when automatic column selection is done. Add the new field names to any existing field names that are deferred (or removed from any existing field names that are marked as the only ones for immediate loading). """ # Fields on related models are stored in the literal double-underscore # format, so that we can use a set datastructure. We do the foo__bar # splitting and handling when computing the SQL column names (as part of # get_columns()). existing, defer = self.deferred_loading if defer: # Add to existing deferred names. self.deferred_loading = existing.union(field_names), True else: # Remove names from the set of any existing "immediate load" names. if new_existing := existing.difference(field_names): self.deferred_loading = new_existing, False else: self.clear_deferred_loading() if new_only := set(field_names).difference(existing): self.deferred_loading = new_only, True def add_immediate_loading(self, field_names): """ Add the given list of model field names to the set of fields to retrieve when the SQL is executed ("immediate loading" fields). The field names replace any existing immediate loading field names. If there are field names already specified for deferred loading, remove those names from the new field_names before storing the new names for immediate loading. (That is, immediate loading overrides any existing immediate values, but respects existing deferrals.) """ existing, defer = self.deferred_loading field_names = set(field_names) if "pk" in field_names: field_names.remove("pk") field_names.add(self.get_meta().pk.name) if defer: # Remove any existing deferred names from the current set before # setting the new names. self.deferred_loading = field_names.difference(existing), False else: # Replace any existing "immediate load" field names. self.deferred_loading = frozenset(field_names), False def set_annotation_mask(self, names): """Set the mask of annotations that will be returned by the SELECT.""" if names is None: self.annotation_select_mask = None else: self.annotation_select_mask = list(dict.fromkeys(names)) self._annotation_select_cache = None def append_annotation_mask(self, names): if self.annotation_select_mask is not None: self.set_annotation_mask((*self.annotation_select_mask, *names)) def set_extra_mask(self, names): """ Set the mask of extra select items that will be returned by SELECT. Don't remove them from the Query since they might be used later. """ if names is None: self.extra_select_mask = None else: self.extra_select_mask = set(names) self._extra_select_cache = None def set_values(self, fields): self.select_related = False self.clear_deferred_loading() self.clear_select_fields() self.has_select_fields = True if fields: field_names = [] extra_names = [] annotation_names = [] if not self.extra and not self.annotations: # Shortcut - if there are no extra or annotations, then # the values() clause must be just field names. field_names = list(fields) else: self.default_cols = False for f in fields: if f in self.extra_select: extra_names.append(f) elif f in self.annotation_select: annotation_names.append(f) elif f in self.annotations: raise FieldError( f"Cannot select the '{f}' alias. Use annotate() to " "promote it." ) else: # Call `names_to_path` to ensure a FieldError including # annotations about to be masked as valid choices if # `f` is not resolvable. if self.annotation_select: self.names_to_path(f.split(LOOKUP_SEP), self.model._meta) field_names.append(f) self.set_extra_mask(extra_names) self.set_annotation_mask(annotation_names) selected = frozenset(field_names + extra_names + annotation_names) else: field_names = [f.attname for f in self.model._meta.concrete_fields] selected = frozenset(field_names) # Selected annotations must be known before setting the GROUP BY # clause. if self.group_by is True: self.add_fields( (f.attname for f in self.model._meta.concrete_fields), False ) # Disable GROUP BY aliases to avoid orphaning references to the # SELECT clause which is about to be cleared. self.set_group_by(allow_aliases=False) self.clear_select_fields() elif self.group_by: # Resolve GROUP BY annotation references if they are not part of # the selected fields anymore. group_by = [] for expr in self.group_by: if isinstance(expr, Ref) and expr.refs not in selected: expr = self.annotations[expr.refs] group_by.append(expr) self.group_by = tuple(group_by) self.values_select = tuple(field_names) self.add_fields(field_names, True) @property def annotation_select(self): """ Return the dictionary of aggregate columns that are not masked and should be used in the SELECT clause. Cache this result for performance. """ if self._annotation_select_cache is not None: return self._annotation_select_cache elif not self.annotations: return {} elif self.annotation_select_mask is not None: self._annotation_select_cache = { k: self.annotations[k] for k in self.annotation_select_mask if k in self.annotations } return self._annotation_select_cache else: return self.annotations @property def extra_select(self): if self._extra_select_cache is not None: return self._extra_select_cache if not self.extra: return {} elif self.extra_select_mask is not None: self._extra_select_cache = { k: v for k, v in self.extra.items() if k in self.extra_select_mask } return self._extra_select_cache else: return self.extra def trim_start(self, names_with_path): """ Trim joins from the start of the join path. The candidates for trim are the PathInfos in names_with_path structure that are m2m joins. Also set the select column so the start matches the join. This method is meant to be used for generating the subquery joins & cols in split_exclude(). Return a lookup usable for doing outerq.filter(lookup=self) and a boolean indicating if the joins in the prefix contain a LEFT OUTER join. _""" all_paths = [] for _, paths in names_with_path: all_paths.extend(paths) contains_louter = False # Trim and operate only on tables that were generated for # the lookup part of the query. That is, avoid trimming # joins generated for F() expressions. lookup_tables = [ t for t in self.alias_map if t in self._lookup_joins or t == self.base_table ] for trimmed_paths, path in enumerate(all_paths): if path.m2m: break if self.alias_map[lookup_tables[trimmed_paths + 1]].join_type == LOUTER: contains_louter = True alias = lookup_tables[trimmed_paths] self.unref_alias(alias) # The path.join_field is a Rel, lets get the other side's field join_field = path.join_field.field # Build the filter prefix. paths_in_prefix = trimmed_paths trimmed_prefix = [] for name, path in names_with_path: if paths_in_prefix - len(path) < 0: break trimmed_prefix.append(name) paths_in_prefix -= len(path) trimmed_prefix.append(join_field.foreign_related_fields[0].name) trimmed_prefix = LOOKUP_SEP.join(trimmed_prefix) # Lets still see if we can trim the first join from the inner query # (that is, self). We can't do this for: # - LEFT JOINs because we would miss those rows that have nothing on # the outer side, # - INNER JOINs from filtered relations because we would miss their # filters. first_join = self.alias_map[lookup_tables[trimmed_paths + 1]] if first_join.join_type != LOUTER and not first_join.filtered_relation: select_fields = [r[0] for r in join_field.related_fields] select_alias = lookup_tables[trimmed_paths + 1] self.unref_alias(lookup_tables[trimmed_paths]) extra_restriction = join_field.get_extra_restriction( None, lookup_tables[trimmed_paths + 1] ) if extra_restriction: self.where.add(extra_restriction, AND) else: # TODO: It might be possible to trim more joins from the start of the # inner query if it happens to have a longer join chain containing the # values in select_fields. Lets punt this one for now. select_fields = [r[1] for r in join_field.related_fields] select_alias = lookup_tables[trimmed_paths] # The found starting point is likely a join_class instead of a # base_table_class reference. But the first entry in the query's FROM # clause must not be a JOIN. for table in self.alias_map: if self.alias_refcount[table] > 0: self.alias_map[table] = self.base_table_class( self.alias_map[table].table_name, table, ) break self.set_select([f.get_col(select_alias) for f in select_fields]) return trimmed_prefix, contains_louter def is_nullable(self, field): """ Check if the given field should be treated as nullable. Some backends treat '' as null and Django treats such fields as nullable for those backends. In such situations field.null can be False even if we should treat the field as nullable. """ # We need to use DEFAULT_DB_ALIAS here, as QuerySet does not have # (nor should it have) knowledge of which connection is going to be # used. The proper fix would be to defer all decisions where # is_nullable() is needed to the compiler stage, but that is not easy # to do currently. return field.null or ( field.empty_strings_allowed and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls ) def get_order_dir(field, default="ASC"): """ Return the field name and direction for an order specification. For example, '-foo' is returned as ('foo', 'DESC'). The 'default' param is used to indicate which way no prefix (or a '+' prefix) should sort. The '-' prefix always sorts the opposite way. """ dirn = ORDER_DIR[default] if field[0] == "-": return field[1:], dirn[1] return field, dirn[0] class JoinPromoter: """ A class to abstract away join promotion problems for complex filter conditions. """ def __init__(self, connector, num_children, negated): self.connector = connector self.negated = negated if self.negated: if connector == AND: self.effective_connector = OR else: self.effective_connector = AND else: self.effective_connector = self.connector self.num_children = num_children # Maps of table alias to how many times it is seen as required for # inner and/or outer joins. self.votes = Counter() def __repr__(self): return ( f"{self.__class__.__qualname__}(connector={self.connector!r}, " f"num_children={self.num_children!r}, negated={self.negated!r})" ) def add_votes(self, votes): """ Add single vote per item to self.votes. Parameter can be any iterable. """ self.votes.update(votes) def update_join_types(self, query): """ Change join types so that the generated query is as efficient as possible, but still correct. So, change as many joins as possible to INNER, but don't make OUTER joins INNER if that could remove results from the query. """ to_promote = set() to_demote = set() # The effective_connector is used so that NOT (a AND b) is treated # similarly to (a OR b) for join promotion. for table, votes in self.votes.items(): # We must use outer joins in OR case when the join isn't contained # in all of the joins. Otherwise the INNER JOIN itself could remove # valid results. Consider the case where a model with rel_a and # rel_b relations is queried with rel_a__col=1 | rel_b__col=2. Now, # if rel_a join doesn't produce any results is null (for example # reverse foreign key or null value in direct foreign key), and # there is a matching row in rel_b with col=2, then an INNER join # to rel_a would remove a valid match from the query. So, we need # to promote any existing INNER to LOUTER (it is possible this # promotion in turn will be demoted later on). if self.effective_connector == OR and votes < self.num_children: to_promote.add(table) # If connector is AND and there is a filter that can match only # when there is a joinable row, then use INNER. For example, in # rel_a__col=1 & rel_b__col=2, if either of the rels produce NULL # as join output, then the col=1 or col=2 can't match (as # NULL=anything is always false). # For the OR case, if all children voted for a join to be inner, # then we can use INNER for the join. For example: # (rel_a__col__icontains=Alex | rel_a__col__icontains=Russell) # then if rel_a doesn't produce any rows, the whole condition # can't match. Hence we can safely use INNER join. if self.effective_connector == AND or ( self.effective_connector == OR and votes == self.num_children ): to_demote.add(table) # Finally, what happens in cases where we have: # (rel_a__col=1|rel_b__col=2) & rel_a__col__gte=0 # Now, we first generate the OR clause, and promote joins for it # in the first if branch above. Both rel_a and rel_b are promoted # to LOUTER joins. After that we do the AND case. The OR case # voted no inner joins but the rel_a__col__gte=0 votes inner join # for rel_a. We demote it back to INNER join (in AND case a single # vote is enough). The demotion is OK, if rel_a doesn't produce # rows, then the rel_a__col__gte=0 clause can't be true, and thus # the whole clause must be false. So, it is safe to use INNER # join. # Note that in this example we could just as well have the __gte # clause and the OR clause swapped. Or we could replace the __gte # clause with an OR clause containing rel_a__col=1|rel_a__col=2, # and again we could safely demote to INNER. query.promote_joins(to_promote) query.demote_joins(to_demote) return to_demote
86cfd23e86a555ce218aff7fc2c27fcac3f6333a6f16835a41802a1a0daeb479
import collections import json import re from functools import partial from itertools import chain from django.core.exceptions import EmptyResultSet, FieldError, FullResultSet from django.db import DatabaseError, NotSupportedError from django.db.models.constants import LOOKUP_SEP from django.db.models.expressions import F, OrderBy, RawSQL, Ref, Value from django.db.models.functions import Cast, Random from django.db.models.lookups import Lookup from django.db.models.query_utils import select_related_descend from django.db.models.sql.constants import ( CURSOR, GET_ITERATOR_CHUNK_SIZE, MULTI, NO_RESULTS, ORDER_DIR, SINGLE, ) from django.db.models.sql.query import Query, get_order_dir from django.db.models.sql.where import AND from django.db.transaction import TransactionManagementError from django.utils.functional import cached_property from django.utils.hashable import make_hashable from django.utils.regex_helper import _lazy_re_compile class PositionRef(Ref): def __init__(self, ordinal, refs, source): self.ordinal = ordinal super().__init__(refs, source) def as_sql(self, compiler, connection): return str(self.ordinal), () class SQLCompiler: # Multiline ordering SQL clause may appear from RawSQL. ordering_parts = _lazy_re_compile( r"^(.*)\s(?:ASC|DESC).*", re.MULTILINE | re.DOTALL, ) def __init__(self, query, connection, using, elide_empty=True): self.query = query self.connection = connection self.using = using # Some queries, e.g. coalesced aggregation, need to be executed even if # they would return an empty result set. self.elide_empty = elide_empty self.quote_cache = {"*": "*"} # The select, klass_info, and annotations are needed by QuerySet.iterator() # these are set as a side-effect of executing the query. Note that we calculate # separately a list of extra select columns needed for grammatical correctness # of the query, but these columns are not included in self.select. self.select = None self.annotation_col_map = None self.klass_info = None self._meta_ordering = None def __repr__(self): return ( f"<{self.__class__.__qualname__} " f"model={self.query.model.__qualname__} " f"connection={self.connection!r} using={self.using!r}>" ) def setup_query(self, with_col_aliases=False): if all(self.query.alias_refcount[a] == 0 for a in self.query.alias_map): self.query.get_initial_alias() self.select, self.klass_info, self.annotation_col_map = self.get_select( with_col_aliases=with_col_aliases, ) self.col_count = len(self.select) def pre_sql_setup(self, with_col_aliases=False): """ Do any necessary class setup immediately prior to producing SQL. This is for things that can't necessarily be done in __init__ because we might not have all the pieces in place at that time. """ self.setup_query(with_col_aliases=with_col_aliases) order_by = self.get_order_by() self.where, self.having, self.qualify = self.query.where.split_having_qualify( must_group_by=self.query.group_by is not None ) extra_select = self.get_extra_select(order_by, self.select) self.has_extra_select = bool(extra_select) group_by = self.get_group_by(self.select + extra_select, order_by) return extra_select, order_by, group_by def get_group_by(self, select, order_by): """ Return a list of 2-tuples of form (sql, params). The logic of what exactly the GROUP BY clause contains is hard to describe in other words than "if it passes the test suite, then it is correct". """ # Some examples: # SomeModel.objects.annotate(Count('somecol')) # GROUP BY: all fields of the model # # SomeModel.objects.values('name').annotate(Count('somecol')) # GROUP BY: name # # SomeModel.objects.annotate(Count('somecol')).values('name') # GROUP BY: all cols of the model # # SomeModel.objects.values('name', 'pk') # .annotate(Count('somecol')).values('pk') # GROUP BY: name, pk # # SomeModel.objects.values('name').annotate(Count('somecol')).values('pk') # GROUP BY: name, pk # # In fact, the self.query.group_by is the minimal set to GROUP BY. It # can't be ever restricted to a smaller set, but additional columns in # HAVING, ORDER BY, and SELECT clauses are added to it. Unfortunately # the end result is that it is impossible to force the query to have # a chosen GROUP BY clause - you can almost do this by using the form: # .values(*wanted_cols).annotate(AnAggregate()) # but any later annotations, extra selects, values calls that # refer some column outside of the wanted_cols, order_by, or even # filter calls can alter the GROUP BY clause. # The query.group_by is either None (no GROUP BY at all), True # (group by select fields), or a list of expressions to be added # to the group by. if self.query.group_by is None: return [] expressions = [] group_by_refs = set() if self.query.group_by is not True: # If the group by is set to a list (by .values() call most likely), # then we need to add everything in it to the GROUP BY clause. # Backwards compatibility hack for setting query.group_by. Remove # when we have public API way of forcing the GROUP BY clause. # Converts string references to expressions. for expr in self.query.group_by: if not hasattr(expr, "as_sql"): expr = self.query.resolve_ref(expr) if isinstance(expr, Ref): if expr.refs not in group_by_refs: group_by_refs.add(expr.refs) expressions.append(expr.source) else: expressions.append(expr) # Note that even if the group_by is set, it is only the minimal # set to group by. So, we need to add cols in select, order_by, and # having into the select in any case. selected_expr_positions = {} for ordinal, (expr, _, alias) in enumerate(select, start=1): if alias: selected_expr_positions[expr] = ordinal # Skip members of the select clause that are already explicitly # grouped against. if alias in group_by_refs: continue expressions.extend(expr.get_group_by_cols()) if not self._meta_ordering: for expr, (sql, params, is_ref) in order_by: # Skip references to the SELECT clause, as all expressions in # the SELECT clause are already part of the GROUP BY. if not is_ref: expressions.extend(expr.get_group_by_cols()) having_group_by = self.having.get_group_by_cols() if self.having else () for expr in having_group_by: expressions.append(expr) result = [] seen = set() expressions = self.collapse_group_by(expressions, having_group_by) allows_group_by_select_index = ( self.connection.features.allows_group_by_select_index ) for expr in expressions: try: sql, params = self.compile(expr) except (EmptyResultSet, FullResultSet): continue if ( allows_group_by_select_index and (position := selected_expr_positions.get(expr)) is not None ): sql, params = str(position), () else: sql, params = expr.select_format(self, sql, params) params_hash = make_hashable(params) if (sql, params_hash) not in seen: result.append((sql, params)) seen.add((sql, params_hash)) return result def collapse_group_by(self, expressions, having): # If the database supports group by functional dependence reduction, # then the expressions can be reduced to the set of selected table # primary keys as all other columns are functionally dependent on them. if self.connection.features.allows_group_by_selected_pks: # Filter out all expressions associated with a table's primary key # present in the grouped columns. This is done by identifying all # tables that have their primary key included in the grouped # columns and removing non-primary key columns referring to them. # Unmanaged models are excluded because they could be representing # database views on which the optimization might not be allowed. pks = { expr for expr in expressions if ( hasattr(expr, "target") and expr.target.primary_key and self.connection.features.allows_group_by_selected_pks_on_model( expr.target.model ) ) } aliases = {expr.alias for expr in pks} expressions = [ expr for expr in expressions if expr in pks or expr in having or getattr(expr, "alias", None) not in aliases ] return expressions def get_select(self, with_col_aliases=False): """ Return three values: - a list of 3-tuples of (expression, (sql, params), alias) - a klass_info structure, - a dictionary of annotations The (sql, params) is what the expression will produce, and alias is the "AS alias" for the column (possibly None). The klass_info structure contains the following information: - The base model of the query. - Which columns for that model are present in the query (by position of the select clause). - related_klass_infos: [f, klass_info] to descent into The annotations is a dictionary of {'attname': column position} values. """ select = [] klass_info = None annotations = {} select_idx = 0 for alias, (sql, params) in self.query.extra_select.items(): annotations[alias] = select_idx select.append((RawSQL(sql, params), alias)) select_idx += 1 assert not (self.query.select and self.query.default_cols) select_mask = self.query.get_select_mask() if self.query.default_cols: cols = self.get_default_columns(select_mask) else: # self.query.select is a special case. These columns never go to # any model. cols = self.query.select if cols: select_list = [] for col in cols: select_list.append(select_idx) select.append((col, None)) select_idx += 1 klass_info = { "model": self.query.model, "select_fields": select_list, } for alias, annotation in self.query.annotation_select.items(): annotations[alias] = select_idx select.append((annotation, alias)) select_idx += 1 if self.query.select_related: related_klass_infos = self.get_related_selections(select, select_mask) klass_info["related_klass_infos"] = related_klass_infos def get_select_from_parent(klass_info): for ki in klass_info["related_klass_infos"]: if ki["from_parent"]: ki["select_fields"] = ( klass_info["select_fields"] + ki["select_fields"] ) get_select_from_parent(ki) get_select_from_parent(klass_info) ret = [] col_idx = 1 for col, alias in select: try: sql, params = self.compile(col) except EmptyResultSet: empty_result_set_value = getattr( col, "empty_result_set_value", NotImplemented ) if empty_result_set_value is NotImplemented: # Select a predicate that's always False. sql, params = "0", () else: sql, params = self.compile(Value(empty_result_set_value)) except FullResultSet: sql, params = self.compile(Value(True)) else: sql, params = col.select_format(self, sql, params) if alias is None and with_col_aliases: alias = f"col{col_idx}" col_idx += 1 ret.append((col, (sql, params), alias)) return ret, klass_info, annotations def _order_by_pairs(self): if self.query.extra_order_by: ordering = self.query.extra_order_by elif not self.query.default_ordering: ordering = self.query.order_by elif self.query.order_by: ordering = self.query.order_by elif (meta := self.query.get_meta()) and meta.ordering: ordering = meta.ordering self._meta_ordering = ordering else: ordering = [] if self.query.standard_ordering: default_order, _ = ORDER_DIR["ASC"] else: default_order, _ = ORDER_DIR["DESC"] selected_exprs = {} if select := self.select: for ordinal, (expr, _, alias) in enumerate(select, start=1): pos_expr = PositionRef(ordinal, alias, expr) if alias: selected_exprs[alias] = pos_expr selected_exprs[expr] = pos_expr for field in ordering: if hasattr(field, "resolve_expression"): if isinstance(field, Value): # output_field must be resolved for constants. field = Cast(field, field.output_field) if not isinstance(field, OrderBy): field = field.asc() if not self.query.standard_ordering: field = field.copy() field.reverse_ordering() select_ref = selected_exprs.get(field.expression) if select_ref or ( isinstance(field.expression, F) and (select_ref := selected_exprs.get(field.expression.name)) ): # Emulation of NULLS (FIRST|LAST) cannot be combined with # the usage of ordering by position. if ( field.nulls_first is None and field.nulls_last is None ) or self.connection.features.supports_order_by_nulls_modifier: field = field.copy() field.expression = select_ref # Alias collisions are not possible when dealing with # combined queries so fallback to it if emulation of NULLS # handling is required. elif self.query.combinator: field = field.copy() field.expression = Ref(select_ref.refs, select_ref.source) yield field, select_ref is not None continue if field == "?": # random yield OrderBy(Random()), False continue col, order = get_order_dir(field, default_order) descending = order == "DESC" if select_ref := selected_exprs.get(col): # Reference to expression in SELECT clause yield ( OrderBy( select_ref, descending=descending, ), True, ) continue if col in self.query.annotations: # References to an expression which is masked out of the SELECT # clause. if self.query.combinator and self.select: # Don't use the resolved annotation because other # combinated queries might define it differently. expr = F(col) else: expr = self.query.annotations[col] if isinstance(expr, Value): # output_field must be resolved for constants. expr = Cast(expr, expr.output_field) yield OrderBy(expr, descending=descending), False continue if "." in field: # This came in through an extra(order_by=...) addition. Pass it # on verbatim. table, col = col.split(".", 1) yield ( OrderBy( RawSQL( "%s.%s" % (self.quote_name_unless_alias(table), col), [] ), descending=descending, ), False, ) continue if self.query.extra and col in self.query.extra: if col in self.query.extra_select: yield ( OrderBy( Ref(col, RawSQL(*self.query.extra[col])), descending=descending, ), True, ) else: yield ( OrderBy(RawSQL(*self.query.extra[col]), descending=descending), False, ) else: if self.query.combinator and self.select: # Don't use the first model's field because other # combinated queries might define it differently. yield OrderBy(F(col), descending=descending), False else: # 'col' is of the form 'field' or 'field1__field2' or # '-field1__field2__field', etc. yield from self.find_ordering_name( field, self.query.get_meta(), default_order=default_order, ) def get_order_by(self): """ Return a list of 2-tuples of the form (expr, (sql, params, is_ref)) for the ORDER BY clause. The order_by clause can alter the select clause (for example it can add aliases to clauses that do not yet have one, or it can add totally new select clauses). """ result = [] seen = set() for expr, is_ref in self._order_by_pairs(): resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None) if not is_ref and self.query.combinator and self.select: src = resolved.expression expr_src = expr.expression for sel_expr, _, col_alias in self.select: if src == sel_expr: # When values() is used the exact alias must be used to # reference annotations. if ( self.query.has_select_fields and col_alias in self.query.annotation_select and not ( isinstance(expr_src, F) and col_alias == expr_src.name ) ): continue resolved.set_source_expressions( [Ref(col_alias if col_alias else src.target.column, src)] ) break else: # Add column used in ORDER BY clause to the selected # columns and to each combined query. order_by_idx = len(self.query.select) + 1 col_alias = f"__orderbycol{order_by_idx}" for q in self.query.combined_queries: # If fields were explicitly selected through values() # combined queries cannot be augmented. if q.has_select_fields: raise DatabaseError( "ORDER BY term does not match any column in " "the result set." ) q.add_annotation(expr_src, col_alias) self.query.add_select_col(resolved, col_alias) resolved.set_source_expressions([Ref(col_alias, src)]) sql, params = self.compile(resolved) # Don't add the same column twice, but the order direction is # not taken into account so we strip it. When this entire method # is refactored into expressions, then we can check each part as we # generate it. without_ordering = self.ordering_parts.search(sql)[1] params_hash = make_hashable(params) if (without_ordering, params_hash) in seen: continue seen.add((without_ordering, params_hash)) result.append((resolved, (sql, params, is_ref))) return result def get_extra_select(self, order_by, select): extra_select = [] if self.query.distinct and not self.query.distinct_fields: select_sql = [t[1] for t in select] for expr, (sql, params, is_ref) in order_by: without_ordering = self.ordering_parts.search(sql)[1] if not is_ref and (without_ordering, params) not in select_sql: extra_select.append((expr, (without_ordering, params), None)) return extra_select def quote_name_unless_alias(self, name): """ A wrapper around connection.ops.quote_name that doesn't quote aliases for table names. This avoids problems with some SQL dialects that treat quoted strings specially (e.g. PostgreSQL). """ if name in self.quote_cache: return self.quote_cache[name] if ( (name in self.query.alias_map and name not in self.query.table_map) or name in self.query.extra_select or ( self.query.external_aliases.get(name) and name not in self.query.table_map ) ): self.quote_cache[name] = name return name r = self.connection.ops.quote_name(name) self.quote_cache[name] = r return r def compile(self, node): vendor_impl = getattr(node, "as_" + self.connection.vendor, None) if vendor_impl: sql, params = vendor_impl(self, self.connection) else: sql, params = node.as_sql(self, self.connection) return sql, params def get_combinator_sql(self, combinator, all): features = self.connection.features compilers = [ query.get_compiler(self.using, self.connection, self.elide_empty) for query in self.query.combined_queries ] if not features.supports_slicing_ordering_in_compound: for compiler in compilers: if compiler.query.is_sliced: raise DatabaseError( "LIMIT/OFFSET not allowed in subqueries of compound statements." ) if compiler.get_order_by(): raise DatabaseError( "ORDER BY not allowed in subqueries of compound statements." ) elif self.query.is_sliced and combinator == "union": for compiler in compilers: # A sliced union cannot have its parts elided as some of them # might be sliced as well and in the event where only a single # part produces a non-empty resultset it might be impossible to # generate valid SQL. compiler.elide_empty = False parts = () for compiler in compilers: try: # If the columns list is limited, then all combined queries # must have the same columns list. Set the selects defined on # the query on all combined queries, if not already set. if not compiler.query.values_select and self.query.values_select: compiler.query = compiler.query.clone() compiler.query.set_values( ( *self.query.extra_select, *self.query.values_select, *self.query.annotation_select, ) ) part_sql, part_args = compiler.as_sql(with_col_aliases=True) if compiler.query.combinator: # Wrap in a subquery if wrapping in parentheses isn't # supported. if not features.supports_parentheses_in_compound: part_sql = "SELECT * FROM ({})".format(part_sql) # Add parentheses when combining with compound query if not # already added for all compound queries. elif ( self.query.subquery or not features.supports_slicing_ordering_in_compound ): part_sql = "({})".format(part_sql) elif ( self.query.subquery and features.supports_slicing_ordering_in_compound ): part_sql = "({})".format(part_sql) parts += ((part_sql, part_args),) except EmptyResultSet: # Omit the empty queryset with UNION and with DIFFERENCE if the # first queryset is nonempty. if combinator == "union" or (combinator == "difference" and parts): continue raise if not parts: raise EmptyResultSet combinator_sql = self.connection.ops.set_operators[combinator] if all and combinator == "union": combinator_sql += " ALL" braces = "{}" if not self.query.subquery and features.supports_slicing_ordering_in_compound: braces = "({})" sql_parts, args_parts = zip( *((braces.format(sql), args) for sql, args in parts) ) result = [" {} ".format(combinator_sql).join(sql_parts)] params = [] for part in args_parts: params.extend(part) return result, params def get_qualify_sql(self): where_parts = [] if self.where: where_parts.append(self.where) if self.having: where_parts.append(self.having) inner_query = self.query.clone() inner_query.subquery = True inner_query.where = inner_query.where.__class__(where_parts) # Augment the inner query with any window function references that # might have been masked via values() and alias(). If any masked # aliases are added they'll be masked again to avoid fetching # the data in the `if qual_aliases` branch below. select = { expr: alias for expr, _, alias in self.get_select(with_col_aliases=True)[0] } select_aliases = set(select.values()) qual_aliases = set() replacements = {} def collect_replacements(expressions): while expressions: expr = expressions.pop() if expr in replacements: continue elif select_alias := select.get(expr): replacements[expr] = select_alias elif isinstance(expr, Lookup): expressions.extend(expr.get_source_expressions()) elif isinstance(expr, Ref): if expr.refs not in select_aliases: expressions.extend(expr.get_source_expressions()) else: num_qual_alias = len(qual_aliases) select_alias = f"qual{num_qual_alias}" qual_aliases.add(select_alias) inner_query.add_annotation(expr, select_alias) replacements[expr] = select_alias collect_replacements(list(self.qualify.leaves())) self.qualify = self.qualify.replace_expressions( {expr: Ref(alias, expr) for expr, alias in replacements.items()} ) order_by = [] for order_by_expr, *_ in self.get_order_by(): collect_replacements(order_by_expr.get_source_expressions()) order_by.append( order_by_expr.replace_expressions( {expr: Ref(alias, expr) for expr, alias in replacements.items()} ) ) inner_query_compiler = inner_query.get_compiler( self.using, connection=self.connection, elide_empty=self.elide_empty ) inner_sql, inner_params = inner_query_compiler.as_sql( # The limits must be applied to the outer query to avoid pruning # results too eagerly. with_limits=False, # Force unique aliasing of selected columns to avoid collisions # and make rhs predicates referencing easier. with_col_aliases=True, ) qualify_sql, qualify_params = self.compile(self.qualify) result = [ "SELECT * FROM (", inner_sql, ")", self.connection.ops.quote_name("qualify"), "WHERE", qualify_sql, ] if qual_aliases: # If some select aliases were unmasked for filtering purposes they # must be masked back. cols = [self.connection.ops.quote_name(alias) for alias in select.values()] result = [ "SELECT", ", ".join(cols), "FROM (", *result, ")", self.connection.ops.quote_name("qualify_mask"), ] params = list(inner_params) + qualify_params # As the SQL spec is unclear on whether or not derived tables # ordering must propagate it has to be explicitly repeated on the # outer-most query to ensure it's preserved. if order_by: ordering_sqls = [] for ordering in order_by: ordering_sql, ordering_params = self.compile(ordering) ordering_sqls.append(ordering_sql) params.extend(ordering_params) result.extend(["ORDER BY", ", ".join(ordering_sqls)]) return result, params def as_sql(self, with_limits=True, with_col_aliases=False): """ Create the SQL for this query. Return the SQL string and list of parameters. If 'with_limits' is False, any limit/offset information is not included in the query. """ refcounts_before = self.query.alias_refcount.copy() try: combinator = self.query.combinator extra_select, order_by, group_by = self.pre_sql_setup( with_col_aliases=with_col_aliases or bool(combinator), ) for_update_part = None # Is a LIMIT/OFFSET clause needed? with_limit_offset = with_limits and self.query.is_sliced combinator = self.query.combinator features = self.connection.features if combinator: if not getattr(features, "supports_select_{}".format(combinator)): raise NotSupportedError( "{} is not supported on this database backend.".format( combinator ) ) result, params = self.get_combinator_sql( combinator, self.query.combinator_all ) elif self.qualify: result, params = self.get_qualify_sql() order_by = None else: distinct_fields, distinct_params = self.get_distinct() # This must come after 'select', 'ordering', and 'distinct' # (see docstring of get_from_clause() for details). from_, f_params = self.get_from_clause() try: where, w_params = ( self.compile(self.where) if self.where is not None else ("", []) ) except EmptyResultSet: if self.elide_empty: raise # Use a predicate that's always False. where, w_params = "0 = 1", [] except FullResultSet: where, w_params = "", [] try: having, h_params = ( self.compile(self.having) if self.having is not None else ("", []) ) except FullResultSet: having, h_params = "", [] result = ["SELECT"] params = [] if self.query.distinct: distinct_result, distinct_params = self.connection.ops.distinct_sql( distinct_fields, distinct_params, ) result += distinct_result params += distinct_params out_cols = [] for _, (s_sql, s_params), alias in self.select + extra_select: if alias: s_sql = "%s AS %s" % ( s_sql, self.connection.ops.quote_name(alias), ) params.extend(s_params) out_cols.append(s_sql) result += [", ".join(out_cols)] if from_: result += ["FROM", *from_] elif self.connection.features.bare_select_suffix: result += [self.connection.features.bare_select_suffix] params.extend(f_params) if self.query.select_for_update and features.has_select_for_update: if ( self.connection.get_autocommit() # Don't raise an exception when database doesn't # support transactions, as it's a noop. and features.supports_transactions ): raise TransactionManagementError( "select_for_update cannot be used outside of a transaction." ) if ( with_limit_offset and not features.supports_select_for_update_with_limit ): raise NotSupportedError( "LIMIT/OFFSET is not supported with " "select_for_update on this database backend." ) nowait = self.query.select_for_update_nowait skip_locked = self.query.select_for_update_skip_locked of = self.query.select_for_update_of no_key = self.query.select_for_no_key_update # If it's a NOWAIT/SKIP LOCKED/OF/NO KEY query but the # backend doesn't support it, raise NotSupportedError to # prevent a possible deadlock. if nowait and not features.has_select_for_update_nowait: raise NotSupportedError( "NOWAIT is not supported on this database backend." ) elif skip_locked and not features.has_select_for_update_skip_locked: raise NotSupportedError( "SKIP LOCKED is not supported on this database backend." ) elif of and not features.has_select_for_update_of: raise NotSupportedError( "FOR UPDATE OF is not supported on this database backend." ) elif no_key and not features.has_select_for_no_key_update: raise NotSupportedError( "FOR NO KEY UPDATE is not supported on this " "database backend." ) for_update_part = self.connection.ops.for_update_sql( nowait=nowait, skip_locked=skip_locked, of=self.get_select_for_update_of_arguments(), no_key=no_key, ) if for_update_part and features.for_update_after_from: result.append(for_update_part) if where: result.append("WHERE %s" % where) params.extend(w_params) grouping = [] for g_sql, g_params in group_by: grouping.append(g_sql) params.extend(g_params) if grouping: if distinct_fields: raise NotImplementedError( "annotate() + distinct(fields) is not implemented." ) order_by = order_by or self.connection.ops.force_no_ordering() result.append("GROUP BY %s" % ", ".join(grouping)) if self._meta_ordering: order_by = None if having: result.append("HAVING %s" % having) params.extend(h_params) if self.query.explain_info: result.insert( 0, self.connection.ops.explain_query_prefix( self.query.explain_info.format, **self.query.explain_info.options, ), ) if order_by: ordering = [] for _, (o_sql, o_params, _) in order_by: ordering.append(o_sql) params.extend(o_params) order_by_sql = "ORDER BY %s" % ", ".join(ordering) if combinator and features.requires_compound_order_by_subquery: result = ["SELECT * FROM (", *result, ")", order_by_sql] else: result.append(order_by_sql) if with_limit_offset: result.append( self.connection.ops.limit_offset_sql( self.query.low_mark, self.query.high_mark ) ) if for_update_part and not features.for_update_after_from: result.append(for_update_part) if self.query.subquery and extra_select: # If the query is used as a subquery, the extra selects would # result in more columns than the left-hand side expression is # expecting. This can happen when a subquery uses a combination # of order_by() and distinct(), forcing the ordering expressions # to be selected as well. Wrap the query in another subquery # to exclude extraneous selects. sub_selects = [] sub_params = [] for index, (select, _, alias) in enumerate(self.select, start=1): if alias: sub_selects.append( "%s.%s" % ( self.connection.ops.quote_name("subquery"), self.connection.ops.quote_name(alias), ) ) else: select_clone = select.relabeled_clone( {select.alias: "subquery"} ) subselect, subparams = select_clone.as_sql( self, self.connection ) sub_selects.append(subselect) sub_params.extend(subparams) return "SELECT %s FROM (%s) subquery" % ( ", ".join(sub_selects), " ".join(result), ), tuple(sub_params + params) return " ".join(result), tuple(params) finally: # Finally do cleanup - get rid of the joins we created above. self.query.reset_refcounts(refcounts_before) def get_default_columns( self, select_mask, start_alias=None, opts=None, from_parent=None ): """ Compute the default columns for selecting every field in the base model. Will sometimes be called to pull in related models (e.g. via select_related), in which case "opts" and "start_alias" will be given to provide a starting point for the traversal. Return a list of strings, quoted appropriately for use in SQL directly, as well as a set of aliases used in the select statement (if 'as_pairs' is True, return a list of (alias, col_name) pairs instead of strings as the first component and None as the second component). """ result = [] if opts is None: if (opts := self.query.get_meta()) is None: return result start_alias = start_alias or self.query.get_initial_alias() # The 'seen_models' is used to optimize checking the needed parent # alias for a given field. This also includes None -> start_alias to # be used by local fields. seen_models = {None: start_alias} for field in opts.concrete_fields: model = field.model._meta.concrete_model # A proxy model will have a different model and concrete_model. We # will assign None if the field belongs to this model. if model == opts.model: model = None if ( from_parent and model is not None and issubclass( from_parent._meta.concrete_model, model._meta.concrete_model ) ): # Avoid loading data for already loaded parents. # We end up here in the case select_related() resolution # proceeds from parent model to child model. In that case the # parent model data is already present in the SELECT clause, # and we want to avoid reloading the same data again. continue if select_mask and field not in select_mask: continue alias = self.query.join_parent_model(opts, model, start_alias, seen_models) column = field.get_col(alias) result.append(column) return result def get_distinct(self): """ Return a quoted list of fields to use in DISTINCT ON part of the query. This method can alter the tables in the query, and thus it must be called before get_from_clause(). """ result = [] params = [] opts = self.query.get_meta() for name in self.query.distinct_fields: parts = name.split(LOOKUP_SEP) _, targets, alias, joins, path, _, transform_function = self._setup_joins( parts, opts, None ) targets, alias, _ = self.query.trim_joins(targets, joins, path) for target in targets: if name in self.query.annotation_select: result.append(self.connection.ops.quote_name(name)) else: r, p = self.compile(transform_function(target, alias)) result.append(r) params.append(p) return result, params def find_ordering_name( self, name, opts, alias=None, default_order="ASC", already_seen=None ): """ Return the table alias (the name might be ambiguous, the alias will not be) and column name for ordering by the given 'name' parameter. The 'name' is of the form 'field1__field2__...__fieldN'. """ name, order = get_order_dir(name, default_order) descending = order == "DESC" pieces = name.split(LOOKUP_SEP) ( 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 it is the pk # shortcut or the attribute name of the field that is specified or # there are transforms to process. if ( field.is_relation and opts.ordering and getattr(field, "attname", None) != pieces[-1] and name != "pk" and not getattr(transform_function, "has_transforms", False) ): # 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 ) if join_tuple in already_seen: raise FieldError("Infinite loop caused by ordering.") already_seen.add(join_tuple) results = [] for item in opts.ordering: if hasattr(item, "resolve_expression") and not isinstance( item, OrderBy ): item = item.desc() if descending else item.asc() if isinstance(item, OrderBy): results.append( (item.prefix_references(f"{name}{LOOKUP_SEP}"), False) ) continue results.extend( (expr.prefix_references(f"{name}{LOOKUP_SEP}"), is_ref) for expr, is_ref in self.find_ordering_name( item, opts, alias, order, already_seen ) ) return results targets, alias, _ = self.query.trim_joins(targets, joins, path) return [ (OrderBy(transform_function(t, alias), descending=descending), False) for t in targets ] def _setup_joins(self, pieces, opts, alias): """ Helper method for get_order_by() and get_distinct(). get_ordering() and get_distinct() must produce same target columns on same input, as the prefixes of get_ordering() and get_distinct() must match. Executing SQL where this is not true is an error. """ alias = alias or self.query.get_initial_alias() field, targets, opts, joins, path, transform_function = self.query.setup_joins( pieces, opts, alias ) alias = joins[-1] return field, targets, alias, joins, path, opts, transform_function def get_from_clause(self): """ Return a list of strings that are joined together to go after the "FROM" part of the query, as well as a list any extra parameters that need to be included. Subclasses, can override this to create a from-clause via a "select". This should only be called after any SQL construction methods that might change the tables that are needed. This means the select columns, ordering, and distinct must be done first. """ result = [] params = [] for alias in tuple(self.query.alias_map): if not self.query.alias_refcount[alias]: continue try: from_clause = self.query.alias_map[alias] except KeyError: # Extra tables can end up in self.tables, but not in the # alias_map if they aren't in a join. That's OK. We skip them. continue clause_sql, clause_params = self.compile(from_clause) result.append(clause_sql) params.extend(clause_params) for t in self.query.extra_tables: alias, _ = self.query.table_alias(t) # Only add the alias if it's not already present (the table_alias() # call increments the refcount, so an alias refcount of one means # this is the only reference). if ( alias not in self.query.alias_map or self.query.alias_refcount[alias] == 1 ): result.append(", %s" % self.quote_name_unless_alias(alias)) return result, params def get_related_selections( self, select, select_mask, opts=None, root_alias=None, cur_depth=1, requested=None, restricted=None, ): """ Fill in the information needed for a select_related query. The current depth is measured as the number of connections away from the root model (for example, cur_depth=1 means we are looking at models with direct connections to the root model). """ def _get_field_choices(): direct_choices = (f.name for f in opts.fields if f.is_relation) reverse_choices = ( f.field.related_query_name() for f in opts.related_objects if f.field.unique ) return chain( direct_choices, reverse_choices, self.query._filtered_relations ) related_klass_infos = [] if not restricted and cur_depth > self.query.max_depth: # We've recursed far enough; bail out. return related_klass_infos if not opts: opts = self.query.get_meta() root_alias = self.query.get_initial_alias() # Setup for the case when only particular related fields should be # included in the related selection. fields_found = set() if requested is None: restricted = isinstance(self.query.select_related, dict) if restricted: requested = self.query.select_related def get_related_klass_infos(klass_info, related_klass_infos): klass_info["related_klass_infos"] = related_klass_infos for f in opts.fields: fields_found.add(f.name) if restricted: next = requested.get(f.name, {}) if not f.is_relation: # If a non-related field is used like a relation, # or if a single non-relational field is given. if next or f.name in requested: raise FieldError( "Non-relational field given in select_related: '%s'. " "Choices are: %s" % ( f.name, ", ".join(_get_field_choices()) or "(none)", ) ) else: next = False if not select_related_descend(f, restricted, requested, select_mask): continue related_select_mask = select_mask.get(f) or {} klass_info = { "model": f.remote_field.model, "field": f, "reverse": False, "local_setter": f.set_cached_value, "remote_setter": f.remote_field.set_cached_value if f.unique else lambda x, y: None, "from_parent": False, } related_klass_infos.append(klass_info) select_fields = [] _, _, _, joins, _, _ = self.query.setup_joins([f.name], opts, root_alias) alias = joins[-1] columns = self.get_default_columns( related_select_mask, start_alias=alias, opts=f.remote_field.model._meta ) for col in columns: select_fields.append(len(select)) select.append((col, None)) klass_info["select_fields"] = select_fields next_klass_infos = self.get_related_selections( select, related_select_mask, f.remote_field.model._meta, alias, cur_depth + 1, next, restricted, ) get_related_klass_infos(klass_info, next_klass_infos) if restricted: related_fields = [ (o.field, o.related_model) for o in opts.related_objects if o.field.unique and not o.many_to_many ] for related_field, model in related_fields: related_select_mask = select_mask.get(related_field) or {} if not select_related_descend( related_field, restricted, requested, related_select_mask, reverse=True, ): continue related_field_name = related_field.related_query_name() fields_found.add(related_field_name) join_info = self.query.setup_joins( [related_field_name], opts, root_alias ) alias = join_info.joins[-1] from_parent = issubclass(model, opts.model) and model is not opts.model klass_info = { "model": model, "field": related_field, "reverse": True, "local_setter": related_field.remote_field.set_cached_value, "remote_setter": related_field.set_cached_value, "from_parent": from_parent, } related_klass_infos.append(klass_info) select_fields = [] columns = self.get_default_columns( related_select_mask, start_alias=alias, opts=model._meta, from_parent=opts.model, ) for col in columns: select_fields.append(len(select)) select.append((col, None)) klass_info["select_fields"] = select_fields next = requested.get(related_field.related_query_name(), {}) next_klass_infos = self.get_related_selections( select, related_select_mask, model._meta, alias, cur_depth + 1, next, restricted, ) get_related_klass_infos(klass_info, next_klass_infos) def local_setter(final_field, obj, from_obj): # Set a reverse fk object when relation is non-empty. if from_obj: final_field.remote_field.set_cached_value(from_obj, obj) def local_setter_noop(obj, from_obj): pass def remote_setter(name, obj, from_obj): setattr(from_obj, name, obj) for name in list(requested): # Filtered relations work only on the topmost level. if cur_depth > 1: break if name in self.query._filtered_relations: fields_found.add(name) final_field, _, join_opts, joins, _, _ = self.query.setup_joins( [name], opts, root_alias ) model = join_opts.model alias = joins[-1] from_parent = ( issubclass(model, opts.model) and model is not opts.model ) klass_info = { "model": model, "field": final_field, "reverse": True, "local_setter": ( partial(local_setter, final_field) if len(joins) <= 2 else local_setter_noop ), "remote_setter": partial(remote_setter, name), "from_parent": from_parent, } related_klass_infos.append(klass_info) select_fields = [] field_select_mask = select_mask.get((name, final_field)) or {} columns = self.get_default_columns( field_select_mask, start_alias=alias, opts=model._meta, from_parent=opts.model, ) for col in columns: select_fields.append(len(select)) select.append((col, None)) klass_info["select_fields"] = select_fields next_requested = requested.get(name, {}) next_klass_infos = self.get_related_selections( select, field_select_mask, opts=model._meta, root_alias=alias, cur_depth=cur_depth + 1, requested=next_requested, restricted=restricted, ) get_related_klass_infos(klass_info, next_klass_infos) fields_not_found = set(requested).difference(fields_found) if fields_not_found: invalid_fields = ("'%s'" % s for s in fields_not_found) raise FieldError( "Invalid field name(s) given in select_related: %s. " "Choices are: %s" % ( ", ".join(invalid_fields), ", ".join(_get_field_choices()) or "(none)", ) ) return related_klass_infos def get_select_for_update_of_arguments(self): """ Return a quoted list of arguments for the SELECT FOR UPDATE OF part of the query. """ def _get_parent_klass_info(klass_info): concrete_model = klass_info["model"]._meta.concrete_model for parent_model, parent_link in concrete_model._meta.parents.items(): parent_list = parent_model._meta.get_parent_list() yield { "model": parent_model, "field": parent_link, "reverse": False, "select_fields": [ select_index for select_index in klass_info["select_fields"] # Selected columns from a model or its parents. if ( self.select[select_index][0].target.model == parent_model or self.select[select_index][0].target.model in parent_list ) ], } def _get_first_selected_col_from_model(klass_info): """ Find the first selected column from a model. If it doesn't exist, don't lock a model. select_fields is filled recursively, so it also contains fields from the parent models. """ concrete_model = klass_info["model"]._meta.concrete_model for select_index in klass_info["select_fields"]: if self.select[select_index][0].target.model == concrete_model: return self.select[select_index][0] def _get_field_choices(): """Yield all allowed field paths in breadth-first search order.""" queue = collections.deque([(None, self.klass_info)]) while queue: parent_path, klass_info = queue.popleft() if parent_path is None: path = [] yield "self" else: field = klass_info["field"] if klass_info["reverse"]: field = field.remote_field path = parent_path + [field.name] yield LOOKUP_SEP.join(path) queue.extend( (path, klass_info) for klass_info in _get_parent_klass_info(klass_info) ) queue.extend( (path, klass_info) for klass_info in klass_info.get("related_klass_infos", []) ) if not self.klass_info: return [] result = [] invalid_names = [] for name in self.query.select_for_update_of: klass_info = self.klass_info if name == "self": col = _get_first_selected_col_from_model(klass_info) else: for part in name.split(LOOKUP_SEP): klass_infos = ( *klass_info.get("related_klass_infos", []), *_get_parent_klass_info(klass_info), ) for related_klass_info in klass_infos: field = related_klass_info["field"] if related_klass_info["reverse"]: field = field.remote_field if field.name == part: klass_info = related_klass_info break else: klass_info = None break if klass_info is None: invalid_names.append(name) continue col = _get_first_selected_col_from_model(klass_info) if col is not None: if self.connection.features.select_for_update_of_column: result.append(self.compile(col)[0]) else: result.append(self.quote_name_unless_alias(col.alias)) if invalid_names: raise FieldError( "Invalid field name(s) given in select_for_update(of=(...)): %s. " "Only relational fields followed in the query are allowed. " "Choices are: %s." % ( ", ".join(invalid_names), ", ".join(_get_field_choices()), ) ) return result def get_converters(self, expressions): converters = {} for i, expression in enumerate(expressions): if expression: backend_converters = self.connection.ops.get_db_converters(expression) field_converters = expression.get_db_converters(self.connection) if backend_converters or field_converters: converters[i] = (backend_converters + field_converters, expression) return converters def apply_converters(self, rows, converters): connection = self.connection converters = list(converters.items()) for row in map(list, rows): for pos, (convs, expression) in converters: value = row[pos] for converter in convs: value = converter(value, expression, connection) row[pos] = value yield row def results_iter( self, results=None, tuple_expected=False, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE, ): """Return an iterator over the results from executing this query.""" if results is None: results = self.execute_sql( MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size ) fields = [s[0] for s in self.select[0 : self.col_count]] converters = self.get_converters(fields) rows = chain.from_iterable(results) if converters: rows = self.apply_converters(rows, converters) if tuple_expected: rows = map(tuple, rows) return rows def has_results(self): """ Backends (e.g. NoSQL) can override this in order to use optimized versions of "query has any results." """ return bool(self.execute_sql(SINGLE)) def execute_sql( self, result_type=MULTI, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE ): """ Run the query against the database and return the result(s). The return value is a single data item if result_type is SINGLE, or an iterator over the results if the result_type is MULTI. result_type is either MULTI (use fetchmany() to retrieve all rows), SINGLE (only retrieve a single row), or None. In this last case, the cursor is returned if any query is executed, since it's used by subclasses such as InsertQuery). It's possible, however, that no query is needed, as the filters describe an empty set. In that case, None is returned, to avoid any unnecessary database interaction. """ result_type = result_type or NO_RESULTS try: sql, params = self.as_sql() if not sql: raise EmptyResultSet except EmptyResultSet: if result_type == MULTI: return iter([]) else: return if chunked_fetch: cursor = self.connection.chunked_cursor() else: cursor = self.connection.cursor() try: cursor.execute(sql, params) except Exception: # Might fail for server-side cursors (e.g. connection closed) cursor.close() raise if result_type == CURSOR: # Give the caller the cursor to process and close. return cursor if result_type == SINGLE: try: val = cursor.fetchone() if val: return val[0 : self.col_count] return val finally: # done with the cursor cursor.close() if result_type == NO_RESULTS: cursor.close() return result = cursor_iter( cursor, self.connection.features.empty_fetchmany_value, self.col_count if self.has_extra_select else None, chunk_size, ) if not chunked_fetch or not self.connection.features.can_use_chunked_reads: # If we are using non-chunked reads, we return the same data # structure as normally, but ensure it is all read into memory # before going any further. Use chunked_fetch if requested, # unless the database doesn't support it. return list(result) return result def as_subquery_condition(self, alias, columns, compiler): qn = compiler.quote_name_unless_alias qn2 = self.connection.ops.quote_name for index, select_col in enumerate(self.query.select): lhs_sql, lhs_params = self.compile(select_col) rhs = "%s.%s" % (qn(alias), qn2(columns[index])) self.query.where.add(RawSQL("%s = %s" % (lhs_sql, rhs), lhs_params), AND) sql, params = self.as_sql() return "EXISTS (%s)" % sql, params def explain_query(self): result = list(self.execute_sql()) # Some backends return 1 item tuples with strings, and others return # tuples with integers and strings. Flatten them out into strings. format_ = self.query.explain_info.format output_formatter = json.dumps if format_ and format_.lower() == "json" else str for row in result[0]: if not isinstance(row, str): yield " ".join(output_formatter(c) for c in row) else: yield row class SQLInsertCompiler(SQLCompiler): returning_fields = None returning_params = () def field_as_sql(self, field, val): """ Take a field and a value intended to be saved on that field, and return placeholder SQL and accompanying params. Check for raw values, expressions, and fields with get_placeholder() defined in that order. When field is None, consider the value raw and use it as the placeholder, with no corresponding parameters returned. """ if field is None: # A field value of None means the value is raw. sql, params = val, [] elif hasattr(val, "as_sql"): # This is an expression, let's compile it. sql, params = self.compile(val) elif hasattr(field, "get_placeholder"): # Some fields (e.g. geo fields) need special munging before # they can be inserted. sql, params = field.get_placeholder(val, self, self.connection), [val] else: # Return the common case for the placeholder sql, params = "%s", [val] # The following hook is only used by Oracle Spatial, which sometimes # needs to yield 'NULL' and [] as its placeholder and params instead # of '%s' and [None]. The 'NULL' placeholder is produced earlier by # OracleOperations.get_geom_placeholder(). The following line removes # the corresponding None parameter. See ticket #10888. params = self.connection.ops.modify_insert_params(sql, params) return sql, params def prepare_value(self, field, value): """ Prepare a value to be used in a query by resolving it if it is an expression and otherwise calling the field's get_db_prep_save(). """ if hasattr(value, "resolve_expression"): value = value.resolve_expression( self.query, allow_joins=False, for_save=True ) # Don't allow values containing Col expressions. They refer to # existing columns on a row, but in the case of insert the row # doesn't exist yet. if value.contains_column_references: raise ValueError( 'Failed to insert expression "%s" on %s. F() expressions ' "can only be used to update, not to insert." % (value, field) ) if value.contains_aggregate: raise FieldError( "Aggregate functions are not allowed in this query " "(%s=%r)." % (field.name, value) ) if value.contains_over_clause: raise FieldError( "Window expressions are not allowed in this query (%s=%r)." % (field.name, value) ) return field.get_db_prep_save(value, connection=self.connection) def pre_save_val(self, field, obj): """ Get the given field's value off the given obj. pre_save() is used for things like auto_now on DateTimeField. Skip it if this is a raw query. """ if self.query.raw: return getattr(obj, field.attname) return field.pre_save(obj, add=True) def assemble_as_sql(self, fields, value_rows): """ Take a sequence of N fields and a sequence of M rows of values, and generate placeholder SQL and parameters for each field and value. Return a pair containing: * a sequence of M rows of N SQL placeholder strings, and * a sequence of M rows of corresponding parameter values. Each placeholder string may contain any number of '%s' interpolation strings, and each parameter row will contain exactly as many params as the total number of '%s's in the corresponding placeholder row. """ if not value_rows: return [], [] # list of (sql, [params]) tuples for each object to be saved # Shape: [n_objs][n_fields][2] rows_of_fields_as_sql = ( (self.field_as_sql(field, v) for field, v in zip(fields, row)) for row in value_rows ) # tuple like ([sqls], [[params]s]) for each object to be saved # Shape: [n_objs][2][n_fields] sql_and_param_pair_rows = (zip(*row) for row in rows_of_fields_as_sql) # Extract separate lists for placeholders and params. # Each of these has shape [n_objs][n_fields] placeholder_rows, param_rows = zip(*sql_and_param_pair_rows) # Params for each field are still lists, and need to be flattened. param_rows = [[p for ps in row for p in ps] for row in param_rows] return placeholder_rows, param_rows def as_sql(self): # We don't need quote_name_unless_alias() here, since these are all # going to be column names (so we can avoid the extra overhead). qn = self.connection.ops.quote_name opts = self.query.get_meta() insert_statement = self.connection.ops.insert_statement( on_conflict=self.query.on_conflict, ) result = ["%s %s" % (insert_statement, qn(opts.db_table))] fields = self.query.fields or [opts.pk] result.append("(%s)" % ", ".join(qn(f.column) for f in fields)) if self.query.fields: value_rows = [ [ self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields ] for obj in self.query.objs ] else: # An empty object. value_rows = [ [self.connection.ops.pk_default_value()] for _ in self.query.objs ] fields = [None] # Currently the backends just accept values when generating bulk # queries and generate their own placeholders. Doing that isn't # necessary and it should be possible to use placeholders and # expressions in bulk inserts too. can_bulk = ( not self.returning_fields and self.connection.features.has_bulk_insert ) placeholder_rows, param_rows = self.assemble_as_sql(fields, value_rows) on_conflict_suffix_sql = self.connection.ops.on_conflict_suffix_sql( fields, self.query.on_conflict, (f.column for f in self.query.update_fields), (f.column for f in self.query.unique_fields), ) if ( self.returning_fields and self.connection.features.can_return_columns_from_insert ): if self.connection.features.can_return_rows_from_bulk_insert: result.append( self.connection.ops.bulk_insert_sql(fields, placeholder_rows) ) params = param_rows else: result.append("VALUES (%s)" % ", ".join(placeholder_rows[0])) params = [param_rows[0]] if on_conflict_suffix_sql: result.append(on_conflict_suffix_sql) # Skip empty r_sql to allow subclasses to customize behavior for # 3rd party backends. Refs #19096. r_sql, self.returning_params = self.connection.ops.return_insert_columns( self.returning_fields ) if r_sql: result.append(r_sql) params += [self.returning_params] return [(" ".join(result), tuple(chain.from_iterable(params)))] if can_bulk: result.append(self.connection.ops.bulk_insert_sql(fields, placeholder_rows)) if on_conflict_suffix_sql: result.append(on_conflict_suffix_sql) return [(" ".join(result), tuple(p for ps in param_rows for p in ps))] else: if on_conflict_suffix_sql: result.append(on_conflict_suffix_sql) return [ (" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals) for p, vals in zip(placeholder_rows, param_rows) ] def execute_sql(self, returning_fields=None): assert not ( returning_fields and len(self.query.objs) != 1 and not self.connection.features.can_return_rows_from_bulk_insert ) opts = self.query.get_meta() self.returning_fields = returning_fields with self.connection.cursor() as cursor: for sql, params in self.as_sql(): cursor.execute(sql, params) if not self.returning_fields: return [] if ( self.connection.features.can_return_rows_from_bulk_insert and len(self.query.objs) > 1 ): rows = self.connection.ops.fetch_returned_insert_rows(cursor) elif self.connection.features.can_return_columns_from_insert: assert len(self.query.objs) == 1 rows = [ self.connection.ops.fetch_returned_insert_columns( cursor, self.returning_params, ) ] else: rows = [ ( self.connection.ops.last_insert_id( cursor, opts.db_table, opts.pk.column, ), ) ] cols = [field.get_col(opts.db_table) for field in self.returning_fields] converters = self.get_converters(cols) if converters: rows = list(self.apply_converters(rows, converters)) return rows class SQLDeleteCompiler(SQLCompiler): @cached_property def single_alias(self): # Ensure base table is in aliases. self.query.get_initial_alias() return sum(self.query.alias_refcount[t] > 0 for t in self.query.alias_map) == 1 @classmethod def _expr_refs_base_model(cls, expr, base_model): if isinstance(expr, Query): return expr.model == base_model if not hasattr(expr, "get_source_expressions"): return False return any( cls._expr_refs_base_model(source_expr, base_model) for source_expr in expr.get_source_expressions() ) @cached_property def contains_self_reference_subquery(self): return any( self._expr_refs_base_model(expr, self.query.model) for expr in chain( self.query.annotations.values(), self.query.where.children ) ) def _as_sql(self, query): delete = "DELETE FROM %s" % self.quote_name_unless_alias(query.base_table) try: where, params = self.compile(query.where) except FullResultSet: return delete, () return f"{delete} WHERE {where}", tuple(params) def as_sql(self): """ Create the SQL for this query. Return the SQL string and list of parameters. """ if self.single_alias and ( self.connection.features.delete_can_self_reference_subquery or not self.contains_self_reference_subquery ): return self._as_sql(self.query) innerq = self.query.clone() innerq.__class__ = Query innerq.clear_select_clause() pk = self.query.model._meta.pk innerq.select = [pk.get_col(self.query.get_initial_alias())] outerq = Query(self.query.model) if not self.connection.features.update_can_self_select: # Force the materialization of the inner query to allow reference # to the target table on MySQL. sql, params = innerq.get_compiler(connection=self.connection).as_sql() innerq = RawSQL("SELECT * FROM (%s) subquery" % sql, params) outerq.add_filter("pk__in", innerq) return self._as_sql(outerq) class SQLUpdateCompiler(SQLCompiler): def as_sql(self): """ Create the SQL for this query. Return the SQL string and list of parameters. """ self.pre_sql_setup() if not self.query.values: return "", () qn = self.quote_name_unless_alias values, update_params = [], [] for field, model, val in self.query.values: if hasattr(val, "resolve_expression"): val = val.resolve_expression( self.query, allow_joins=False, for_save=True ) if val.contains_aggregate: raise FieldError( "Aggregate functions are not allowed in this query " "(%s=%r)." % (field.name, val) ) if val.contains_over_clause: raise FieldError( "Window expressions are not allowed in this query " "(%s=%r)." % (field.name, val) ) elif hasattr(val, "prepare_database_save"): if field.remote_field: val = val.prepare_database_save(field) else: raise TypeError( "Tried to update field %s with a model instance, %r. " "Use a value compatible with %s." % (field, val, field.__class__.__name__) ) val = field.get_db_prep_save(val, connection=self.connection) # Getting the placeholder for the field. if hasattr(field, "get_placeholder"): placeholder = field.get_placeholder(val, self, self.connection) else: placeholder = "%s" name = field.column if hasattr(val, "as_sql"): sql, params = self.compile(val) values.append("%s = %s" % (qn(name), placeholder % sql)) update_params.extend(params) elif val is not None: values.append("%s = %s" % (qn(name), placeholder)) update_params.append(val) else: values.append("%s = NULL" % qn(name)) table = self.query.base_table result = [ "UPDATE %s SET" % qn(table), ", ".join(values), ] try: where, params = self.compile(self.query.where) except FullResultSet: params = [] else: result.append("WHERE %s" % where) return " ".join(result), tuple(update_params + params) def execute_sql(self, result_type): """ Execute the specified update. Return the number of rows affected by the primary update query. The "primary update query" is the first non-empty query that is executed. Row counts for any subsequent, related queries are not available. """ cursor = super().execute_sql(result_type) try: rows = cursor.rowcount if cursor else 0 is_empty = cursor is None finally: if cursor: cursor.close() for query in self.query.get_related_updates(): aux_rows = query.get_compiler(self.using).execute_sql(result_type) if is_empty and aux_rows: rows = aux_rows is_empty = False return rows def pre_sql_setup(self): """ If the update depends on results from other tables, munge the "where" conditions to match the format required for (portable) SQL updates. If multiple updates are required, pull out the id values to update at this point so that they don't change as a result of the progressive updates. """ refcounts_before = self.query.alias_refcount.copy() # Ensure base table is in the query self.query.get_initial_alias() count = self.query.count_active_tables() if not self.query.related_updates and count == 1: return query = self.query.chain(klass=Query) query.select_related = False query.clear_ordering(force=True) query.extra = {} query.select = [] meta = query.get_meta() fields = [meta.pk.name] related_ids_index = [] for related in self.query.related_updates: if all( path.join_field.primary_key for path in meta.get_path_to_parent(related) ): # If a primary key chain exists to the targeted related update, # then the meta.pk value can be used for it. related_ids_index.append((related, 0)) else: # This branch will only be reached when updating a field of an # ancestor that is not part of the primary key chain of a MTI # tree. related_ids_index.append((related, len(fields))) fields.append(related._meta.pk.name) query.add_fields(fields) super().pre_sql_setup() must_pre_select = ( count > 1 and not self.connection.features.update_can_self_select ) # Now we adjust the current query: reset the where clause and get rid # of all the tables we don't need (since they're in the sub-select). self.query.clear_where() if self.query.related_updates or must_pre_select: # Either we're using the idents in multiple update queries (so # don't want them to change), or the db backend doesn't support # selecting from the updating table (e.g. MySQL). idents = [] related_ids = collections.defaultdict(list) for rows in query.get_compiler(self.using).execute_sql(MULTI): idents.extend(r[0] for r in rows) for parent, index in related_ids_index: related_ids[parent].extend(r[index] for r in rows) self.query.add_filter("pk__in", idents) self.query.related_ids = related_ids else: # The fast path. Filters and updates in one query. self.query.add_filter("pk__in", query) self.query.reset_refcounts(refcounts_before) class SQLAggregateCompiler(SQLCompiler): def as_sql(self): """ Create the SQL for this query. Return the SQL string and list of parameters. """ sql, params = [], [] for annotation in self.query.annotation_select.values(): ann_sql, ann_params = self.compile(annotation) ann_sql, ann_params = annotation.select_format(self, ann_sql, ann_params) sql.append(ann_sql) params.extend(ann_params) self.col_count = len(self.query.annotation_select) sql = ", ".join(sql) params = tuple(params) inner_query_sql, inner_query_params = self.query.inner_query.get_compiler( self.using, elide_empty=self.elide_empty, ).as_sql(with_col_aliases=True) sql = "SELECT %s FROM (%s) subquery" % (sql, inner_query_sql) params += inner_query_params return sql, params def cursor_iter(cursor, sentinel, col_count, itersize): """ Yield blocks of rows from a cursor and ensure the cursor is closed when done. """ try: for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): yield rows if col_count is None else [r[:col_count] for r in rows] finally: cursor.close()