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