test_modelchoicefield.py 16 KB

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