1. import datetime
    
  2. 
    
  3. from django import forms
    
  4. from django.core.exceptions import ValidationError
    
  5. from django.forms.models import ModelChoiceIterator, ModelChoiceIteratorValue
    
  6. from django.forms.widgets import CheckboxSelectMultiple
    
  7. from django.template import Context, Template
    
  8. from django.test import TestCase
    
  9. 
    
  10. from .models import Article, Author, Book, Category, Writer
    
  11. 
    
  12. 
    
  13. class ModelChoiceFieldTests(TestCase):
    
  14.     @classmethod
    
  15.     def setUpTestData(cls):
    
  16.         cls.c1 = Category.objects.create(
    
  17.             name="Entertainment", slug="entertainment", url="entertainment"
    
  18.         )
    
  19.         cls.c2 = Category.objects.create(name="A test", slug="test", url="test")
    
  20.         cls.c3 = Category.objects.create(name="Third", slug="third-test", url="third")
    
  21. 
    
  22.     def test_basics(self):
    
  23.         f = forms.ModelChoiceField(Category.objects.all())
    
  24.         self.assertEqual(
    
  25.             list(f.choices),
    
  26.             [
    
  27.                 ("", "---------"),
    
  28.                 (self.c1.pk, "Entertainment"),
    
  29.                 (self.c2.pk, "A test"),
    
  30.                 (self.c3.pk, "Third"),
    
  31.             ],
    
  32.         )
    
  33.         with self.assertRaises(ValidationError):
    
  34.             f.clean("")
    
  35.         with self.assertRaises(ValidationError):
    
  36.             f.clean(None)
    
  37.         with self.assertRaises(ValidationError):
    
  38.             f.clean(0)
    
  39. 
    
  40.         # Invalid types that require TypeError to be caught.
    
  41.         with self.assertRaises(ValidationError):
    
  42.             f.clean([["fail"]])
    
  43.         with self.assertRaises(ValidationError):
    
  44.             f.clean([{"foo": "bar"}])
    
  45. 
    
  46.         self.assertEqual(f.clean(self.c2.id).name, "A test")
    
  47.         self.assertEqual(f.clean(self.c3.id).name, "Third")
    
  48. 
    
  49.         # Add a Category object *after* the ModelChoiceField has already been
    
  50.         # instantiated. This proves clean() checks the database during clean()
    
  51.         # rather than caching it at  instantiation time.
    
  52.         c4 = Category.objects.create(name="Fourth", url="4th")
    
  53.         self.assertEqual(f.clean(c4.id).name, "Fourth")
    
  54. 
    
  55.         # Delete a Category object *after* the ModelChoiceField has already been
    
  56.         # instantiated. This proves clean() checks the database during clean()
    
  57.         # rather than caching it at instantiation time.
    
  58.         Category.objects.get(url="4th").delete()
    
  59.         msg = (
    
  60.             "['Select a valid choice. That choice is not one of the available "
    
  61.             "choices.']"
    
  62.         )
    
  63.         with self.assertRaisesMessage(ValidationError, msg):
    
  64.             f.clean(c4.id)
    
  65. 
    
  66.     def test_clean_model_instance(self):
    
  67.         f = forms.ModelChoiceField(Category.objects.all())
    
  68.         self.assertEqual(f.clean(self.c1), self.c1)
    
  69.         # An instance of incorrect model.
    
  70.         msg = (
    
  71.             "['Select a valid choice. That choice is not one of the available "
    
  72.             "choices.']"
    
  73.         )
    
  74.         with self.assertRaisesMessage(ValidationError, msg):
    
  75.             f.clean(Book.objects.create())
    
  76. 
    
  77.     def test_clean_to_field_name(self):
    
  78.         f = forms.ModelChoiceField(Category.objects.all(), to_field_name="slug")
    
  79.         self.assertEqual(f.clean(self.c1.slug), self.c1)
    
  80.         self.assertEqual(f.clean(self.c1), self.c1)
    
  81. 
    
  82.     def test_choices(self):
    
  83.         f = forms.ModelChoiceField(
    
  84.             Category.objects.filter(pk=self.c1.id), required=False
    
  85.         )
    
  86.         self.assertIsNone(f.clean(""))
    
  87.         self.assertEqual(f.clean(str(self.c1.id)).name, "Entertainment")
    
  88.         with self.assertRaises(ValidationError):
    
  89.             f.clean("100")
    
  90. 
    
  91.         # len() can be called on choices.
    
  92.         self.assertEqual(len(f.choices), 2)
    
  93. 
    
  94.         # queryset can be changed after the field is created.
    
  95.         f.queryset = Category.objects.exclude(name="Third").order_by("pk")
    
  96.         self.assertEqual(
    
  97.             list(f.choices),
    
  98.             [
    
  99.                 ("", "---------"),
    
  100.                 (self.c1.pk, "Entertainment"),
    
  101.                 (self.c2.pk, "A test"),
    
  102.             ],
    
  103.         )
    
  104.         self.assertEqual(f.clean(self.c2.id).name, "A test")
    
  105.         with self.assertRaises(ValidationError):
    
  106.             f.clean(self.c3.id)
    
  107. 
    
  108.         # Choices can be iterated repeatedly.
    
  109.         gen_one = list(f.choices)
    
  110.         gen_two = f.choices
    
  111.         self.assertEqual(gen_one[2], (self.c2.pk, "A test"))
    
  112.         self.assertEqual(
    
  113.             list(gen_two),
    
  114.             [
    
  115.                 ("", "---------"),
    
  116.                 (self.c1.pk, "Entertainment"),
    
  117.                 (self.c2.pk, "A test"),
    
  118.             ],
    
  119.         )
    
  120. 
    
  121.         # Overriding label_from_instance() to print custom labels.
    
  122.         f.queryset = Category.objects.order_by("pk")
    
  123.         f.label_from_instance = lambda obj: "category " + str(obj)
    
  124.         self.assertEqual(
    
  125.             list(f.choices),
    
  126.             [
    
  127.                 ("", "---------"),
    
  128.                 (self.c1.pk, "category Entertainment"),
    
  129.                 (self.c2.pk, "category A test"),
    
  130.                 (self.c3.pk, "category Third"),
    
  131.             ],
    
  132.         )
    
  133. 
    
  134.     def test_choices_freshness(self):
    
  135.         f = forms.ModelChoiceField(Category.objects.order_by("pk"))
    
  136.         self.assertEqual(len(f.choices), 4)
    
  137.         self.assertEqual(
    
  138.             list(f.choices),
    
  139.             [
    
  140.                 ("", "---------"),
    
  141.                 (self.c1.pk, "Entertainment"),
    
  142.                 (self.c2.pk, "A test"),
    
  143.                 (self.c3.pk, "Third"),
    
  144.             ],
    
  145.         )
    
  146.         c4 = Category.objects.create(name="Fourth", slug="4th", url="4th")
    
  147.         self.assertEqual(len(f.choices), 5)
    
  148.         self.assertEqual(
    
  149.             list(f.choices),
    
  150.             [
    
  151.                 ("", "---------"),
    
  152.                 (self.c1.pk, "Entertainment"),
    
  153.                 (self.c2.pk, "A test"),
    
  154.                 (self.c3.pk, "Third"),
    
  155.                 (c4.pk, "Fourth"),
    
  156.             ],
    
  157.         )
    
  158. 
    
  159.     def test_choices_bool(self):
    
  160.         f = forms.ModelChoiceField(Category.objects.all(), empty_label=None)
    
  161.         self.assertIs(bool(f.choices), True)
    
  162.         Category.objects.all().delete()
    
  163.         self.assertIs(bool(f.choices), False)
    
  164. 
    
  165.     def test_choices_bool_empty_label(self):
    
  166.         f = forms.ModelChoiceField(Category.objects.all(), empty_label="--------")
    
  167.         Category.objects.all().delete()
    
  168.         self.assertIs(bool(f.choices), True)
    
  169. 
    
  170.     def test_choices_radio_blank(self):
    
  171.         choices = [
    
  172.             (self.c1.pk, "Entertainment"),
    
  173.             (self.c2.pk, "A test"),
    
  174.             (self.c3.pk, "Third"),
    
  175.         ]
    
  176.         categories = Category.objects.order_by("pk")
    
  177.         for widget in [forms.RadioSelect, forms.RadioSelect()]:
    
  178.             for blank in [True, False]:
    
  179.                 with self.subTest(widget=widget, blank=blank):
    
  180.                     f = forms.ModelChoiceField(
    
  181.                         categories,
    
  182.                         widget=widget,
    
  183.                         blank=blank,
    
  184.                     )
    
  185.                     self.assertEqual(
    
  186.                         list(f.choices),
    
  187.                         [("", "---------")] + choices if blank else choices,
    
  188.                     )
    
  189. 
    
  190.     def test_deepcopies_widget(self):
    
  191.         class ModelChoiceForm(forms.Form):
    
  192.             category = forms.ModelChoiceField(Category.objects.all())
    
  193. 
    
  194.         form1 = ModelChoiceForm()
    
  195.         field1 = form1.fields["category"]
    
  196.         # To allow the widget to change the queryset of field1.widget.choices
    
  197.         # without affecting other forms, the following must hold (#11183):
    
  198.         self.assertIsNot(field1, ModelChoiceForm.base_fields["category"])
    
  199.         self.assertIs(field1.widget.choices.field, field1)
    
  200. 
    
  201.     def test_result_cache_not_shared(self):
    
  202.         class ModelChoiceForm(forms.Form):
    
  203.             category = forms.ModelChoiceField(Category.objects.all())
    
  204. 
    
  205.         form1 = ModelChoiceForm()
    
  206.         self.assertCountEqual(
    
  207.             form1.fields["category"].queryset, [self.c1, self.c2, self.c3]
    
  208.         )
    
  209.         form2 = ModelChoiceForm()
    
  210.         self.assertIsNone(form2.fields["category"].queryset._result_cache)
    
  211. 
    
  212.     def test_queryset_none(self):
    
  213.         class ModelChoiceForm(forms.Form):
    
  214.             category = forms.ModelChoiceField(queryset=None)
    
  215. 
    
  216.             def __init__(self, *args, **kwargs):
    
  217.                 super().__init__(*args, **kwargs)
    
  218.                 self.fields["category"].queryset = Category.objects.filter(
    
  219.                     slug__contains="test"
    
  220.                 )
    
  221. 
    
  222.         form = ModelChoiceForm()
    
  223.         self.assertCountEqual(form.fields["category"].queryset, [self.c2, self.c3])
    
  224. 
    
  225.     def test_no_extra_query_when_accessing_attrs(self):
    
  226.         """
    
  227.         ModelChoiceField with RadioSelect widget doesn't produce unnecessary
    
  228.         db queries when accessing its BoundField's attrs.
    
  229.         """
    
  230. 
    
  231.         class ModelChoiceForm(forms.Form):
    
  232.             category = forms.ModelChoiceField(
    
  233.                 Category.objects.all(), widget=forms.RadioSelect
    
  234.             )
    
  235. 
    
  236.         form = ModelChoiceForm()
    
  237.         field = form["category"]  # BoundField
    
  238.         template = Template("{{ field.name }}{{ field }}{{ field.help_text }}")
    
  239.         with self.assertNumQueries(1):
    
  240.             template.render(Context({"field": field}))
    
  241. 
    
  242.     def test_disabled_modelchoicefield(self):
    
  243.         class ModelChoiceForm(forms.ModelForm):
    
  244.             author = forms.ModelChoiceField(Author.objects.all(), disabled=True)
    
  245. 
    
  246.             class Meta:
    
  247.                 model = Book
    
  248.                 fields = ["author"]
    
  249. 
    
  250.         book = Book.objects.create(author=Writer.objects.create(name="Test writer"))
    
  251.         form = ModelChoiceForm({}, instance=book)
    
  252.         self.assertEqual(
    
  253.             form.errors["author"],
    
  254.             ["Select a valid choice. That choice is not one of the available choices."],
    
  255.         )
    
  256. 
    
  257.     def test_disabled_modelchoicefield_has_changed(self):
    
  258.         field = forms.ModelChoiceField(Author.objects.all(), disabled=True)
    
  259.         self.assertIs(field.has_changed("x", "y"), False)
    
  260. 
    
  261.     def test_disabled_modelchoicefield_initial_model_instance(self):
    
  262.         class ModelChoiceForm(forms.Form):
    
  263.             categories = forms.ModelChoiceField(
    
  264.                 Category.objects.all(),
    
  265.                 disabled=True,
    
  266.                 initial=self.c1,
    
  267.             )
    
  268. 
    
  269.         self.assertTrue(ModelChoiceForm(data={"categories": self.c1.pk}).is_valid())
    
  270. 
    
  271.     def test_disabled_multiplemodelchoicefield(self):
    
  272.         class ArticleForm(forms.ModelForm):
    
  273.             categories = forms.ModelMultipleChoiceField(
    
  274.                 Category.objects.all(), required=False
    
  275.             )
    
  276. 
    
  277.             class Meta:
    
  278.                 model = Article
    
  279.                 fields = ["categories"]
    
  280. 
    
  281.         category1 = Category.objects.create(name="cat1")
    
  282.         category2 = Category.objects.create(name="cat2")
    
  283.         article = Article.objects.create(
    
  284.             pub_date=datetime.date(1988, 1, 4),
    
  285.             writer=Writer.objects.create(name="Test writer"),
    
  286.         )
    
  287.         article.categories.set([category1.pk])
    
  288. 
    
  289.         form = ArticleForm(data={"categories": [category2.pk]}, instance=article)
    
  290.         self.assertEqual(form.errors, {})
    
  291.         self.assertEqual(
    
  292.             [x.pk for x in form.cleaned_data["categories"]], [category2.pk]
    
  293.         )
    
  294.         # Disabled fields use the value from `instance` rather than `data`.
    
  295.         form = ArticleForm(data={"categories": [category2.pk]}, instance=article)
    
  296.         form.fields["categories"].disabled = True
    
  297.         self.assertEqual(form.errors, {})
    
  298.         self.assertEqual(
    
  299.             [x.pk for x in form.cleaned_data["categories"]], [category1.pk]
    
  300.         )
    
  301. 
    
  302.     def test_disabled_modelmultiplechoicefield_has_changed(self):
    
  303.         field = forms.ModelMultipleChoiceField(Author.objects.all(), disabled=True)
    
  304.         self.assertIs(field.has_changed("x", "y"), False)
    
  305. 
    
  306.     def test_overridable_choice_iterator(self):
    
  307.         """
    
  308.         Iterator defaults to ModelChoiceIterator and can be overridden with
    
  309.         the iterator attribute on a ModelChoiceField subclass.
    
  310.         """
    
  311.         field = forms.ModelChoiceField(Category.objects.all())
    
  312.         self.assertIsInstance(field.choices, ModelChoiceIterator)
    
  313. 
    
  314.         class CustomModelChoiceIterator(ModelChoiceIterator):
    
  315.             pass
    
  316. 
    
  317.         class CustomModelChoiceField(forms.ModelChoiceField):
    
  318.             iterator = CustomModelChoiceIterator
    
  319. 
    
  320.         field = CustomModelChoiceField(Category.objects.all())
    
  321.         self.assertIsInstance(field.choices, CustomModelChoiceIterator)
    
  322. 
    
  323.     def test_choice_iterator_passes_model_to_widget(self):
    
  324.         class CustomCheckboxSelectMultiple(CheckboxSelectMultiple):
    
  325.             def create_option(
    
  326.                 self, name, value, label, selected, index, subindex=None, attrs=None
    
  327.             ):
    
  328.                 option = super().create_option(
    
  329.                     name, value, label, selected, index, subindex, attrs
    
  330.                 )
    
  331.                 # Modify the HTML based on the object being rendered.
    
  332.                 c = value.instance
    
  333.                 option["attrs"]["data-slug"] = c.slug
    
  334.                 return option
    
  335. 
    
  336.         class CustomModelMultipleChoiceField(forms.ModelMultipleChoiceField):
    
  337.             widget = CustomCheckboxSelectMultiple
    
  338. 
    
  339.         field = CustomModelMultipleChoiceField(Category.objects.order_by("pk"))
    
  340.         self.assertHTMLEqual(
    
  341.             field.widget.render("name", []),
    
  342.             (
    
  343.                 "<div>"
    
  344.                 '<div><label><input type="checkbox" name="name" value="%d" '
    
  345.                 'data-slug="entertainment">Entertainment</label></div>'
    
  346.                 '<div><label><input type="checkbox" name="name" value="%d" '
    
  347.                 'data-slug="test">A test</label></div>'
    
  348.                 '<div><label><input type="checkbox" name="name" value="%d" '
    
  349.                 'data-slug="third-test">Third</label></div>'
    
  350.                 "</div>"
    
  351.             )
    
  352.             % (self.c1.pk, self.c2.pk, self.c3.pk),
    
  353.         )
    
  354. 
    
  355.     def test_custom_choice_iterator_passes_model_to_widget(self):
    
  356.         class CustomModelChoiceValue:
    
  357.             def __init__(self, value, obj):
    
  358.                 self.value = value
    
  359.                 self.obj = obj
    
  360. 
    
  361.             def __str__(self):
    
  362.                 return str(self.value)
    
  363. 
    
  364.         class CustomModelChoiceIterator(ModelChoiceIterator):
    
  365.             def choice(self, obj):
    
  366.                 value, label = super().choice(obj)
    
  367.                 return CustomModelChoiceValue(value, obj), label
    
  368. 
    
  369.         class CustomCheckboxSelectMultiple(CheckboxSelectMultiple):
    
  370.             def create_option(
    
  371.                 self, name, value, label, selected, index, subindex=None, attrs=None
    
  372.             ):
    
  373.                 option = super().create_option(
    
  374.                     name, value, label, selected, index, subindex, attrs
    
  375.                 )
    
  376.                 # Modify the HTML based on the object being rendered.
    
  377.                 c = value.obj
    
  378.                 option["attrs"]["data-slug"] = c.slug
    
  379.                 return option
    
  380. 
    
  381.         class CustomModelMultipleChoiceField(forms.ModelMultipleChoiceField):
    
  382.             iterator = CustomModelChoiceIterator
    
  383.             widget = CustomCheckboxSelectMultiple
    
  384. 
    
  385.         field = CustomModelMultipleChoiceField(Category.objects.order_by("pk"))
    
  386.         self.assertHTMLEqual(
    
  387.             field.widget.render("name", []),
    
  388.             """
    
  389.             <div><div>
    
  390.             <label><input type="checkbox" name="name" value="%d"
    
  391.                 data-slug="entertainment">Entertainment
    
  392.             </label></div>
    
  393.             <div><label>
    
  394.             <input type="checkbox" name="name" value="%d" data-slug="test">A test
    
  395.             </label></div>
    
  396.             <div><label>
    
  397.             <input type="checkbox" name="name" value="%d" data-slug="third-test">Third
    
  398.             </label></div></div>
    
  399.             """
    
  400.             % (self.c1.pk, self.c2.pk, self.c3.pk),
    
  401.         )
    
  402. 
    
  403.     def test_choice_value_hash(self):
    
  404.         value_1 = ModelChoiceIteratorValue(self.c1.pk, self.c1)
    
  405.         value_2 = ModelChoiceIteratorValue(self.c2.pk, self.c2)
    
  406.         self.assertEqual(
    
  407.             hash(value_1), hash(ModelChoiceIteratorValue(self.c1.pk, None))
    
  408.         )
    
  409.         self.assertNotEqual(hash(value_1), hash(value_2))
    
  410. 
    
  411.     def test_choices_not_fetched_when_not_rendering(self):
    
  412.         with self.assertNumQueries(1):
    
  413.             field = forms.ModelChoiceField(Category.objects.order_by("-name"))
    
  414.             self.assertEqual("Entertainment", field.clean(self.c1.pk).name)
    
  415. 
    
  416.     def test_queryset_manager(self):
    
  417.         f = forms.ModelChoiceField(Category.objects)
    
  418.         self.assertEqual(len(f.choices), 4)
    
  419.         self.assertCountEqual(
    
  420.             list(f.choices),
    
  421.             [
    
  422.                 ("", "---------"),
    
  423.                 (self.c1.pk, "Entertainment"),
    
  424.                 (self.c2.pk, "A test"),
    
  425.                 (self.c3.pk, "Third"),
    
  426.             ],
    
  427.         )
    
  428. 
    
  429.     def test_num_queries(self):
    
  430.         """
    
  431.         Widgets that render multiple subwidgets shouldn't make more than one
    
  432.         database query.
    
  433.         """
    
  434.         categories = Category.objects.all()
    
  435. 
    
  436.         class CategoriesForm(forms.Form):
    
  437.             radio = forms.ModelChoiceField(
    
  438.                 queryset=categories, widget=forms.RadioSelect
    
  439.             )
    
  440.             checkbox = forms.ModelMultipleChoiceField(
    
  441.                 queryset=categories, widget=forms.CheckboxSelectMultiple
    
  442.             )
    
  443. 
    
  444.         template = Template(
    
  445.             "{% for widget in form.checkbox %}{{ widget }}{% endfor %}"
    
  446.             "{% for widget in form.radio %}{{ widget }}{% endfor %}"
    
  447.         )
    
  448.         with self.assertNumQueries(2):
    
  449.             template.render(Context({"form": CategoriesForm()}))