Debian Codegraph @

tests/model_forms/tests.py

raw
1 import datetime
2 import os
3 import shutil
4 from decimal import Decimal
5 from unittest import mock, skipUnless
6
7 from django import forms
8 from django.core.exceptions import (
9 NON_FIELD_ERRORS,
10 FieldError,
11 ImproperlyConfigured,
12 ValidationError,
13 )
14 from django.core.files.uploadedfile import SimpleUploadedFile
15 from django.db import connection, models
16 from django.db.models.query import EmptyQuerySet
17 from django.forms.models import (
18 ModelFormMetaclass,
19 construct_instance,
20 fields_for_model,
21 model_to_dict,
22 modelform_factory,
23 )
24 from django.template import Context, Template
25 from django.test import SimpleTestCase, TestCase, ignore_warnings, skipUnlessDBFeature
26 from django.test.utils import isolate_apps
27 from django.utils.choices import BlankChoiceIterator
28 from django.utils.deprecation import RemovedInDjango60Warning
29 from django.utils.version import PY314, PYPY
30
31 from .models import (
32 Article,
33 ArticleStatus,
34 Author,
35 Author1,
36 Award,
37 BetterWriter,
38 BigInt,
39 Book,
40 Category,
41 Character,
42 Colour,
43 ColourfulItem,
44 CustomErrorMessage,
45 CustomFF,
46 CustomFieldForExclusionModel,
47 DateTimePost,
48 DerivedBook,
49 DerivedPost,
50 Dice,
51 Document,
52 ExplicitPK,
53 FilePathModel,
54 FlexibleDatePost,
55 Homepage,
56 ImprovedArticle,
57 ImprovedArticleWithParentLink,
58 Inventory,
59 NullableUniqueCharFieldModel,
60 Number,
61 Person,
62 Photo,
63 Post,
64 Price,
65 Product,
66 Publication,
67 PublicationDefaults,
68 StrictAssignmentAll,
69 StrictAssignmentFieldSpecific,
70 Student,
71 StumpJoke,
72 TextFile,
73 Triple,
74 Writer,
75 WriterProfile,
76 temp_storage_dir,
77 test_images,
78 )
79
80 if test_images:
81 from .models import ImageFile, NoExtensionImageFile, OptionalImageFile
82
83 class ImageFileForm(forms.ModelForm):
84 class Meta:
85 model = ImageFile
86 fields = "__all__"
87
88 class OptionalImageFileForm(forms.ModelForm):
89 class Meta:
90 model = OptionalImageFile
91 fields = "__all__"
92
93 class NoExtensionImageFileForm(forms.ModelForm):
94 class Meta:
95 model = NoExtensionImageFile
96 fields = "__all__"
97
98
99 class ProductForm(forms.ModelForm):
100 class Meta:
101 model = Product
102 fields = "__all__"
103
104
105 class PriceForm(forms.ModelForm):
106 class Meta:
107 model = Price
108 fields = "__all__"
109
110
111 class BookForm(forms.ModelForm):
112 class Meta:
113 model = Book
114 fields = "__all__"
115
116
117 class DerivedBookForm(forms.ModelForm):
118 class Meta:
119 model = DerivedBook
120 fields = "__all__"
121
122
123 class ExplicitPKForm(forms.ModelForm):
124 class Meta:
125 model = ExplicitPK
126 fields = (
127 "key",
128 "desc",
129 )
130
131
132 class PostForm(forms.ModelForm):
133 class Meta:
134 model = Post
135 fields = "__all__"
136
137
138 class DerivedPostForm(forms.ModelForm):
139 class Meta:
140 model = DerivedPost
141 fields = "__all__"
142
143
144 class CustomWriterForm(forms.ModelForm):
145 name = forms.CharField(required=False)
146
147 class Meta:
148 model = Writer
149 fields = "__all__"
150
151
152 class BaseCategoryForm(forms.ModelForm):
153 class Meta:
154 model = Category
155 fields = "__all__"
156
157
158 class ArticleForm(forms.ModelForm):
159 class Meta:
160 model = Article
161 fields = "__all__"
162
163
164 class RoykoForm(forms.ModelForm):
165 class Meta:
166 model = Writer
167 fields = "__all__"
168
169
170 class ArticleStatusForm(forms.ModelForm):
171 class Meta:
172 model = ArticleStatus
173 fields = "__all__"
174
175
176 class InventoryForm(forms.ModelForm):
177 class Meta:
178 model = Inventory
179 fields = "__all__"
180
181
182 class SelectInventoryForm(forms.Form):
183 items = forms.ModelMultipleChoiceField(
184 Inventory.objects.all(), to_field_name="barcode"
185 )
186
187
188 class CustomFieldForExclusionForm(forms.ModelForm):
189 class Meta:
190 model = CustomFieldForExclusionModel
191 fields = ["name", "markup"]
192
193
194 class TextFileForm(forms.ModelForm):
195 class Meta:
196 model = TextFile
197 fields = "__all__"
198
199
200 class BigIntForm(forms.ModelForm):
201 class Meta:
202 model = BigInt
203 fields = "__all__"
204
205
206 class ModelFormWithMedia(forms.ModelForm):
207 class Media:
208 js = ("/some/form/javascript",)
209 css = {"all": ("/some/form/css",)}
210
211 class Meta:
212 model = TextFile
213 fields = "__all__"
214
215
216 class CustomErrorMessageForm(forms.ModelForm):
217 name1 = forms.CharField(error_messages={"invalid": "Form custom error message."})
218
219 class Meta:
220 fields = "__all__"
221 model = CustomErrorMessage
222
223
224 class ModelFormBaseTest(TestCase):
225 def test_base_form(self):
226 self.assertEqual(list(BaseCategoryForm.base_fields), ["name", "slug", "url"])
227
228 def test_no_model_class(self):
229 class NoModelModelForm(forms.ModelForm):
230 pass
231
232 with self.assertRaisesMessage(
233 ValueError, "ModelForm has no model class specified."
234 ):
235 NoModelModelForm()
236
237 def test_empty_fields_to_fields_for_model(self):
238 """
239 An argument of fields=() to fields_for_model should return an empty dictionary
240 """
241 field_dict = fields_for_model(Person, fields=())
242 self.assertEqual(len(field_dict), 0)
243
244 def test_fields_for_model_form_fields(self):
245 form_declared_fields = CustomWriterForm.declared_fields
246 field_dict = fields_for_model(
247 Writer,
248 fields=["name"],
249 form_declared_fields=form_declared_fields,
250 )
251 self.assertIs(field_dict["name"], form_declared_fields["name"])
252
253 def test_empty_fields_on_modelform(self):
254 """
255 No fields on a ModelForm should actually result in no fields.
256 """
257
258 class EmptyPersonForm(forms.ModelForm):
259 class Meta:
260 model = Person
261 fields = ()
262
263 form = EmptyPersonForm()
264 self.assertEqual(len(form.fields), 0)
265
266 def test_empty_fields_to_construct_instance(self):
267 """
268 No fields should be set on a model instance if construct_instance
269 receives fields=().
270 """
271 form = modelform_factory(Person, fields="__all__")({"name": "John Doe"})
272 self.assertTrue(form.is_valid())
273 instance = construct_instance(form, Person(), fields=())
274 self.assertEqual(instance.name, "")
275
276 def test_blank_with_null_foreign_key_field(self):
277 """
278 #13776 -- ModelForm's with models having a FK set to null=False and
279 required=False should be valid.
280 """
281
282 class FormForTestingIsValid(forms.ModelForm):
283 class Meta:
284 model = Student
285 fields = "__all__"
286
287 def __init__(self, *args, **kwargs):
288 super().__init__(*args, **kwargs)
289 self.fields["character"].required = False
290
291 char = Character.objects.create(
292 username="user", last_action=datetime.datetime.today()
293 )
294 data = {"study": "Engineering"}
295 data2 = {"study": "Engineering", "character": char.pk}
296
297 # form is valid because required=False for field 'character'
298 f1 = FormForTestingIsValid(data)
299 self.assertTrue(f1.is_valid())
300
301 f2 = FormForTestingIsValid(data2)
302 self.assertTrue(f2.is_valid())
303 obj = f2.save()
304 self.assertEqual(obj.character, char)
305
306 def test_blank_false_with_null_true_foreign_key_field(self):
307 """
308 A ModelForm with a model having ForeignKey(blank=False, null=True)
309 and the form field set to required=False should allow the field to be
310 unset.
311 """
312
313 class AwardForm(forms.ModelForm):
314 class Meta:
315 model = Award
316 fields = "__all__"
317
318 def __init__(self, *args, **kwargs):
319 super().__init__(*args, **kwargs)
320 self.fields["character"].required = False
321
322 character = Character.objects.create(
323 username="user", last_action=datetime.datetime.today()
324 )
325 award = Award.objects.create(name="Best sprinter", character=character)
326 data = {"name": "Best tester", "character": ""} # remove character
327 form = AwardForm(data=data, instance=award)
328 self.assertTrue(form.is_valid())
329 award = form.save()
330 self.assertIsNone(award.character)
331
332 def test_blank_foreign_key_with_radio(self):
333 class BookForm(forms.ModelForm):
334 class Meta:
335 model = Book
336 fields = ["author"]
337 widgets = {"author": forms.RadioSelect()}
338
339 writer = Writer.objects.create(name="Joe Doe")
340 form = BookForm()
341 self.assertEqual(
342 list(form.fields["author"].choices),
343 [
344 ("", "---------"),
345 (writer.pk, "Joe Doe"),
346 ],
347 )
348
349 def test_non_blank_foreign_key_with_radio(self):
350 class AwardForm(forms.ModelForm):
351 class Meta:
352 model = Award
353 fields = ["character"]
354 widgets = {"character": forms.RadioSelect()}
355
356 character = Character.objects.create(
357 username="user",
358 last_action=datetime.datetime.today(),
359 )
360 form = AwardForm()
361 self.assertEqual(
362 list(form.fields["character"].choices),
363 [(character.pk, "user")],
364 )
365
366 def test_save_blank_false_with_required_false(self):
367 """
368 A ModelForm with a model with a field set to blank=False and the form
369 field set to required=False should allow the field to be unset.
370 """
371 obj = Writer.objects.create(name="test")
372 form = CustomWriterForm(data={"name": ""}, instance=obj)
373 self.assertTrue(form.is_valid())
374 obj = form.save()
375 self.assertEqual(obj.name, "")
376
377 @ignore_warnings(category=RemovedInDjango60Warning)
378 def test_save_blank_null_unique_charfield_saves_null(self):
379 form_class = modelform_factory(
380 model=NullableUniqueCharFieldModel, fields="__all__"
381 )
382 empty_value = (
383 "" if connection.features.interprets_empty_strings_as_nulls else None
384 )
385 data = {
386 "codename": "",
387 "email": "",
388 "slug": "",
389 "url": "",
390 }
391 form = form_class(data=data)
392 self.assertTrue(form.is_valid())
393 form.save()
394 self.assertEqual(form.instance.codename, empty_value)
395 self.assertEqual(form.instance.email, empty_value)
396 self.assertEqual(form.instance.slug, empty_value)
397 self.assertEqual(form.instance.url, empty_value)
398
399 # Save a second form to verify there isn't a unique constraint violation.
400 form = form_class(data=data)
401 self.assertTrue(form.is_valid())
402 form.save()
403 self.assertEqual(form.instance.codename, empty_value)
404 self.assertEqual(form.instance.email, empty_value)
405 self.assertEqual(form.instance.slug, empty_value)
406 self.assertEqual(form.instance.url, empty_value)
407
408 def test_missing_fields_attribute(self):
409 message = (
410 "Creating a ModelForm without either the 'fields' attribute "
411 "or the 'exclude' attribute is prohibited; form "
412 "MissingFieldsForm needs updating."
413 )
414 with self.assertRaisesMessage(ImproperlyConfigured, message):
415
416 class MissingFieldsForm(forms.ModelForm):
417 class Meta:
418 model = Category
419
420 def test_extra_fields(self):
421 class ExtraFields(BaseCategoryForm):
422 some_extra_field = forms.BooleanField()
423
424 self.assertEqual(
425 list(ExtraFields.base_fields), ["name", "slug", "url", "some_extra_field"]
426 )
427
428 def test_extra_field_model_form(self):
429 with self.assertRaisesMessage(FieldError, "no-field"):
430
431 class ExtraPersonForm(forms.ModelForm):
432 """ModelForm with an extra field"""
433
434 age = forms.IntegerField()
435
436 class Meta:
437 model = Person
438 fields = ("name", "no-field")
439
440 def test_extra_declared_field_model_form(self):
441 class ExtraPersonForm(forms.ModelForm):
442 """ModelForm with an extra field"""
443
444 age = forms.IntegerField()
445
446 class Meta:
447 model = Person
448 fields = ("name", "age")
449
450 def test_extra_field_modelform_factory(self):
451 with self.assertRaisesMessage(
452 FieldError, "Unknown field(s) (no-field) specified for Person"
453 ):
454 modelform_factory(Person, fields=["no-field", "name"])
455
456 def test_replace_field(self):
457 class ReplaceField(forms.ModelForm):
458 url = forms.BooleanField()
459
460 class Meta:
461 model = Category
462 fields = "__all__"
463
464 self.assertIsInstance(
465 ReplaceField.base_fields["url"], forms.fields.BooleanField
466 )
467
468 def test_replace_field_variant_2(self):
469 # Should have the same result as before,
470 # but 'fields' attribute specified differently
471 class ReplaceField(forms.ModelForm):
472 url = forms.BooleanField()
473
474 class Meta:
475 model = Category
476 fields = ["url"]
477
478 self.assertIsInstance(
479 ReplaceField.base_fields["url"], forms.fields.BooleanField
480 )
481
482 def test_replace_field_variant_3(self):
483 # Should have the same result as before,
484 # but 'fields' attribute specified differently
485 class ReplaceField(forms.ModelForm):
486 url = forms.BooleanField()
487
488 class Meta:
489 model = Category
490 fields = [] # url will still appear, since it is explicit above
491
492 self.assertIsInstance(
493 ReplaceField.base_fields["url"], forms.fields.BooleanField
494 )
495
496 def test_override_field(self):
497 class WriterForm(forms.ModelForm):
498 book = forms.CharField(required=False)
499
500 class Meta:
501 model = Writer
502 fields = "__all__"
503
504 wf = WriterForm({"name": "Richard Lockridge"})
505 self.assertTrue(wf.is_valid())
506
507 def test_limit_nonexistent_field(self):
508 expected_msg = "Unknown field(s) (nonexistent) specified for Category"
509 with self.assertRaisesMessage(FieldError, expected_msg):
510
511 class InvalidCategoryForm(forms.ModelForm):
512 class Meta:
513 model = Category
514 fields = ["nonexistent"]
515
516 def test_limit_fields_with_string(self):
517 msg = (
518 "CategoryForm.Meta.fields cannot be a string. Did you mean to type: "
519 "('url',)?"
520 )
521 with self.assertRaisesMessage(TypeError, msg):
522
523 class CategoryForm(forms.ModelForm):
524 class Meta:
525 model = Category
526 fields = "url" # note the missing comma
527
528 def test_exclude_fields(self):
529 class ExcludeFields(forms.ModelForm):
530 class Meta:
531 model = Category
532 exclude = ["url"]
533
534 self.assertEqual(list(ExcludeFields.base_fields), ["name", "slug"])
535
536 def test_exclude_nonexistent_field(self):
537 class ExcludeFields(forms.ModelForm):
538 class Meta:
539 model = Category
540 exclude = ["nonexistent"]
541
542 self.assertEqual(list(ExcludeFields.base_fields), ["name", "slug", "url"])
543
544 def test_exclude_fields_with_string(self):
545 msg = (
546 "CategoryForm.Meta.exclude cannot be a string. Did you mean to type: "
547 "('url',)?"
548 )
549 with self.assertRaisesMessage(TypeError, msg):
550
551 class CategoryForm(forms.ModelForm):
552 class Meta:
553 model = Category
554 exclude = "url" # note the missing comma
555
556 def test_exclude_and_validation(self):
557 # This Price instance generated by this form is not valid because the quantity
558 # field is required, but the form is valid because the field is excluded from
559 # the form. This is for backwards compatibility.
560 class PriceFormWithoutQuantity(forms.ModelForm):
561 class Meta:
562 model = Price
563 exclude = ("quantity",)
564
565 form = PriceFormWithoutQuantity({"price": "6.00"})
566 self.assertTrue(form.is_valid())
567 price = form.save(commit=False)
568 msg = "{'quantity': ['This field cannot be null.']}"
569 with self.assertRaisesMessage(ValidationError, msg):
570 price.full_clean()
571
572 # The form should not validate fields that it doesn't contain even if they are
573 # specified using 'fields', not 'exclude'.
574 class PriceFormWithoutQuantity(forms.ModelForm):
575 class Meta:
576 model = Price
577 fields = ("price",)
578
579 form = PriceFormWithoutQuantity({"price": "6.00"})
580 self.assertTrue(form.is_valid())
581
582 # The form should still have an instance of a model that is not complete and
583 # not saved into a DB yet.
584 self.assertEqual(form.instance.price, Decimal("6.00"))
585 self.assertIsNone(form.instance.quantity)
586 self.assertIsNone(form.instance.pk)
587
588 def test_confused_form(self):
589 class ConfusedForm(forms.ModelForm):
590 """Using 'fields' *and* 'exclude'. Not sure why you'd want to do
591 this, but uh, "be liberal in what you accept" and all.
592 """
593
594 class Meta:
595 model = Category
596 fields = ["name", "url"]
597 exclude = ["url"]
598
599 self.assertEqual(list(ConfusedForm.base_fields), ["name"])
600
601 def test_mixmodel_form(self):
602 class MixModelForm(BaseCategoryForm):
603 """Don't allow more than one 'model' definition in the
604 inheritance hierarchy. Technically, it would generate a valid
605 form, but the fact that the resulting save method won't deal with
606 multiple objects is likely to trip up people not familiar with the
607 mechanics.
608 """
609
610 class Meta:
611 model = Article
612 fields = "__all__"
613
614 # MixModelForm is now an Article-related thing, because MixModelForm.Meta
615 # overrides BaseCategoryForm.Meta.
616
617 self.assertEqual(
618 list(MixModelForm.base_fields),
619 [
620 "headline",
621 "slug",
622 "pub_date",
623 "writer",
624 "article",
625 "categories",
626 "status",
627 ],
628 )
629
630 def test_article_form(self):
631 self.assertEqual(
632 list(ArticleForm.base_fields),
633 [
634 "headline",
635 "slug",
636 "pub_date",
637 "writer",
638 "article",
639 "categories",
640 "status",
641 ],
642 )
643
644 def test_bad_form(self):
645 # First class with a Meta class wins...
646 class BadForm(ArticleForm, BaseCategoryForm):
647 pass
648
649 self.assertEqual(
650 list(BadForm.base_fields),
651 [
652 "headline",
653 "slug",
654 "pub_date",
655 "writer",
656 "article",
657 "categories",
658 "status",
659 ],
660 )
661
662 def test_invalid_meta_model(self):
663 class InvalidModelForm(forms.ModelForm):
664 class Meta:
665 pass # no model
666
667 # Can't create new form
668 msg = "ModelForm has no model class specified."
669 with self.assertRaisesMessage(ValueError, msg):
670 InvalidModelForm()
671
672 # Even if you provide a model instance
673 with self.assertRaisesMessage(ValueError, msg):
674 InvalidModelForm(instance=Category)
675
676 def test_subcategory_form(self):
677 class SubCategoryForm(BaseCategoryForm):
678 """Subclassing without specifying a Meta on the class will use
679 the parent's Meta (or the first parent in the MRO if there are
680 multiple parent classes).
681 """
682
683 pass
684
685 self.assertEqual(list(SubCategoryForm.base_fields), ["name", "slug", "url"])
686
687 def test_subclassmeta_form(self):
688 class SomeCategoryForm(forms.ModelForm):
689 checkbox = forms.BooleanField()
690
691 class Meta:
692 model = Category
693 fields = "__all__"
694
695 class SubclassMeta(SomeCategoryForm):
696 """We can also subclass the Meta inner class to change the fields
697 list.
698 """
699
700 class Meta(SomeCategoryForm.Meta):
701 exclude = ["url"]
702
703 self.assertHTMLEqual(
704 str(SubclassMeta()),
705 '<div><label for="id_name">Name:</label>'
706 '<input type="text" name="name" maxlength="20" required id="id_name">'
707 '</div><div><label for="id_slug">Slug:</label><input type="text" '
708 'name="slug" maxlength="20" required id="id_slug"></div><div>'
709 '<label for="id_checkbox">Checkbox:</label>'
710 '<input type="checkbox" name="checkbox" required id="id_checkbox"></div>',
711 )
712
713 def test_orderfields_form(self):
714 class OrderFields(forms.ModelForm):
715 class Meta:
716 model = Category
717 fields = ["url", "name"]
718
719 self.assertEqual(list(OrderFields.base_fields), ["url", "name"])
720 self.assertHTMLEqual(
721 str(OrderFields()),
722 '<div><label for="id_url">The URL:</label>'
723 '<input type="text" name="url" maxlength="40" required id="id_url">'
724 '</div><div><label for="id_name">Name:</label><input type="text" '
725 'name="name" maxlength="20" required id="id_name"></div>',
726 )
727
728 def test_orderfields2_form(self):
729 class OrderFields2(forms.ModelForm):
730 class Meta:
731 model = Category
732 fields = ["slug", "url", "name"]
733 exclude = ["url"]
734
735 self.assertEqual(list(OrderFields2.base_fields), ["slug", "name"])
736
737 def test_default_populated_on_optional_field(self):
738 class PubForm(forms.ModelForm):
739 mode = forms.CharField(max_length=255, required=False)
740
741 class Meta:
742 model = PublicationDefaults
743 fields = ("mode",)
744
745 # Empty data uses the model field default.
746 mf1 = PubForm({})
747 self.assertEqual(mf1.errors, {})
748 m1 = mf1.save(commit=False)
749 self.assertEqual(m1.mode, "di")
750 self.assertEqual(m1._meta.get_field("mode").get_default(), "di")
751
752 # Blank data doesn't use the model field default.
753 mf2 = PubForm({"mode": ""})
754 self.assertEqual(mf2.errors, {})
755 m2 = mf2.save(commit=False)
756 self.assertEqual(m2.mode, "")
757
758 def test_default_not_populated_on_non_empty_value_in_cleaned_data(self):
759 class PubForm(forms.ModelForm):
760 mode = forms.CharField(max_length=255, required=False)
761 mocked_mode = None
762
763 def clean(self):
764 self.cleaned_data["mode"] = self.mocked_mode
765 return self.cleaned_data
766
767 class Meta:
768 model = PublicationDefaults
769 fields = ("mode",)
770
771 pub_form = PubForm({})
772 pub_form.mocked_mode = "de"
773 pub = pub_form.save(commit=False)
774 self.assertEqual(pub.mode, "de")
775 # Default should be populated on an empty value in cleaned_data.
776 default_mode = "di"
777 for empty_value in pub_form.fields["mode"].empty_values:
778 with self.subTest(empty_value=empty_value):
779 pub_form = PubForm({})
780 pub_form.mocked_mode = empty_value
781 pub = pub_form.save(commit=False)
782 self.assertEqual(pub.mode, default_mode)
783
784 def test_default_not_populated_on_optional_checkbox_input(self):
785 class PubForm(forms.ModelForm):
786 class Meta:
787 model = PublicationDefaults
788 fields = ("active",)
789
790 # Empty data doesn't use the model default because CheckboxInput
791 # doesn't have a value in HTML form submission.
792 mf1 = PubForm({})
793 self.assertEqual(mf1.errors, {})
794 m1 = mf1.save(commit=False)
795 self.assertIs(m1.active, False)
796 self.assertIsInstance(mf1.fields["active"].widget, forms.CheckboxInput)
797 self.assertIs(m1._meta.get_field("active").get_default(), True)
798
799 def test_default_not_populated_on_checkboxselectmultiple(self):
800 class PubForm(forms.ModelForm):
801 mode = forms.CharField(required=False, widget=forms.CheckboxSelectMultiple)
802
803 class Meta:
804 model = PublicationDefaults
805 fields = ("mode",)
806
807 # Empty data doesn't use the model default because an unchecked
808 # CheckboxSelectMultiple doesn't have a value in HTML form submission.
809 mf1 = PubForm({})
810 self.assertEqual(mf1.errors, {})
811 m1 = mf1.save(commit=False)
812 self.assertEqual(m1.mode, "")
813 self.assertEqual(m1._meta.get_field("mode").get_default(), "di")
814
815 def test_default_not_populated_on_selectmultiple(self):
816 class PubForm(forms.ModelForm):
817 mode = forms.CharField(required=False, widget=forms.SelectMultiple)
818
819 class Meta:
820 model = PublicationDefaults
821 fields = ("mode",)
822
823 # Empty data doesn't use the model default because an unselected
824 # SelectMultiple doesn't have a value in HTML form submission.
825 mf1 = PubForm({})
826 self.assertEqual(mf1.errors, {})
827 m1 = mf1.save(commit=False)
828 self.assertEqual(m1.mode, "")
829 self.assertEqual(m1._meta.get_field("mode").get_default(), "di")
830
831 def test_prefixed_form_with_default_field(self):
832 class PubForm(forms.ModelForm):
833 prefix = "form-prefix"
834
835 class Meta:
836 model = PublicationDefaults
837 fields = ("mode",)
838
839 mode = "de"
840 self.assertNotEqual(
841 mode, PublicationDefaults._meta.get_field("mode").get_default()
842 )
843
844 mf1 = PubForm({"form-prefix-mode": mode})
845 self.assertEqual(mf1.errors, {})
846 m1 = mf1.save(commit=False)
847 self.assertEqual(m1.mode, mode)
848
849 def test_renderer_kwarg(self):
850 custom = object()
851 self.assertIs(ProductForm(renderer=custom).renderer, custom)
852
853 def test_default_splitdatetime_field(self):
854 class PubForm(forms.ModelForm):
855 datetime_published = forms.SplitDateTimeField(required=False)
856
857 class Meta:
858 model = PublicationDefaults
859 fields = ("datetime_published",)
860
861 mf1 = PubForm({})
862 self.assertEqual(mf1.errors, {})
863 m1 = mf1.save(commit=False)
864 self.assertEqual(m1.datetime_published, datetime.datetime(2000, 1, 1))
865
866 mf2 = PubForm(
867 {"datetime_published_0": "2010-01-01", "datetime_published_1": "0:00:00"}
868 )
869 self.assertEqual(mf2.errors, {})
870 m2 = mf2.save(commit=False)
871 self.assertEqual(m2.datetime_published, datetime.datetime(2010, 1, 1))
872
873 def test_default_filefield(self):
874 class PubForm(forms.ModelForm):
875 class Meta:
876 model = PublicationDefaults
877 fields = ("file",)
878
879 mf1 = PubForm({})
880 self.assertEqual(mf1.errors, {})
881 m1 = mf1.save(commit=False)
882 self.assertEqual(m1.file.name, "default.txt")
883
884 mf2 = PubForm({}, {"file": SimpleUploadedFile("name", b"foo")})
885 self.assertEqual(mf2.errors, {})
886 m2 = mf2.save(commit=False)
887 self.assertEqual(m2.file.name, "name")
888
889 def test_default_selectdatewidget(self):
890 class PubForm(forms.ModelForm):
891 date_published = forms.DateField(
892 required=False, widget=forms.SelectDateWidget
893 )
894
895 class Meta:
896 model = PublicationDefaults
897 fields = ("date_published",)
898
899 mf1 = PubForm({})
900 self.assertEqual(mf1.errors, {})
901 m1 = mf1.save(commit=False)
902 self.assertEqual(m1.date_published, datetime.date.today())
903
904 mf2 = PubForm(
905 {
906 "date_published_year": "2010",
907 "date_published_month": "1",
908 "date_published_day": "1",
909 }
910 )
911 self.assertEqual(mf2.errors, {})
912 m2 = mf2.save(commit=False)
913 self.assertEqual(m2.date_published, datetime.date(2010, 1, 1))
914
915
916 # RemovedInDjango60Warning.
917 # It's a temporary workaround for the deprecation period.
918 class HttpsURLField(forms.URLField):
919 def __init__(self, **kwargs):
920 super().__init__(assume_scheme="https", **kwargs)
921
922
923 class FieldOverridesByFormMetaForm(forms.ModelForm):
924 class Meta:
925 model = Category
926 fields = ["name", "url", "slug"]
927 widgets = {
928 "name": forms.Textarea,
929 "url": forms.TextInput(attrs={"class": "url"}),
930 }
931 labels = {
932 "name": "Title",
933 }
934 help_texts = {
935 "slug": "Watch out! Letters, numbers, underscores and hyphens only.",
936 }
937 error_messages = {
938 "slug": {
939 "invalid": (
940 "Didn't you read the help text? "
941 "We said letters, numbers, underscores and hyphens only!"
942 )
943 }
944 }
945 field_classes = {
946 "url": HttpsURLField,
947 }
948
949
950 class TestFieldOverridesByFormMeta(SimpleTestCase):
951 def test_widget_overrides(self):
952 form = FieldOverridesByFormMetaForm()
953 self.assertHTMLEqual(
954 str(form["name"]),
955 '<textarea id="id_name" rows="10" cols="40" name="name" maxlength="20" '
956 "required></textarea>",
957 )
958 self.assertHTMLEqual(
959 str(form["url"]),
960 '<input id="id_url" type="text" class="url" name="url" maxlength="40" '
961 "required>",
962 )
963 self.assertHTMLEqual(
964 str(form["slug"]),
965 '<input id="id_slug" type="text" name="slug" maxlength="20" '
966 'aria-describedby="id_slug_helptext" required>',
967 )
968
969 def test_label_overrides(self):
970 form = FieldOverridesByFormMetaForm()
971 self.assertHTMLEqual(
972 str(form["name"].label_tag()),
973 '<label for="id_name">Title:</label>',
974 )
975 self.assertHTMLEqual(
976 str(form["url"].label_tag()),
977 '<label for="id_url">The URL:</label>',
978 )
979 self.assertHTMLEqual(
980 str(form["slug"].label_tag()),
981 '<label for="id_slug">Slug:</label>',
982 )
983 self.assertHTMLEqual(
984 form["name"].legend_tag(),
985 '<legend for="id_name">Title:</legend>',
986 )
987 self.assertHTMLEqual(
988 form["url"].legend_tag(),
989 '<legend for="id_url">The URL:</legend>',
990 )
991 self.assertHTMLEqual(
992 form["slug"].legend_tag(),
993 '<legend for="id_slug">Slug:</legend>',
994 )
995
996 def test_help_text_overrides(self):
997 form = FieldOverridesByFormMetaForm()
998 self.assertEqual(
999 form["slug"].help_text,
1000 "Watch out! Letters, numbers, underscores and hyphens only.",
1001 )
1002
1003 def test_error_messages_overrides(self):
1004 form = FieldOverridesByFormMetaForm(
1005 data={
1006 "name": "Category",
1007 "url": "http://www.example.com/category/",
1008 "slug": "!%#*@",
1009 }
1010 )
1011 form.full_clean()
1012
1013 error = [
1014 "Didn't you read the help text? "
1015 "We said letters, numbers, underscores and hyphens only!",
1016 ]
1017 self.assertEqual(form.errors, {"slug": error})
1018
1019 def test_field_type_overrides(self):
1020 form = FieldOverridesByFormMetaForm()
1021 self.assertIs(Category._meta.get_field("url").__class__, models.CharField)
1022 self.assertIsInstance(form.fields["url"], forms.URLField)
1023
1024
1025 class IncompleteCategoryFormWithFields(forms.ModelForm):
1026 """
1027 A form that replaces the model's url field with a custom one. This should
1028 prevent the model field's validation from being called.
1029 """
1030
1031 url = forms.CharField(required=False)
1032
1033 class Meta:
1034 fields = ("name", "slug")
1035 model = Category
1036
1037
1038 class IncompleteCategoryFormWithExclude(forms.ModelForm):
1039 """
1040 A form that replaces the model's url field with a custom one. This should
1041 prevent the model field's validation from being called.
1042 """
1043
1044 url = forms.CharField(required=False)
1045
1046 class Meta:
1047 exclude = ["url"]
1048 model = Category
1049
1050
1051 class ValidationTest(SimpleTestCase):
1052 def test_validates_with_replaced_field_not_specified(self):
1053 form = IncompleteCategoryFormWithFields(
1054 data={"name": "some name", "slug": "some-slug"}
1055 )
1056 self.assertIs(form.is_valid(), True)
1057
1058 def test_validates_with_replaced_field_excluded(self):
1059 form = IncompleteCategoryFormWithExclude(
1060 data={"name": "some name", "slug": "some-slug"}
1061 )
1062 self.assertIs(form.is_valid(), True)
1063
1064 def test_notrequired_overrides_notblank(self):
1065 form = CustomWriterForm({})
1066 self.assertIs(form.is_valid(), True)
1067
1068
1069 class UniqueTest(TestCase):
1070 """
1071 unique/unique_together validation.
1072 """
1073
1074 @classmethod
1075 def setUpTestData(cls):
1076 cls.writer = Writer.objects.create(name="Mike Royko")
1077
1078 def test_simple_unique(self):
1079 form = ProductForm({"slug": "teddy-bear-blue"})
1080 self.assertTrue(form.is_valid())
1081 obj = form.save()
1082 form = ProductForm({"slug": "teddy-bear-blue"})
1083 self.assertEqual(len(form.errors), 1)
1084 self.assertEqual(
1085 form.errors["slug"], ["Product with this Slug already exists."]
1086 )
1087 form = ProductForm({"slug": "teddy-bear-blue"}, instance=obj)
1088 self.assertTrue(form.is_valid())
1089
1090 def test_unique_together(self):
1091 """ModelForm test of unique_together constraint"""
1092 form = PriceForm({"price": "6.00", "quantity": "1"})
1093 self.assertTrue(form.is_valid())
1094 form.save()
1095 form = PriceForm({"price": "6.00", "quantity": "1"})
1096 self.assertFalse(form.is_valid())
1097 self.assertEqual(len(form.errors), 1)
1098 self.assertEqual(
1099 form.errors["__all__"],
1100 ["Price with this Price and Quantity already exists."],
1101 )
1102
1103 def test_unique_together_exclusion(self):
1104 """
1105 Forms don't validate unique_together constraints when only part of the
1106 constraint is included in the form's fields. This allows using
1107 form.save(commit=False) and then assigning the missing field(s) to the
1108 model instance.
1109 """
1110
1111 class BookForm(forms.ModelForm):
1112 class Meta:
1113 model = DerivedBook
1114 fields = ("isbn", "suffix1")
1115
1116 # The unique_together is on suffix1/suffix2 but only suffix1 is part
1117 # of the form. The fields must have defaults, otherwise they'll be
1118 # skipped by other logic.
1119 self.assertEqual(DerivedBook._meta.unique_together, (("suffix1", "suffix2"),))
1120 for name in ("suffix1", "suffix2"):
1121 with self.subTest(name=name):
1122 field = DerivedBook._meta.get_field(name)
1123 self.assertEqual(field.default, 0)
1124
1125 # The form fails validation with "Derived book with this Suffix1 and
1126 # Suffix2 already exists." if the unique_together validation isn't
1127 # skipped.
1128 DerivedBook.objects.create(isbn="12345")
1129 form = BookForm({"isbn": "56789", "suffix1": "0"})
1130 self.assertTrue(form.is_valid(), form.errors)
1131
1132 def test_multiple_field_unique_together(self):
1133 """
1134 When the same field is involved in multiple unique_together
1135 constraints, we need to make sure we don't remove the data for it
1136 before doing all the validation checking (not just failing after
1137 the first one).
1138 """
1139
1140 class TripleForm(forms.ModelForm):
1141 class Meta:
1142 model = Triple
1143 fields = "__all__"
1144
1145 Triple.objects.create(left=1, middle=2, right=3)
1146
1147 form = TripleForm({"left": "1", "middle": "2", "right": "3"})
1148 self.assertFalse(form.is_valid())
1149
1150 form = TripleForm({"left": "1", "middle": "3", "right": "1"})
1151 self.assertTrue(form.is_valid())
1152
1153 @skipUnlessDBFeature("supports_nullable_unique_constraints")
1154 def test_unique_null(self):
1155 title = "I May Be Wrong But I Doubt It"
1156 form = BookForm({"title": title, "author": self.writer.pk})
1157 self.assertTrue(form.is_valid())
1158 form.save()
1159 form = BookForm({"title": title, "author": self.writer.pk})
1160 self.assertFalse(form.is_valid())
1161 self.assertEqual(len(form.errors), 1)
1162 self.assertEqual(
1163 form.errors["__all__"], ["Book with this Title and Author already exists."]
1164 )
1165 form = BookForm({"title": title})
1166 self.assertTrue(form.is_valid())
1167 form.save()
1168 form = BookForm({"title": title})
1169 self.assertTrue(form.is_valid())
1170
1171 def test_inherited_unique(self):
1172 title = "Boss"
1173 Book.objects.create(title=title, author=self.writer, special_id=1)
1174 form = DerivedBookForm(
1175 {
1176 "title": "Other",
1177 "author": self.writer.pk,
1178 "special_id": "1",
1179 "isbn": "12345",
1180 }
1181 )
1182 self.assertFalse(form.is_valid())
1183 self.assertEqual(len(form.errors), 1)
1184 self.assertEqual(
1185 form.errors["special_id"], ["Book with this Special id already exists."]
1186 )
1187
1188 def test_inherited_unique_together(self):
1189 title = "Boss"
1190 form = BookForm({"title": title, "author": self.writer.pk})
1191 self.assertTrue(form.is_valid())
1192 form.save()
1193 form = DerivedBookForm(
1194 {"title": title, "author": self.writer.pk, "isbn": "12345"}
1195 )
1196 self.assertFalse(form.is_valid())
1197 self.assertEqual(len(form.errors), 1)
1198 self.assertEqual(
1199 form.errors["__all__"], ["Book with this Title and Author already exists."]
1200 )
1201
1202 def test_abstract_inherited_unique(self):
1203 title = "Boss"
1204 isbn = "12345"
1205 DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn)
1206 form = DerivedBookForm(
1207 {
1208 "title": "Other",
1209 "author": self.writer.pk,
1210 "isbn": isbn,
1211 "suffix1": "1",
1212 "suffix2": "2",
1213 }
1214 )
1215 self.assertFalse(form.is_valid())
1216 self.assertEqual(len(form.errors), 1)
1217 self.assertEqual(
1218 form.errors["isbn"], ["Derived book with this Isbn already exists."]
1219 )
1220
1221 def test_abstract_inherited_unique_together(self):
1222 title = "Boss"
1223 isbn = "12345"
1224 DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn)
1225 form = DerivedBookForm(
1226 {
1227 "title": "Other",
1228 "author": self.writer.pk,
1229 "isbn": "9876",
1230 "suffix1": "0",
1231 "suffix2": "0",
1232 }
1233 )
1234 self.assertFalse(form.is_valid())
1235 self.assertEqual(len(form.errors), 1)
1236 self.assertEqual(
1237 form.errors["__all__"],
1238 ["Derived book with this Suffix1 and Suffix2 already exists."],
1239 )
1240
1241 def test_explicitpk_unspecified(self):
1242 """Test for primary_key being in the form and failing validation."""
1243 form = ExplicitPKForm({"key": "", "desc": ""})
1244 self.assertFalse(form.is_valid())
1245
1246 def test_explicitpk_unique(self):
1247 """Ensure keys and blank character strings are tested for uniqueness."""
1248 form = ExplicitPKForm({"key": "key1", "desc": ""})
1249 self.assertTrue(form.is_valid())
1250 form.save()
1251 form = ExplicitPKForm({"key": "key1", "desc": ""})
1252 self.assertFalse(form.is_valid())
1253 if connection.features.interprets_empty_strings_as_nulls:
1254 self.assertEqual(len(form.errors), 1)
1255 self.assertEqual(
1256 form.errors["key"], ["Explicit pk with this Key already exists."]
1257 )
1258 else:
1259 self.assertEqual(len(form.errors), 3)
1260 self.assertEqual(
1261 form.errors["__all__"],
1262 ["Explicit pk with this Key and Desc already exists."],
1263 )
1264 self.assertEqual(
1265 form.errors["desc"], ["Explicit pk with this Desc already exists."]
1266 )
1267 self.assertEqual(
1268 form.errors["key"], ["Explicit pk with this Key already exists."]
1269 )
1270
1271 def test_unique_for_date(self):
1272 p = Post.objects.create(
1273 title="Django 1.0 is released",
1274 slug="Django 1.0",
1275 subtitle="Finally",
1276 posted=datetime.date(2008, 9, 3),
1277 )
1278 form = PostForm({"title": "Django 1.0 is released", "posted": "2008-09-03"})
1279 self.assertFalse(form.is_valid())
1280 self.assertEqual(len(form.errors), 1)
1281 self.assertEqual(
1282 form.errors["title"], ["Title must be unique for Posted date."]
1283 )
1284 form = PostForm({"title": "Work on Django 1.1 begins", "posted": "2008-09-03"})
1285 self.assertTrue(form.is_valid())
1286 form = PostForm({"title": "Django 1.0 is released", "posted": "2008-09-04"})
1287 self.assertTrue(form.is_valid())
1288 form = PostForm({"slug": "Django 1.0", "posted": "2008-01-01"})
1289 self.assertFalse(form.is_valid())
1290 self.assertEqual(len(form.errors), 1)
1291 self.assertEqual(form.errors["slug"], ["Slug must be unique for Posted year."])
1292 form = PostForm({"subtitle": "Finally", "posted": "2008-09-30"})
1293 self.assertFalse(form.is_valid())
1294 self.assertEqual(
1295 form.errors["subtitle"], ["Subtitle must be unique for Posted month."]
1296 )
1297 data = {
1298 "subtitle": "Finally",
1299 "title": "Django 1.0 is released",
1300 "slug": "Django 1.0",
1301 "posted": "2008-09-03",
1302 }
1303 form = PostForm(data, instance=p)
1304 self.assertTrue(form.is_valid())
1305 form = PostForm({"title": "Django 1.0 is released"})
1306 self.assertFalse(form.is_valid())
1307 self.assertEqual(len(form.errors), 1)
1308 self.assertEqual(form.errors["posted"], ["This field is required."])
1309
1310 def test_unique_for_date_in_exclude(self):
1311 """
1312 If the date for unique_for_* constraints is excluded from the
1313 ModelForm (in this case 'posted' has editable=False, then the
1314 constraint should be ignored.
1315 """
1316
1317 class DateTimePostForm(forms.ModelForm):
1318 class Meta:
1319 model = DateTimePost
1320 fields = "__all__"
1321
1322 DateTimePost.objects.create(
1323 title="Django 1.0 is released",
1324 slug="Django 1.0",
1325 subtitle="Finally",
1326 posted=datetime.datetime(2008, 9, 3, 10, 10, 1),
1327 )
1328 # 'title' has unique_for_date='posted'
1329 form = DateTimePostForm(
1330 {"title": "Django 1.0 is released", "posted": "2008-09-03"}
1331 )
1332 self.assertTrue(form.is_valid())
1333 # 'slug' has unique_for_year='posted'
1334 form = DateTimePostForm({"slug": "Django 1.0", "posted": "2008-01-01"})
1335 self.assertTrue(form.is_valid())
1336 # 'subtitle' has unique_for_month='posted'
1337 form = DateTimePostForm({"subtitle": "Finally", "posted": "2008-09-30"})
1338 self.assertTrue(form.is_valid())
1339
1340 def test_inherited_unique_for_date(self):
1341 p = Post.objects.create(
1342 title="Django 1.0 is released",
1343 slug="Django 1.0",
1344 subtitle="Finally",
1345 posted=datetime.date(2008, 9, 3),
1346 )
1347 form = DerivedPostForm(
1348 {"title": "Django 1.0 is released", "posted": "2008-09-03"}
1349 )
1350 self.assertFalse(form.is_valid())
1351 self.assertEqual(len(form.errors), 1)
1352 self.assertEqual(
1353 form.errors["title"], ["Title must be unique for Posted date."]
1354 )
1355 form = DerivedPostForm(
1356 {"title": "Work on Django 1.1 begins", "posted": "2008-09-03"}
1357 )
1358 self.assertTrue(form.is_valid())
1359 form = DerivedPostForm(
1360 {"title": "Django 1.0 is released", "posted": "2008-09-04"}
1361 )
1362 self.assertTrue(form.is_valid())
1363 form = DerivedPostForm({"slug": "Django 1.0", "posted": "2008-01-01"})
1364 self.assertFalse(form.is_valid())
1365 self.assertEqual(len(form.errors), 1)
1366 self.assertEqual(form.errors["slug"], ["Slug must be unique for Posted year."])
1367 form = DerivedPostForm({"subtitle": "Finally", "posted": "2008-09-30"})
1368 self.assertFalse(form.is_valid())
1369 self.assertEqual(
1370 form.errors["subtitle"], ["Subtitle must be unique for Posted month."]
1371 )
1372 data = {
1373 "subtitle": "Finally",
1374 "title": "Django 1.0 is released",
1375 "slug": "Django 1.0",
1376 "posted": "2008-09-03",
1377 }
1378 form = DerivedPostForm(data, instance=p)
1379 self.assertTrue(form.is_valid())
1380
1381 def test_unique_for_date_with_nullable_date(self):
1382 class FlexDatePostForm(forms.ModelForm):
1383 class Meta:
1384 model = FlexibleDatePost
1385 fields = "__all__"
1386
1387 p = FlexibleDatePost.objects.create(
1388 title="Django 1.0 is released",
1389 slug="Django 1.0",
1390 subtitle="Finally",
1391 posted=datetime.date(2008, 9, 3),
1392 )
1393
1394 form = FlexDatePostForm({"title": "Django 1.0 is released"})
1395 self.assertTrue(form.is_valid())
1396 form = FlexDatePostForm({"slug": "Django 1.0"})
1397 self.assertTrue(form.is_valid())
1398 form = FlexDatePostForm({"subtitle": "Finally"})
1399 self.assertTrue(form.is_valid())
1400 data = {
1401 "subtitle": "Finally",
1402 "title": "Django 1.0 is released",
1403 "slug": "Django 1.0",
1404 }
1405 form = FlexDatePostForm(data, instance=p)
1406 self.assertTrue(form.is_valid())
1407
1408 def test_override_unique_message(self):
1409 class CustomProductForm(ProductForm):
1410 class Meta(ProductForm.Meta):
1411 error_messages = {
1412 "slug": {
1413 "unique": "%(model_name)s's %(field_label)s not unique.",
1414 }
1415 }
1416
1417 Product.objects.create(slug="teddy-bear-blue")
1418 form = CustomProductForm({"slug": "teddy-bear-blue"})
1419 self.assertEqual(len(form.errors), 1)
1420 self.assertEqual(form.errors["slug"], ["Product's Slug not unique."])
1421
1422 def test_override_unique_together_message(self):
1423 class CustomPriceForm(PriceForm):
1424 class Meta(PriceForm.Meta):
1425 error_messages = {
1426 NON_FIELD_ERRORS: {
1427 "unique_together": (
1428 "%(model_name)s's %(field_labels)s not unique."
1429 ),
1430 }
1431 }
1432
1433 Price.objects.create(price=6.00, quantity=1)
1434 form = CustomPriceForm({"price": "6.00", "quantity": "1"})
1435 self.assertEqual(len(form.errors), 1)
1436 self.assertEqual(
1437 form.errors[NON_FIELD_ERRORS], ["Price's Price and Quantity not unique."]
1438 )
1439
1440 def test_override_unique_for_date_message(self):
1441 class CustomPostForm(PostForm):
1442 class Meta(PostForm.Meta):
1443 error_messages = {
1444 "title": {
1445 "unique_for_date": (
1446 "%(model_name)s's %(field_label)s not unique "
1447 "for %(date_field_label)s date."
1448 ),
1449 }
1450 }
1451
1452 Post.objects.create(
1453 title="Django 1.0 is released",
1454 slug="Django 1.0",
1455 subtitle="Finally",
1456 posted=datetime.date(2008, 9, 3),
1457 )
1458 form = CustomPostForm(
1459 {"title": "Django 1.0 is released", "posted": "2008-09-03"}
1460 )
1461 self.assertEqual(len(form.errors), 1)
1462 self.assertEqual(
1463 form.errors["title"], ["Post's Title not unique for Posted date."]
1464 )
1465
1466
1467 class ModelFormBasicTests(TestCase):
1468 def create_basic_data(self):
1469 self.c1 = Category.objects.create(
1470 name="Entertainment", slug="entertainment", url="entertainment"
1471 )
1472 self.c2 = Category.objects.create(
1473 name="It's a test", slug="its-test", url="test"
1474 )
1475 self.c3 = Category.objects.create(
1476 name="Third test", slug="third-test", url="third"
1477 )
1478 self.w_royko = Writer.objects.create(name="Mike Royko")
1479 self.w_woodward = Writer.objects.create(name="Bob Woodward")
1480
1481 def test_base_form(self):
1482 self.assertEqual(Category.objects.count(), 0)
1483 f = BaseCategoryForm()
1484 self.assertHTMLEqual(
1485 str(f),
1486 '<div><label for="id_name">Name:</label><input type="text" name="name" '
1487 'maxlength="20" required id="id_name"></div><div><label for="id_slug">Slug:'
1488 '</label><input type="text" name="slug" maxlength="20" required '
1489 'id="id_slug"></div><div><label for="id_url">The URL:</label>'
1490 '<input type="text" name="url" maxlength="40" required id="id_url"></div>',
1491 )
1492 self.assertHTMLEqual(
1493 str(f.as_ul()),
1494 """
1495 <li><label for="id_name">Name:</label>
1496 <input id="id_name" type="text" name="name" maxlength="20" required></li>
1497 <li><label for="id_slug">Slug:</label>
1498 <input id="id_slug" type="text" name="slug" maxlength="20" required></li>
1499 <li><label for="id_url">The URL:</label>
1500 <input id="id_url" type="text" name="url" maxlength="40" required></li>
1501 """,
1502 )
1503 self.assertHTMLEqual(
1504 str(f["name"]),
1505 """<input id="id_name" type="text" name="name" maxlength="20" required>""",
1506 )
1507
1508 def test_auto_id(self):
1509 f = BaseCategoryForm(auto_id=False)
1510 self.assertHTMLEqual(
1511 str(f.as_ul()),
1512 """<li>Name: <input type="text" name="name" maxlength="20" required></li>
1513 <li>Slug: <input type="text" name="slug" maxlength="20" required></li>
1514 <li>The URL: <input type="text" name="url" maxlength="40" required></li>""",
1515 )
1516
1517 def test_initial_values(self):
1518 self.create_basic_data()
1519 # Initial values can be provided for model forms
1520 f = ArticleForm(
1521 auto_id=False,
1522 initial={
1523 "headline": "Your headline here",
1524 "categories": [str(self.c1.id), str(self.c2.id)],
1525 },
1526 )
1527 self.assertHTMLEqual(
1528 f.as_ul(),
1529 """
1530 <li>Headline:
1531 <input type="text" name="headline" value="Your headline here" maxlength="50"
1532 required>
1533 </li>
1534 <li>Slug: <input type="text" name="slug" maxlength="50" required></li>
1535 <li>Pub date: <input type="text" name="pub_date" required></li>
1536 <li>Writer: <select name="writer" required>
1537 <option value="" selected>---------</option>
1538 <option value="%s">Bob Woodward</option>
1539 <option value="%s">Mike Royko</option>
1540 </select></li>
1541 <li>Article:
1542 <textarea rows="10" cols="40" name="article" required></textarea></li>
1543 <li>Categories: <select multiple name="categories">
1544 <option value="%s" selected>Entertainment</option>
1545 <option value="%s" selected>It&#x27;s a test</option>
1546 <option value="%s">Third test</option>
1547 </select></li>
1548 <li>Status: <select name="status">
1549 <option value="" selected>---------</option>
1550 <option value="1">Draft</option>
1551 <option value="2">Pending</option>
1552 <option value="3">Live</option>
1553 </select></li>
1554 """
1555 % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
1556 )
1557
1558 # When the ModelForm is passed an instance, that instance's current values are
1559 # inserted as 'initial' data in each Field.
1560 f = RoykoForm(auto_id=False, instance=self.w_royko)
1561 self.assertHTMLEqual(
1562 str(f),
1563 '<div>Name:<div class="helptext">Use both first and last names.</div>'
1564 '<input type="text" name="name" value="Mike Royko" maxlength="50" '
1565 "required></div>",
1566 )
1567
1568 art = Article.objects.create(
1569 headline="Test article",
1570 slug="test-article",
1571 pub_date=datetime.date(1988, 1, 4),
1572 writer=self.w_royko,
1573 article="Hello.",
1574 )
1575 art_id_1 = art.id
1576
1577 f = ArticleForm(auto_id=False, instance=art)
1578 self.assertHTMLEqual(
1579 f.as_ul(),
1580 """
1581 <li>Headline:
1582 <input type="text" name="headline" value="Test article" maxlength="50"
1583 required>
1584 </li>
1585 <li>Slug:
1586 <input type="text" name="slug" value="test-article" maxlength="50" required>
1587 </li>
1588 <li>Pub date:
1589 <input type="text" name="pub_date" value="1988-01-04" required></li>
1590 <li>Writer: <select name="writer" required>
1591 <option value="">---------</option>
1592 <option value="%s">Bob Woodward</option>
1593 <option value="%s" selected>Mike Royko</option>
1594 </select></li>
1595 <li>Article:
1596 <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li>
1597 <li>Categories: <select multiple name="categories">
1598 <option value="%s">Entertainment</option>
1599 <option value="%s">It&#x27;s a test</option>
1600 <option value="%s">Third test</option>
1601 </select></li>
1602 <li>Status: <select name="status">
1603 <option value="" selected>---------</option>
1604 <option value="1">Draft</option>
1605 <option value="2">Pending</option>
1606 <option value="3">Live</option>
1607 </select></li>
1608 """
1609 % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
1610 )
1611
1612 f = ArticleForm(
1613 {
1614 "headline": "Test headline",
1615 "slug": "test-headline",
1616 "pub_date": "1984-02-06",
1617 "writer": str(self.w_royko.pk),
1618 "article": "Hello.",
1619 },
1620 instance=art,
1621 )
1622 self.assertEqual(f.errors, {})
1623 self.assertTrue(f.is_valid())
1624 test_art = f.save()
1625 self.assertEqual(test_art.id, art_id_1)
1626 test_art = Article.objects.get(id=art_id_1)
1627 self.assertEqual(test_art.headline, "Test headline")
1628
1629 def test_m2m_initial_callable(self):
1630 """
1631 A callable can be provided as the initial value for an m2m field.
1632 """
1633 self.maxDiff = 1200
1634 self.create_basic_data()
1635
1636 # Set up a callable initial value
1637 def formfield_for_dbfield(db_field, **kwargs):
1638 if db_field.name == "categories":
1639 kwargs["initial"] = lambda: Category.objects.order_by("name")[:2]
1640 return db_field.formfield(**kwargs)
1641
1642 # Create a ModelForm, instantiate it, and check that the output is as expected
1643 ModelForm = modelform_factory(
1644 Article,
1645 fields=["headline", "categories"],
1646 formfield_callback=formfield_for_dbfield,
1647 )
1648 form = ModelForm()
1649 self.assertHTMLEqual(
1650 form.as_ul(),
1651 """<li><label for="id_headline">Headline:</label>
1652 <input id="id_headline" type="text" name="headline" maxlength="50" required></li>
1653 <li><label for="id_categories">Categories:</label>
1654 <select multiple name="categories" id="id_categories">
1655 <option value="%d" selected>Entertainment</option>
1656 <option value="%d" selected>It&#x27;s a test</option>
1657 <option value="%d">Third test</option>
1658 </select></li>""" % (self.c1.pk, self.c2.pk, self.c3.pk),
1659 )
1660
1661 def test_basic_creation(self):
1662 self.assertEqual(Category.objects.count(), 0)
1663 f = BaseCategoryForm(
1664 {
1665 "name": "Entertainment",
1666 "slug": "entertainment",
1667 "url": "entertainment",
1668 }
1669 )
1670 self.assertTrue(f.is_valid())
1671 self.assertEqual(f.cleaned_data["name"], "Entertainment")
1672 self.assertEqual(f.cleaned_data["slug"], "entertainment")
1673 self.assertEqual(f.cleaned_data["url"], "entertainment")
1674 c1 = f.save()
1675 # Testing whether the same object is returned from the
1676 # ORM... not the fastest way...
1677
1678 self.assertEqual(Category.objects.count(), 1)
1679 self.assertEqual(c1, Category.objects.all()[0])
1680 self.assertEqual(c1.name, "Entertainment")
1681
1682 def test_save_commit_false(self):
1683 # If you call save() with commit=False, then it will return an object that
1684 # hasn't yet been saved to the database. In this case, it's up to you to call
1685 # save() on the resulting model instance.
1686 f = BaseCategoryForm(
1687 {"name": "Third test", "slug": "third-test", "url": "third"}
1688 )
1689 self.assertTrue(f.is_valid())
1690 c1 = f.save(commit=False)
1691 self.assertEqual(c1.name, "Third test")
1692 self.assertEqual(Category.objects.count(), 0)
1693 c1.save()
1694 self.assertEqual(Category.objects.count(), 1)
1695
1696 def test_save_with_data_errors(self):
1697 # If you call save() with invalid data, you'll get a ValueError.
1698 f = BaseCategoryForm({"name": "", "slug": "not a slug!", "url": "foo"})
1699 self.assertEqual(f.errors["name"], ["This field is required."])
1700 self.assertEqual(
1701 f.errors["slug"],
1702 [
1703 "Enter a valid “slug” consisting of letters, numbers, underscores or "
1704 "hyphens."
1705 ],
1706 )
1707 self.assertEqual(f.cleaned_data, {"url": "foo"})
1708 msg = "The Category could not be created because the data didn't validate."
1709 with self.assertRaisesMessage(ValueError, msg):
1710 f.save()
1711 f = BaseCategoryForm({"name": "", "slug": "", "url": "foo"})
1712 with self.assertRaisesMessage(ValueError, msg):
1713 f.save()
1714
1715 def test_multi_fields(self):
1716 self.create_basic_data()
1717 self.maxDiff = None
1718 # ManyToManyFields are represented by a MultipleChoiceField, ForeignKeys and any
1719 # fields with the 'choices' attribute are represented by a ChoiceField.
1720 f = ArticleForm(auto_id=False)
1721 self.assertHTMLEqual(
1722 str(f),
1723 """
1724 <div>Headline:
1725 <input type="text" name="headline" maxlength="50" required>
1726 </div>
1727 <div>Slug:
1728 <input type="text" name="slug" maxlength="50" required>
1729 </div>
1730 <div>Pub date:
1731 <input type="text" name="pub_date" required>
1732 </div>
1733 <div>Writer:
1734 <select name="writer" required>
1735 <option value="" selected>---------</option>
1736 <option value="%s">Bob Woodward</option>
1737 <option value="%s">Mike Royko</option>
1738 </select>
1739 </div>
1740 <div>Article:
1741 <textarea name="article" cols="40" rows="10" required></textarea>
1742 </div>
1743 <div>Categories:
1744 <select name="categories" multiple>
1745 <option value="%s">Entertainment</option>
1746 <option value="%s">It&#x27;s a test</option>
1747 <option value="%s">Third test</option>
1748 </select>
1749 </div>
1750 <div>Status:
1751 <select name="status">
1752 <option value="" selected>---------</option>
1753 <option value="1">Draft</option><option value="2">Pending</option>
1754 <option value="3">Live</option>
1755 </select>
1756 </div>
1757 """
1758 % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
1759 )
1760
1761 # Add some categories and test the many-to-many form output.
1762 new_art = Article.objects.create(
1763 article="Hello.",
1764 headline="New headline",
1765 slug="new-headline",
1766 pub_date=datetime.date(1988, 1, 4),
1767 writer=self.w_royko,
1768 )
1769 new_art.categories.add(Category.objects.get(name="Entertainment"))
1770 self.assertSequenceEqual(new_art.categories.all(), [self.c1])
1771 f = ArticleForm(auto_id=False, instance=new_art)
1772 self.assertHTMLEqual(
1773 f.as_ul(),
1774 """
1775 <li>Headline:
1776 <input type="text" name="headline" value="New headline" maxlength="50"
1777 required>
1778 </li>
1779 <li>Slug:
1780 <input type="text" name="slug" value="new-headline" maxlength="50" required>
1781 </li>
1782 <li>Pub date:
1783 <input type="text" name="pub_date" value="1988-01-04" required></li>
1784 <li>Writer: <select name="writer" required>
1785 <option value="">---------</option>
1786 <option value="%s">Bob Woodward</option>
1787 <option value="%s" selected>Mike Royko</option>
1788 </select></li>
1789 <li>Article:
1790 <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li>
1791 <li>Categories: <select multiple name="categories">
1792 <option value="%s" selected>Entertainment</option>
1793 <option value="%s">It&#x27;s a test</option>
1794 <option value="%s">Third test</option>
1795 </select></li>
1796 <li>Status: <select name="status">
1797 <option value="" selected>---------</option>
1798 <option value="1">Draft</option>
1799 <option value="2">Pending</option>
1800 <option value="3">Live</option>
1801 </select></li>
1802 """
1803 % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
1804 )
1805
1806 def test_subset_fields(self):
1807 # You can restrict a form to a subset of the complete list of fields
1808 # by providing a 'fields' argument. If you try to save a
1809 # model created with such a form, you need to ensure that the fields
1810 # that are _not_ on the form have default values, or are allowed to have
1811 # a value of None. If a field isn't specified on a form, the object created
1812 # from the form can't provide a value for that field!
1813 class PartialArticleForm(forms.ModelForm):
1814 class Meta:
1815 model = Article
1816 fields = ("headline", "pub_date")
1817
1818 f = PartialArticleForm(auto_id=False)
1819 self.assertHTMLEqual(
1820 str(f),
1821 '<div>Headline:<input type="text" name="headline" maxlength="50" required>'
1822 '</div><div>Pub date:<input type="text" name="pub_date" required></div>',
1823 )
1824
1825 class PartialArticleFormWithSlug(forms.ModelForm):
1826 class Meta:
1827 model = Article
1828 fields = ("headline", "slug", "pub_date")
1829
1830 w_royko = Writer.objects.create(name="Mike Royko")
1831 art = Article.objects.create(
1832 article="Hello.",
1833 headline="New headline",
1834 slug="new-headline",
1835 pub_date=datetime.date(1988, 1, 4),
1836 writer=w_royko,
1837 )
1838 f = PartialArticleFormWithSlug(
1839 {
1840 "headline": "New headline",
1841 "slug": "new-headline",
1842 "pub_date": "1988-01-04",
1843 },
1844 auto_id=False,
1845 instance=art,
1846 )
1847 self.assertHTMLEqual(
1848 f.as_ul(),
1849 """
1850 <li>Headline:
1851 <input type="text" name="headline" value="New headline" maxlength="50"
1852 required>
1853 </li>
1854 <li>Slug:
1855 <input type="text" name="slug" value="new-headline" maxlength="50"
1856 required>
1857 </li>
1858 <li>Pub date:
1859 <input type="text" name="pub_date" value="1988-01-04" required></li>
1860 """,
1861 )
1862 self.assertTrue(f.is_valid())
1863 new_art = f.save()
1864 self.assertEqual(new_art.id, art.id)
1865 new_art = Article.objects.get(id=art.id)
1866 self.assertEqual(new_art.headline, "New headline")
1867
1868 def test_m2m_editing(self):
1869 self.create_basic_data()
1870 form_data = {
1871 "headline": "New headline",
1872 "slug": "new-headline",
1873 "pub_date": "1988-01-04",
1874 "writer": str(self.w_royko.pk),
1875 "article": "Hello.",
1876 "categories": [str(self.c1.id), str(self.c2.id)],
1877 }
1878 # Create a new article, with categories, via the form.
1879 f = ArticleForm(form_data)
1880 new_art = f.save()
1881 new_art = Article.objects.get(id=new_art.id)
1882 art_id_1 = new_art.id
1883 self.assertSequenceEqual(
1884 new_art.categories.order_by("name"), [self.c1, self.c2]
1885 )
1886
1887 # Now, submit form data with no categories. This deletes the existing
1888 # categories.
1889 form_data["categories"] = []
1890 f = ArticleForm(form_data, instance=new_art)
1891 new_art = f.save()
1892 self.assertEqual(new_art.id, art_id_1)
1893 new_art = Article.objects.get(id=art_id_1)
1894 self.assertSequenceEqual(new_art.categories.all(), [])
1895
1896 # Create a new article, with no categories, via the form.
1897 f = ArticleForm(form_data)
1898 new_art = f.save()
1899 art_id_2 = new_art.id
1900 self.assertNotIn(art_id_2, (None, art_id_1))
1901 new_art = Article.objects.get(id=art_id_2)
1902 self.assertSequenceEqual(new_art.categories.all(), [])
1903
1904 # Create a new article, with categories, via the form, but use commit=False.
1905 # The m2m data won't be saved until save_m2m() is invoked on the form.
1906 form_data["categories"] = [str(self.c1.id), str(self.c2.id)]
1907 f = ArticleForm(form_data)
1908 new_art = f.save(commit=False)
1909
1910 # Manually save the instance
1911 new_art.save()
1912 art_id_3 = new_art.id
1913 self.assertNotIn(art_id_3, (None, art_id_1, art_id_2))
1914
1915 # The instance doesn't have m2m data yet
1916 new_art = Article.objects.get(id=art_id_3)
1917 self.assertSequenceEqual(new_art.categories.all(), [])
1918
1919 # Save the m2m data on the form
1920 f.save_m2m()
1921 self.assertSequenceEqual(
1922 new_art.categories.order_by("name"), [self.c1, self.c2]
1923 )
1924
1925 def test_custom_form_fields(self):
1926 # Here, we define a custom ModelForm. Because it happens to have the
1927 # same fields as the Category model, we can just call the form's save()
1928 # to apply its changes to an existing Category instance.
1929 class ShortCategory(forms.ModelForm):
1930 name = forms.CharField(max_length=5)
1931 slug = forms.CharField(max_length=5)
1932 url = forms.CharField(max_length=3)
1933
1934 class Meta:
1935 model = Category
1936 fields = "__all__"
1937
1938 cat = Category.objects.create(name="Third test")
1939 form = ShortCategory(
1940 {"name": "Third", "slug": "third", "url": "3rd"}, instance=cat
1941 )
1942 self.assertEqual(form.save().name, "Third")
1943 self.assertEqual(Category.objects.get(id=cat.id).name, "Third")
1944
1945 def test_runtime_choicefield_populated(self):
1946 self.maxDiff = None
1947 # Here, we demonstrate that choices for a ForeignKey ChoiceField are determined
1948 # at runtime, based on the data in the database when the form is displayed, not
1949 # the data in the database when the form is instantiated.
1950 self.create_basic_data()
1951 f = ArticleForm(auto_id=False)
1952 self.assertHTMLEqual(
1953 f.as_ul(),
1954 '<li>Headline: <input type="text" name="headline" maxlength="50" required>'
1955 "</li>"
1956 '<li>Slug: <input type="text" name="slug" maxlength="50" required></li>'
1957 '<li>Pub date: <input type="text" name="pub_date" required></li>'
1958 '<li>Writer: <select name="writer" required>'
1959 '<option value="" selected>---------</option>'
1960 '<option value="%s">Bob Woodward</option>'
1961 '<option value="%s">Mike Royko</option>'
1962 "</select></li>"
1963 '<li>Article: <textarea rows="10" cols="40" name="article" required>'
1964 "</textarea></li>"
1965 '<li>Categories: <select multiple name="categories">'
1966 '<option value="%s">Entertainment</option>'
1967 '<option value="%s">It&#x27;s a test</option>'
1968 '<option value="%s">Third test</option>'
1969 "</select> </li>"
1970 '<li>Status: <select name="status">'
1971 '<option value="" selected>---------</option>'
1972 '<option value="1">Draft</option>'
1973 '<option value="2">Pending</option>'
1974 '<option value="3">Live</option>'
1975 "</select></li>"
1976 % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
1977 )
1978
1979 c4 = Category.objects.create(name="Fourth", url="4th")
1980 w_bernstein = Writer.objects.create(name="Carl Bernstein")
1981 self.assertHTMLEqual(
1982 f.as_ul(),
1983 '<li>Headline: <input type="text" name="headline" maxlength="50" required>'
1984 "</li>"
1985 '<li>Slug: <input type="text" name="slug" maxlength="50" required></li>'
1986 '<li>Pub date: <input type="text" name="pub_date" required></li>'
1987 '<li>Writer: <select name="writer" required>'
1988 '<option value="" selected>---------</option>'
1989 '<option value="%s">Bob Woodward</option>'
1990 '<option value="%s">Carl Bernstein</option>'
1991 '<option value="%s">Mike Royko</option>'
1992 "</select></li>"
1993 '<li>Article: <textarea rows="10" cols="40" name="article" required>'
1994 "</textarea></li>"
1995 '<li>Categories: <select multiple name="categories">'
1996 '<option value="%s">Entertainment</option>'
1997 '<option value="%s">It&#x27;s a test</option>'
1998 '<option value="%s">Third test</option>'
1999 '<option value="%s">Fourth</option>'
2000 "</select></li>"
2001 '<li>Status: <select name="status">'
2002 '<option value="" selected>---------</option>'
2003 '<option value="1">Draft</option>'
2004 '<option value="2">Pending</option>'
2005 '<option value="3">Live</option>'
2006 "</select></li>"
2007 % (
2008 self.w_woodward.pk,
2009 w_bernstein.pk,
2010 self.w_royko.pk,
2011 self.c1.pk,
2012 self.c2.pk,
2013 self.c3.pk,
2014 c4.pk,
2015 ),
2016 )
2017
2018 @isolate_apps("model_forms")
2019 def test_callable_choices_are_lazy(self):
2020 call_count = 0
2021
2022 def get_animal_choices():
2023 nonlocal call_count
2024 call_count += 1
2025 return [("LION", "Lion"), ("ZEBRA", "Zebra")]
2026
2027 class ZooKeeper(models.Model):
2028 animal = models.CharField(
2029 blank=True,
2030 choices=get_animal_choices,
2031 max_length=5,
2032 )
2033
2034 class ZooKeeperForm(forms.ModelForm):
2035 class Meta:
2036 model = ZooKeeper
2037 fields = ["animal"]
2038
2039 self.assertEqual(call_count, 0)
2040 form = ZooKeeperForm()
2041 self.assertEqual(call_count, 0)
2042 self.assertIsInstance(form.fields["animal"].choices, BlankChoiceIterator)
2043 self.assertEqual(call_count, 0)
2044 self.assertEqual(
2045 form.fields["animal"].choices,
2046 models.BLANK_CHOICE_DASH + [("LION", "Lion"), ("ZEBRA", "Zebra")],
2047 )
2048 self.assertEqual(call_count, 1)
2049
2050 def test_recleaning_model_form_instance(self):
2051 """
2052 Re-cleaning an instance that was added via a ModelForm shouldn't raise
2053 a pk uniqueness error.
2054 """
2055
2056 class AuthorForm(forms.ModelForm):
2057 class Meta:
2058 model = Author
2059 fields = "__all__"
2060
2061 form = AuthorForm({"full_name": "Bob"})
2062 self.assertTrue(form.is_valid())
2063 obj = form.save()
2064 obj.name = "Alice"
2065 obj.full_clean()
2066
2067 def test_validate_foreign_key_uses_default_manager(self):
2068 class MyForm(forms.ModelForm):
2069 class Meta:
2070 model = Article
2071 fields = "__all__"
2072
2073 # Archived writers are filtered out by the default manager.
2074 w = Writer.objects.create(name="Randy", archived=True)
2075 data = {
2076 "headline": "My Article",
2077 "slug": "my-article",
2078 "pub_date": datetime.date.today(),
2079 "writer": w.pk,
2080 "article": "lorem ipsum",
2081 }
2082 form = MyForm(data)
2083 self.assertIs(form.is_valid(), False)
2084 self.assertEqual(
2085 form.errors,
2086 {
2087 "writer": [
2088 "Select a valid choice. That choice is not one of the available "
2089 "choices."
2090 ]
2091 },
2092 )
2093
2094 def test_validate_foreign_key_to_model_with_overridden_manager(self):
2095 class MyForm(forms.ModelForm):
2096 class Meta:
2097 model = Article
2098 fields = "__all__"
2099
2100 def __init__(self, *args, **kwargs):
2101 super().__init__(*args, **kwargs)
2102 # Allow archived authors.
2103 self.fields["writer"].queryset = Writer._base_manager.all()
2104
2105 w = Writer.objects.create(name="Randy", archived=True)
2106 data = {
2107 "headline": "My Article",
2108 "slug": "my-article",
2109 "pub_date": datetime.date.today(),
2110 "writer": w.pk,
2111 "article": "lorem ipsum",
2112 }
2113 form = MyForm(data)
2114 self.assertIs(form.is_valid(), True)
2115 article = form.save()
2116 self.assertEqual(article.writer, w)
2117
2118
2119 class ModelMultipleChoiceFieldTests(TestCase):
2120 @classmethod
2121 def setUpTestData(cls):
2122 cls.c1 = Category.objects.create(
2123 name="Entertainment", slug="entertainment", url="entertainment"
2124 )
2125 cls.c2 = Category.objects.create(
2126 name="It's a test", slug="its-test", url="test"
2127 )
2128 cls.c3 = Category.objects.create(name="Third", slug="third-test", url="third")
2129
2130 def test_model_multiple_choice_field(self):
2131 f = forms.ModelMultipleChoiceField(Category.objects.all())
2132 self.assertCountEqual(
2133 list(f.choices),
2134 [
2135 (self.c1.pk, "Entertainment"),
2136 (self.c2.pk, "It's a test"),
2137 (self.c3.pk, "Third"),
2138 ],
2139 )
2140 with self.assertRaises(ValidationError):
2141 f.clean(None)
2142 with self.assertRaises(ValidationError):
2143 f.clean([])
2144 self.assertCountEqual(f.clean([self.c1.id]), [self.c1])
2145 self.assertCountEqual(f.clean([self.c2.id]), [self.c2])
2146 self.assertCountEqual(f.clean([str(self.c1.id)]), [self.c1])
2147 self.assertCountEqual(
2148 f.clean([str(self.c1.id), str(self.c2.id)]),
2149 [self.c1, self.c2],
2150 )
2151 self.assertCountEqual(
2152 f.clean([self.c1.id, str(self.c2.id)]),
2153 [self.c1, self.c2],
2154 )
2155 self.assertCountEqual(
2156 f.clean((self.c1.id, str(self.c2.id))),
2157 [self.c1, self.c2],
2158 )
2159 with self.assertRaises(ValidationError):
2160 f.clean(["0"])
2161 with self.assertRaises(ValidationError):
2162 f.clean("hello")
2163 with self.assertRaises(ValidationError):
2164 f.clean(["fail"])
2165
2166 # Invalid types that require TypeError to be caught (#22808).
2167 with self.assertRaises(ValidationError):
2168 f.clean([["fail"]])
2169 with self.assertRaises(ValidationError):
2170 f.clean([{"foo": "bar"}])
2171
2172 # Add a Category object *after* the ModelMultipleChoiceField has already been
2173 # instantiated. This proves clean() checks the database during clean() rather
2174 # than caching it at time of instantiation.
2175 # Note, we are using an id of 1006 here since tests that run before
2176 # this may create categories with primary keys up to 6. Use
2177 # a number that will not conflict.
2178 c6 = Category.objects.create(id=1006, name="Sixth", url="6th")
2179 self.assertCountEqual(f.clean([c6.id]), [c6])
2180
2181 # Delete a Category object *after* the ModelMultipleChoiceField has already been
2182 # instantiated. This proves clean() checks the database during clean() rather
2183 # than caching it at time of instantiation.
2184 Category.objects.get(url="6th").delete()
2185 with self.assertRaises(ValidationError):
2186 f.clean([c6.id])
2187
2188 def test_model_multiple_choice_required_false(self):
2189 f = forms.ModelMultipleChoiceField(Category.objects.all(), required=False)
2190 self.assertIsInstance(f.clean([]), EmptyQuerySet)
2191 self.assertIsInstance(f.clean(()), EmptyQuerySet)
2192 with self.assertRaises(ValidationError):
2193 f.clean(["0"])
2194 with self.assertRaises(ValidationError):
2195 f.clean([str(self.c3.id), "0"])
2196 with self.assertRaises(ValidationError):
2197 f.clean([str(self.c1.id), "0"])
2198
2199 # queryset can be changed after the field is created.
2200 f.queryset = Category.objects.exclude(name="Third")
2201 self.assertCountEqual(
2202 list(f.choices),
2203 [(self.c1.pk, "Entertainment"), (self.c2.pk, "It's a test")],
2204 )
2205 self.assertSequenceEqual(f.clean([self.c2.id]), [self.c2])
2206 with self.assertRaises(ValidationError):
2207 f.clean([self.c3.id])
2208 with self.assertRaises(ValidationError):
2209 f.clean([str(self.c2.id), str(self.c3.id)])
2210
2211 f.queryset = Category.objects.all()
2212 f.label_from_instance = lambda obj: "multicategory " + str(obj)
2213 self.assertCountEqual(
2214 list(f.choices),
2215 [
2216 (self.c1.pk, "multicategory Entertainment"),
2217 (self.c2.pk, "multicategory It's a test"),
2218 (self.c3.pk, "multicategory Third"),
2219 ],
2220 )
2221
2222 def test_model_multiple_choice_number_of_queries(self):
2223 """
2224 ModelMultipleChoiceField does O(1) queries instead of O(n) (#10156).
2225 """
2226 persons = [Writer.objects.create(name="Person %s" % i) for i in range(30)]
2227
2228 f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all())
2229 self.assertNumQueries(1, f.clean, [p.pk for p in persons[1:11:2]])
2230
2231 def test_model_multiple_choice_null_characters(self):
2232 f = forms.ModelMultipleChoiceField(queryset=ExplicitPK.objects.all())
2233 msg = "Null characters are not allowed."
2234 with self.assertRaisesMessage(ValidationError, msg):
2235 f.clean(["\x00something"])
2236
2237 with self.assertRaisesMessage(ValidationError, msg):
2238 f.clean(["valid", "\x00something"])
2239
2240 def test_model_multiple_choice_run_validators(self):
2241 """
2242 ModelMultipleChoiceField run given validators (#14144).
2243 """
2244 for i in range(30):
2245 Writer.objects.create(name="Person %s" % i)
2246
2247 self._validator_run = False
2248
2249 def my_validator(value):
2250 self._validator_run = True
2251
2252 f = forms.ModelMultipleChoiceField(
2253 queryset=Writer.objects.all(), validators=[my_validator]
2254 )
2255 f.clean([p.pk for p in Writer.objects.all()[8:9]])
2256 self.assertTrue(self._validator_run)
2257
2258 def test_model_multiple_choice_show_hidden_initial(self):
2259 """
2260 Test support of show_hidden_initial by ModelMultipleChoiceField.
2261 """
2262
2263 class WriterForm(forms.Form):
2264 persons = forms.ModelMultipleChoiceField(
2265 show_hidden_initial=True, queryset=Writer.objects.all()
2266 )
2267
2268 person1 = Writer.objects.create(name="Person 1")
2269 person2 = Writer.objects.create(name="Person 2")
2270
2271 form = WriterForm(
2272 initial={"persons": [person1, person2]},
2273 data={
2274 "initial-persons": [str(person1.pk), str(person2.pk)],
2275 "persons": [str(person1.pk), str(person2.pk)],
2276 },
2277 )
2278 self.assertTrue(form.is_valid())
2279 self.assertFalse(form.has_changed())
2280
2281 form = WriterForm(
2282 initial={"persons": [person1, person2]},
2283 data={
2284 "initial-persons": [str(person1.pk), str(person2.pk)],
2285 "persons": [str(person2.pk)],
2286 },
2287 )
2288 self.assertTrue(form.is_valid())
2289 self.assertTrue(form.has_changed())
2290
2291 def test_model_multiple_choice_field_22745(self):
2292 """
2293 #22745 -- Make sure that ModelMultipleChoiceField with
2294 CheckboxSelectMultiple widget doesn't produce unnecessary db queries
2295 when accessing its BoundField's attrs.
2296 """
2297
2298 class ModelMultipleChoiceForm(forms.Form):
2299 categories = forms.ModelMultipleChoiceField(
2300 Category.objects.all(), widget=forms.CheckboxSelectMultiple
2301 )
2302
2303 form = ModelMultipleChoiceForm()
2304 field = form["categories"] # BoundField
2305 template = Template("{{ field.name }}{{ field }}{{ field.help_text }}")
2306 with self.assertNumQueries(1):
2307 template.render(Context({"field": field}))
2308
2309 def test_show_hidden_initial_changed_queries_efficiently(self):
2310 class WriterForm(forms.Form):
2311 persons = forms.ModelMultipleChoiceField(
2312 show_hidden_initial=True, queryset=Writer.objects.all()
2313 )
2314
2315 writers = (Writer.objects.create(name=str(x)) for x in range(0, 50))
2316 writer_pks = tuple(x.pk for x in writers)
2317 form = WriterForm(data={"initial-persons": writer_pks})
2318 with self.assertNumQueries(1):
2319 self.assertTrue(form.has_changed())
2320
2321 def test_clean_does_deduplicate_values(self):
2322 class PersonForm(forms.Form):
2323 persons = forms.ModelMultipleChoiceField(queryset=Person.objects.all())
2324
2325 person1 = Person.objects.create(name="Person 1")
2326 form = PersonForm(data={})
2327 queryset = form.fields["persons"].clean([str(person1.pk)] * 50)
2328 sql, params = queryset.query.sql_with_params()
2329 self.assertEqual(len(params), 1)
2330
2331 def test_to_field_name_with_initial_data(self):
2332 class ArticleCategoriesForm(forms.ModelForm):
2333 categories = forms.ModelMultipleChoiceField(
2334 Category.objects.all(), to_field_name="slug"
2335 )
2336
2337 class Meta:
2338 model = Article
2339 fields = ["categories"]
2340
2341 article = Article.objects.create(
2342 headline="Test article",
2343 slug="test-article",
2344 pub_date=datetime.date(1988, 1, 4),
2345 writer=Writer.objects.create(name="Test writer"),
2346 article="Hello.",
2347 )
2348 article.categories.add(self.c2, self.c3)
2349 form = ArticleCategoriesForm(instance=article)
2350 self.assertCountEqual(form["categories"].value(), [self.c2.slug, self.c3.slug])
2351
2352
2353 class ModelOneToOneFieldTests(TestCase):
2354 def test_modelform_onetoonefield(self):
2355 class ImprovedArticleForm(forms.ModelForm):
2356 class Meta:
2357 model = ImprovedArticle
2358 fields = "__all__"
2359
2360 class ImprovedArticleWithParentLinkForm(forms.ModelForm):
2361 class Meta:
2362 model = ImprovedArticleWithParentLink
2363 fields = "__all__"
2364
2365 self.assertEqual(list(ImprovedArticleForm.base_fields), ["article"])
2366 self.assertEqual(list(ImprovedArticleWithParentLinkForm.base_fields), [])
2367
2368 def test_modelform_subclassed_model(self):
2369 class BetterWriterForm(forms.ModelForm):
2370 class Meta:
2371 # BetterWriter model is a subclass of Writer with an additional
2372 # `score` field.
2373 model = BetterWriter
2374 fields = "__all__"
2375
2376 bw = BetterWriter.objects.create(name="Joe Better", score=10)
2377 self.assertEqual(
2378 sorted(model_to_dict(bw)), ["id", "name", "score", "writer_ptr"]
2379 )
2380 self.assertEqual(sorted(model_to_dict(bw, fields=[])), [])
2381 self.assertEqual(
2382 sorted(model_to_dict(bw, fields=["id", "name"])), ["id", "name"]
2383 )
2384 self.assertEqual(
2385 sorted(model_to_dict(bw, exclude=[])), ["id", "name", "score", "writer_ptr"]
2386 )
2387 self.assertEqual(
2388 sorted(model_to_dict(bw, exclude=["id", "name"])), ["score", "writer_ptr"]
2389 )
2390
2391 form = BetterWriterForm({"name": "Some Name", "score": 12})
2392 self.assertTrue(form.is_valid())
2393 bw2 = form.save()
2394 self.assertEqual(bw2.score, 12)
2395
2396 def test_onetoonefield(self):
2397 class WriterProfileForm(forms.ModelForm):
2398 class Meta:
2399 # WriterProfile has a OneToOneField to Writer
2400 model = WriterProfile
2401 fields = "__all__"
2402
2403 self.w_royko = Writer.objects.create(name="Mike Royko")
2404 self.w_woodward = Writer.objects.create(name="Bob Woodward")
2405
2406 form = WriterProfileForm()
2407 self.assertHTMLEqual(
2408 form.as_p(),
2409 """
2410 <p><label for="id_writer">Writer:</label>
2411 <select name="writer" id="id_writer" required>
2412 <option value="" selected>---------</option>
2413 <option value="%s">Bob Woodward</option>
2414 <option value="%s">Mike Royko</option>
2415 </select></p>
2416 <p><label for="id_age">Age:</label>
2417 <input type="number" name="age" id="id_age" min="0" required></p>
2418 """
2419 % (
2420 self.w_woodward.pk,
2421 self.w_royko.pk,
2422 ),
2423 )
2424
2425 data = {
2426 "writer": str(self.w_woodward.pk),
2427 "age": "65",
2428 }
2429 form = WriterProfileForm(data)
2430 instance = form.save()
2431 self.assertEqual(str(instance), "Bob Woodward is 65")
2432
2433 form = WriterProfileForm(instance=instance)
2434 self.assertHTMLEqual(
2435 form.as_p(),
2436 """
2437 <p><label for="id_writer">Writer:</label>
2438 <select name="writer" id="id_writer" required>
2439 <option value="">---------</option>
2440 <option value="%s" selected>Bob Woodward</option>
2441 <option value="%s">Mike Royko</option>
2442 </select></p>
2443 <p><label for="id_age">Age:</label>
2444 <input type="number" name="age" value="65" id="id_age" min="0" required>
2445 </p>"""
2446 % (
2447 self.w_woodward.pk,
2448 self.w_royko.pk,
2449 ),
2450 )
2451
2452 def test_assignment_of_none(self):
2453 class AuthorForm(forms.ModelForm):
2454 class Meta:
2455 model = Author
2456 fields = ["publication", "full_name"]
2457
2458 publication = Publication.objects.create(
2459 title="Pravda", date_published=datetime.date(1991, 8, 22)
2460 )
2461 author = Author.objects.create(publication=publication, full_name="John Doe")
2462 form = AuthorForm({"publication": "", "full_name": "John Doe"}, instance=author)
2463 self.assertTrue(form.is_valid())
2464 self.assertIsNone(form.cleaned_data["publication"])
2465 author = form.save()
2466 # author object returned from form still retains original publication object
2467 # that's why we need to retrieve it from database again
2468 new_author = Author.objects.get(pk=author.pk)
2469 self.assertIsNone(new_author.publication)
2470
2471 def test_assignment_of_none_null_false(self):
2472 class AuthorForm(forms.ModelForm):
2473 class Meta:
2474 model = Author1
2475 fields = ["publication", "full_name"]
2476
2477 publication = Publication.objects.create(
2478 title="Pravda", date_published=datetime.date(1991, 8, 22)
2479 )
2480 author = Author1.objects.create(publication=publication, full_name="John Doe")
2481 form = AuthorForm({"publication": "", "full_name": "John Doe"}, instance=author)
2482 self.assertFalse(form.is_valid())
2483
2484
2485 class FileAndImageFieldTests(TestCase):
2486 def setUp(self):
2487 if os.path.exists(temp_storage_dir):
2488 shutil.rmtree(temp_storage_dir)
2489 os.mkdir(temp_storage_dir)
2490 self.addCleanup(shutil.rmtree, temp_storage_dir)
2491
2492 def test_clean_false(self):
2493 """
2494 If the ``clean`` method on a non-required FileField receives False as
2495 the data (meaning clear the field value), it returns False, regardless
2496 of the value of ``initial``.
2497 """
2498 f = forms.FileField(required=False)
2499 self.assertIs(f.clean(False), False)
2500 self.assertIs(f.clean(False, "initial"), False)
2501
2502 def test_clean_false_required(self):
2503 """
2504 If the ``clean`` method on a required FileField receives False as the
2505 data, it has the same effect as None: initial is returned if non-empty,
2506 otherwise the validation catches the lack of a required value.
2507 """
2508 f = forms.FileField(required=True)
2509 self.assertEqual(f.clean(False, "initial"), "initial")
2510 with self.assertRaises(ValidationError):
2511 f.clean(False)
2512
2513 def test_full_clear(self):
2514 """
2515 Integration happy-path test that a model FileField can actually be set
2516 and cleared via a ModelForm.
2517 """
2518
2519 class DocumentForm(forms.ModelForm):
2520 class Meta:
2521 model = Document
2522 fields = "__all__"
2523
2524 form = DocumentForm()
2525 self.assertIn('name="myfile"', str(form))
2526 self.assertNotIn("myfile-clear", str(form))
2527 form = DocumentForm(
2528 files={"myfile": SimpleUploadedFile("something.txt", b"content")}
2529 )
2530 self.assertTrue(form.is_valid())
2531 doc = form.save(commit=False)
2532 self.assertEqual(doc.myfile.name, "something.txt")
2533 form = DocumentForm(instance=doc)
2534 self.assertIn("myfile-clear", str(form))
2535 form = DocumentForm(instance=doc, data={"myfile-clear": "true"})
2536 doc = form.save(commit=False)
2537 self.assertFalse(doc.myfile)
2538
2539 def test_clear_and_file_contradiction(self):
2540 """
2541 If the user submits a new file upload AND checks the clear checkbox,
2542 they get a validation error, and the bound redisplay of the form still
2543 includes the current file and the clear checkbox.
2544 """
2545
2546 class DocumentForm(forms.ModelForm):
2547 class Meta:
2548 model = Document
2549 fields = "__all__"
2550
2551 form = DocumentForm(
2552 files={"myfile": SimpleUploadedFile("something.txt", b"content")}
2553 )
2554 self.assertTrue(form.is_valid())
2555 doc = form.save(commit=False)
2556 form = DocumentForm(
2557 instance=doc,
2558 files={"myfile": SimpleUploadedFile("something.txt", b"content")},
2559 data={"myfile-clear": "true"},
2560 )
2561 self.assertTrue(not form.is_valid())
2562 self.assertEqual(
2563 form.errors["myfile"],
2564 ["Please either submit a file or check the clear checkbox, not both."],
2565 )
2566 rendered = str(form)
2567 self.assertIn("something.txt", rendered)
2568 self.assertIn("myfile-clear", rendered)
2569
2570 def test_render_empty_file_field(self):
2571 class DocumentForm(forms.ModelForm):
2572 class Meta:
2573 model = Document
2574 fields = "__all__"
2575
2576 doc = Document.objects.create()
2577 form = DocumentForm(instance=doc)
2578 self.assertHTMLEqual(
2579 str(form["myfile"]), '<input id="id_myfile" name="myfile" type="file">'
2580 )
2581
2582 def test_file_field_data(self):
2583 # Test conditions when files is either not given or empty.
2584 f = TextFileForm(data={"description": "Assistance"})
2585 self.assertFalse(f.is_valid())
2586 f = TextFileForm(data={"description": "Assistance"}, files={})
2587 self.assertFalse(f.is_valid())
2588
2589 # Upload a file and ensure it all works as expected.
2590 f = TextFileForm(
2591 data={"description": "Assistance"},
2592 files={"file": SimpleUploadedFile("test1.txt", b"hello world")},
2593 )
2594 self.assertTrue(f.is_valid())
2595 self.assertEqual(type(f.cleaned_data["file"]), SimpleUploadedFile)
2596 instance = f.save()
2597 self.assertEqual(instance.file.name, "tests/test1.txt")
2598 instance.file.delete()
2599
2600 # If the previous file has been deleted, the file name can be reused
2601 f = TextFileForm(
2602 data={"description": "Assistance"},
2603 files={"file": SimpleUploadedFile("test1.txt", b"hello world")},
2604 )
2605 self.assertTrue(f.is_valid())
2606 self.assertEqual(type(f.cleaned_data["file"]), SimpleUploadedFile)
2607 instance = f.save()
2608 self.assertEqual(instance.file.name, "tests/test1.txt")
2609
2610 # Check if the max_length attribute has been inherited from the model.
2611 f = TextFileForm(
2612 data={"description": "Assistance"},
2613 files={"file": SimpleUploadedFile("test-maxlength.txt", b"hello world")},
2614 )
2615 self.assertFalse(f.is_valid())
2616
2617 # Edit an instance that already has the file defined in the model. This will not
2618 # save the file again, but leave it exactly as it is.
2619 f = TextFileForm({"description": "Assistance"}, instance=instance)
2620 self.assertTrue(f.is_valid())
2621 self.assertEqual(f.cleaned_data["file"].name, "tests/test1.txt")
2622 instance = f.save()
2623 self.assertEqual(instance.file.name, "tests/test1.txt")
2624
2625 # Delete the current file since this is not done by Django.
2626 instance.file.delete()
2627
2628 # Override the file by uploading a new one.
2629 f = TextFileForm(
2630 data={"description": "Assistance"},
2631 files={"file": SimpleUploadedFile("test2.txt", b"hello world")},
2632 instance=instance,
2633 )
2634 self.assertTrue(f.is_valid())
2635 instance = f.save()
2636 self.assertEqual(instance.file.name, "tests/test2.txt")
2637
2638 # Delete the current file since this is not done by Django.
2639 instance.file.delete()
2640 instance.delete()
2641
2642 def test_filefield_required_false(self):
2643 # Test the non-required FileField
2644 f = TextFileForm(data={"description": "Assistance"})
2645 f.fields["file"].required = False
2646 self.assertTrue(f.is_valid())
2647 instance = f.save()
2648 self.assertEqual(instance.file.name, "")
2649
2650 f = TextFileForm(
2651 data={"description": "Assistance"},
2652 files={"file": SimpleUploadedFile("test3.txt", b"hello world")},
2653 instance=instance,
2654 )
2655 self.assertTrue(f.is_valid())
2656 instance = f.save()
2657 self.assertEqual(instance.file.name, "tests/test3.txt")
2658
2659 # Instance can be edited w/out re-uploading the file and existing file
2660 # should be preserved.
2661 f = TextFileForm({"description": "New Description"}, instance=instance)
2662 f.fields["file"].required = False
2663 self.assertTrue(f.is_valid())
2664 instance = f.save()
2665 self.assertEqual(instance.description, "New Description")
2666 self.assertEqual(instance.file.name, "tests/test3.txt")
2667
2668 # Delete the current file since this is not done by Django.
2669 instance.file.delete()
2670 instance.delete()
2671
2672 def test_custom_file_field_save(self):
2673 """
2674 Regression for #11149: save_form_data should be called only once
2675 """
2676
2677 class CFFForm(forms.ModelForm):
2678 class Meta:
2679 model = CustomFF
2680 fields = "__all__"
2681
2682 # It's enough that the form saves without error -- the custom save routine will
2683 # generate an AssertionError if it is called more than once during save.
2684 form = CFFForm(data={"f": None})
2685 form.save()
2686
2687 def test_file_field_multiple_save(self):
2688 """
2689 Simulate a file upload and check how many times Model.save() gets
2690 called. Test for bug #639.
2691 """
2692
2693 class PhotoForm(forms.ModelForm):
2694 class Meta:
2695 model = Photo
2696 fields = "__all__"
2697
2698 # Grab an image for testing.
2699 filename = os.path.join(os.path.dirname(__file__), "test.png")
2700 with open(filename, "rb") as fp:
2701 img = fp.read()
2702
2703 # Fake a POST QueryDict and FILES MultiValueDict.
2704 data = {"title": "Testing"}
2705 files = {"image": SimpleUploadedFile("test.png", img, "image/png")}
2706
2707 form = PhotoForm(data=data, files=files)
2708 p = form.save()
2709
2710 try:
2711 # Check the savecount stored on the object (see the model).
2712 self.assertEqual(p._savecount, 1)
2713 finally:
2714 # Delete the "uploaded" file to avoid clogging /tmp.
2715 p = Photo.objects.get()
2716 p.image.delete(save=False)
2717
2718 def test_file_path_field_blank(self):
2719 """FilePathField(blank=True) includes the empty option."""
2720
2721 class FPForm(forms.ModelForm):
2722 class Meta:
2723 model = FilePathModel
2724 fields = "__all__"
2725
2726 form = FPForm()
2727 self.assertEqual(
2728 [name for _, name in form["path"].field.choices], ["---------", "models.py"]
2729 )
2730
2731 @skipUnless(test_images, "Pillow not installed")
2732 def test_image_field(self):
2733 # ImageField and FileField are nearly identical, but they differ slightly when
2734 # it comes to validation. This specifically tests that #6302 is fixed for
2735 # both file fields and image fields.
2736
2737 with open(os.path.join(os.path.dirname(__file__), "test.png"), "rb") as fp:
2738 image_data = fp.read()
2739 with open(os.path.join(os.path.dirname(__file__), "test2.png"), "rb") as fp:
2740 image_data2 = fp.read()
2741
2742 f = ImageFileForm(
2743 data={"description": "An image"},
2744 files={"image": SimpleUploadedFile("test.png", image_data)},
2745 )
2746 self.assertTrue(f.is_valid())
2747 self.assertEqual(type(f.cleaned_data["image"]), SimpleUploadedFile)
2748 instance = f.save()
2749 self.assertEqual(instance.image.name, "tests/test.png")
2750 self.assertEqual(instance.width, 16)
2751 self.assertEqual(instance.height, 16)
2752
2753 # Delete the current file since this is not done by Django, but don't save
2754 # because the dimension fields are not null=True.
2755 instance.image.delete(save=False)
2756 f = ImageFileForm(
2757 data={"description": "An image"},
2758 files={"image": SimpleUploadedFile("test.png", image_data)},
2759 )
2760 self.assertTrue(f.is_valid())
2761 self.assertEqual(type(f.cleaned_data["image"]), SimpleUploadedFile)
2762 instance = f.save()
2763 self.assertEqual(instance.image.name, "tests/test.png")
2764 self.assertEqual(instance.width, 16)
2765 self.assertEqual(instance.height, 16)
2766
2767 # Edit an instance that already has the (required) image defined in the
2768 # model. This will not save the image again, but leave it exactly as it
2769 # is.
2770
2771 f = ImageFileForm(data={"description": "Look, it changed"}, instance=instance)
2772 self.assertTrue(f.is_valid())
2773 self.assertEqual(f.cleaned_data["image"].name, "tests/test.png")
2774 instance = f.save()
2775 self.assertEqual(instance.image.name, "tests/test.png")
2776 self.assertEqual(instance.height, 16)
2777 self.assertEqual(instance.width, 16)
2778
2779 # Delete the current file since this is not done by Django, but don't save
2780 # because the dimension fields are not null=True.
2781 instance.image.delete(save=False)
2782 # Override the file by uploading a new one.
2783
2784 f = ImageFileForm(
2785 data={"description": "Changed it"},
2786 files={"image": SimpleUploadedFile("test2.png", image_data2)},
2787 instance=instance,
2788 )
2789 self.assertTrue(f.is_valid())
2790 instance = f.save()
2791 self.assertEqual(instance.image.name, "tests/test2.png")
2792 self.assertEqual(instance.height, 32)
2793 self.assertEqual(instance.width, 48)
2794
2795 # Delete the current file since this is not done by Django, but don't save
2796 # because the dimension fields are not null=True.
2797 instance.image.delete(save=False)
2798 instance.delete()
2799
2800 f = ImageFileForm(
2801 data={"description": "Changed it"},
2802 files={"image": SimpleUploadedFile("test2.png", image_data2)},
2803 )
2804 self.assertTrue(f.is_valid())
2805 instance = f.save()
2806 self.assertEqual(instance.image.name, "tests/test2.png")
2807 self.assertEqual(instance.height, 32)
2808 self.assertEqual(instance.width, 48)
2809
2810 # Delete the current file since this is not done by Django, but don't save
2811 # because the dimension fields are not null=True.
2812 instance.image.delete(save=False)
2813 instance.delete()
2814
2815 # Test the non-required ImageField
2816 # Note: In Oracle, we expect a null ImageField to return '' instead of
2817 # None.
2818 if connection.features.interprets_empty_strings_as_nulls:
2819 expected_null_imagefield_repr = ""
2820 else:
2821 expected_null_imagefield_repr = None
2822
2823 f = OptionalImageFileForm(data={"description": "Test"})
2824 self.assertTrue(f.is_valid())
2825 instance = f.save()
2826 self.assertEqual(instance.image.name, expected_null_imagefield_repr)
2827 self.assertIsNone(instance.width)
2828 self.assertIsNone(instance.height)
2829
2830 f = OptionalImageFileForm(
2831 data={"description": "And a final one"},
2832 files={"image": SimpleUploadedFile("test3.png", image_data)},
2833 instance=instance,
2834 )
2835 self.assertTrue(f.is_valid())
2836 instance = f.save()
2837 self.assertEqual(instance.image.name, "tests/test3.png")
2838 self.assertEqual(instance.width, 16)
2839 self.assertEqual(instance.height, 16)
2840
2841 # Editing the instance without re-uploading the image should not affect
2842 # the image or its width/height properties.
2843 f = OptionalImageFileForm({"description": "New Description"}, instance=instance)
2844 self.assertTrue(f.is_valid())
2845 instance = f.save()
2846 self.assertEqual(instance.description, "New Description")
2847 self.assertEqual(instance.image.name, "tests/test3.png")
2848 self.assertEqual(instance.width, 16)
2849 self.assertEqual(instance.height, 16)
2850
2851 # Delete the current file since this is not done by Django.
2852 instance.image.delete()
2853 instance.delete()
2854
2855 f = OptionalImageFileForm(
2856 data={"description": "And a final one"},
2857 files={"image": SimpleUploadedFile("test4.png", image_data2)},
2858 )
2859 self.assertTrue(f.is_valid())
2860 instance = f.save()
2861 self.assertEqual(instance.image.name, "tests/test4.png")
2862 self.assertEqual(instance.width, 48)
2863 self.assertEqual(instance.height, 32)
2864 instance.delete()
2865 # Callable upload_to behavior that's dependent on the value of another
2866 # field in the model.
2867 f = ImageFileForm(
2868 data={"description": "And a final one", "path": "foo"},
2869 files={"image": SimpleUploadedFile("test4.png", image_data)},
2870 )
2871 self.assertTrue(f.is_valid())
2872 instance = f.save()
2873 self.assertEqual(instance.image.name, "foo/test4.png")
2874 instance.delete()
2875
2876 # Editing an instance that has an image without an extension shouldn't
2877 # fail validation. First create:
2878 f = NoExtensionImageFileForm(
2879 data={"description": "An image"},
2880 files={"image": SimpleUploadedFile("test.png", image_data)},
2881 )
2882 self.assertTrue(f.is_valid())
2883 instance = f.save()
2884 self.assertEqual(instance.image.name, "tests/no_extension")
2885 # Then edit:
2886 f = NoExtensionImageFileForm(
2887 data={"description": "Edited image"}, instance=instance
2888 )
2889 self.assertTrue(f.is_valid())
2890
2891
2892 class ModelOtherFieldTests(SimpleTestCase):
2893 def test_big_integer_field(self):
2894 bif = BigIntForm({"biggie": "-9223372036854775808"})
2895 self.assertTrue(bif.is_valid())
2896 bif = BigIntForm({"biggie": "-9223372036854775809"})
2897 self.assertFalse(bif.is_valid())
2898 self.assertEqual(
2899 bif.errors,
2900 {
2901 "biggie": [
2902 "Ensure this value is greater than or equal to "
2903 "-9223372036854775808."
2904 ]
2905 },
2906 )
2907 bif = BigIntForm({"biggie": "9223372036854775807"})
2908 self.assertTrue(bif.is_valid())
2909 bif = BigIntForm({"biggie": "9223372036854775808"})
2910 self.assertFalse(bif.is_valid())
2911 self.assertEqual(
2912 bif.errors,
2913 {
2914 "biggie": [
2915 "Ensure this value is less than or equal to 9223372036854775807."
2916 ]
2917 },
2918 )
2919
2920 @ignore_warnings(category=RemovedInDjango60Warning)
2921 def test_url_on_modelform(self):
2922 "Check basic URL field validation on model forms"
2923
2924 class HomepageForm(forms.ModelForm):
2925 class Meta:
2926 model = Homepage
2927 fields = "__all__"
2928
2929 self.assertFalse(HomepageForm({"url": "foo"}).is_valid())
2930 self.assertFalse(HomepageForm({"url": "http://"}).is_valid())
2931 self.assertFalse(HomepageForm({"url": "http://example"}).is_valid())
2932 self.assertFalse(HomepageForm({"url": "http://example."}).is_valid())
2933 self.assertFalse(HomepageForm({"url": "http://com."}).is_valid())
2934
2935 self.assertTrue(HomepageForm({"url": "http://localhost"}).is_valid())
2936 self.assertTrue(HomepageForm({"url": "http://example.com"}).is_valid())
2937 self.assertTrue(HomepageForm({"url": "http://www.example.com"}).is_valid())
2938 self.assertTrue(HomepageForm({"url": "http://www.example.com:8000"}).is_valid())
2939 self.assertTrue(HomepageForm({"url": "http://www.example.com/test"}).is_valid())
2940 self.assertTrue(
2941 HomepageForm({"url": "http://www.example.com:8000/test"}).is_valid()
2942 )
2943 self.assertTrue(HomepageForm({"url": "http://example.com/foo/bar"}).is_valid())
2944
2945 def test_url_modelform_assume_scheme_warning(self):
2946 msg = (
2947 "The default scheme will be changed from 'http' to 'https' in Django "
2948 "6.0. Pass the forms.URLField.assume_scheme argument to silence this "
2949 "warning, or set the FORMS_URLFIELD_ASSUME_HTTPS transitional setting to "
2950 "True to opt into using 'https' as the new default scheme."
2951 )
2952 with self.assertWarnsMessage(RemovedInDjango60Warning, msg):
2953
2954 class HomepageForm(forms.ModelForm):
2955 class Meta:
2956 model = Homepage
2957 fields = "__all__"
2958
2959 def test_url_modelform_assume_scheme_early_adopt_https(self):
2960 msg = "The FORMS_URLFIELD_ASSUME_HTTPS transitional setting is deprecated."
2961 with (
2962 self.assertWarnsMessage(RemovedInDjango60Warning, msg),
2963 self.settings(FORMS_URLFIELD_ASSUME_HTTPS=True),
2964 ):
2965
2966 class HomepageForm(forms.ModelForm):
2967 class Meta:
2968 model = Homepage
2969 fields = "__all__"
2970
2971 def test_modelform_non_editable_field(self):
2972 """
2973 When explicitly including a non-editable field in a ModelForm, the
2974 error message should be explicit.
2975 """
2976 # 'created', non-editable, is excluded by default
2977 self.assertNotIn("created", ArticleForm().fields)
2978
2979 msg = (
2980 "'created' cannot be specified for Article model form as it is a "
2981 "non-editable field"
2982 )
2983 with self.assertRaisesMessage(FieldError, msg):
2984
2985 class InvalidArticleForm(forms.ModelForm):
2986 class Meta:
2987 model = Article
2988 fields = ("headline", "created")
2989
2990 def test_https_prefixing(self):
2991 """
2992 If the https:// prefix is omitted on form input, the field adds it
2993 again.
2994 """
2995
2996 class HomepageForm(forms.ModelForm):
2997 # RemovedInDjango60Warning.
2998 url = forms.URLField(assume_scheme="https")
2999
3000 class Meta:
3001 model = Homepage
3002 fields = "__all__"
3003
3004 form = HomepageForm({"url": "example.com"})
3005 self.assertTrue(form.is_valid())
3006 self.assertEqual(form.cleaned_data["url"], "https://example.com")
3007
3008 form = HomepageForm({"url": "example.com/test"})
3009 self.assertTrue(form.is_valid())
3010 self.assertEqual(form.cleaned_data["url"], "https://example.com/test")
3011
3012
3013 class OtherModelFormTests(TestCase):
3014 def test_media_on_modelform(self):
3015 # Similar to a regular Form class you can define custom media to be used on
3016 # the ModelForm.
3017 f = ModelFormWithMedia()
3018 self.assertHTMLEqual(
3019 str(f.media),
3020 '<link href="/some/form/css" media="all" rel="stylesheet">'
3021 '<script src="/some/form/javascript"></script>',
3022 )
3023
3024 def test_choices_type(self):
3025 # Choices on CharField and IntegerField
3026 f = ArticleForm()
3027 with self.assertRaises(ValidationError):
3028 f.fields["status"].clean("42")
3029
3030 f = ArticleStatusForm()
3031 with self.assertRaises(ValidationError):
3032 f.fields["status"].clean("z")
3033
3034 def test_prefetch_related_queryset(self):
3035 """
3036 ModelChoiceField should respect a prefetch_related() on its queryset.
3037 """
3038 blue = Colour.objects.create(name="blue")
3039 red = Colour.objects.create(name="red")
3040 multicolor_item = ColourfulItem.objects.create()
3041 multicolor_item.colours.add(blue, red)
3042 red_item = ColourfulItem.objects.create()
3043 red_item.colours.add(red)
3044
3045 class ColorModelChoiceField(forms.ModelChoiceField):
3046 def label_from_instance(self, obj):
3047 return ", ".join(c.name for c in obj.colours.all())
3048
3049 field = ColorModelChoiceField(ColourfulItem.objects.prefetch_related("colours"))
3050 # CPython < 3.14 calls ModelChoiceField.__len__() when coercing to
3051 # tuple. PyPy and Python 3.14+ don't call __len__() and so .count()
3052 # isn't called on the QuerySet. The following would trigger an extra
3053 # query if prefetch were ignored.
3054 with self.assertNumQueries(2 if PYPY or PY314 else 3):
3055 self.assertEqual(
3056 tuple(field.choices),
3057 (
3058 ("", "---------"),
3059 (multicolor_item.pk, "blue, red"),
3060 (red_item.pk, "red"),
3061 ),
3062 )
3063
3064 def test_foreignkeys_which_use_to_field(self):
3065 apple = Inventory.objects.create(barcode=86, name="Apple")
3066 pear = Inventory.objects.create(barcode=22, name="Pear")
3067 core = Inventory.objects.create(barcode=87, name="Core", parent=apple)
3068
3069 field = forms.ModelChoiceField(Inventory.objects.all(), to_field_name="barcode")
3070 self.assertEqual(
3071 tuple(field.choices),
3072 (("", "---------"), (86, "Apple"), (87, "Core"), (22, "Pear")),
3073 )
3074
3075 form = InventoryForm(instance=core)
3076 self.assertHTMLEqual(
3077 str(form["parent"]),
3078 """<select name="parent" id="id_parent">
3079 <option value="">---------</option>
3080 <option value="86" selected>Apple</option>
3081 <option value="87">Core</option>
3082 <option value="22">Pear</option>
3083 </select>""",
3084 )
3085 data = model_to_dict(core)
3086 data["parent"] = "22"
3087 form = InventoryForm(data=data, instance=core)
3088 core = form.save()
3089 self.assertEqual(core.parent.name, "Pear")
3090
3091 class CategoryForm(forms.ModelForm):
3092 description = forms.CharField()
3093
3094 class Meta:
3095 model = Category
3096 fields = ["description", "url"]
3097
3098 self.assertEqual(list(CategoryForm.base_fields), ["description", "url"])
3099
3100 self.assertHTMLEqual(
3101 str(CategoryForm()),
3102 '<div><label for="id_description">Description:</label><input type="text" '
3103 'name="description" required id="id_description"></div><div>'
3104 '<label for="id_url">The URL:</label><input type="text" name="url" '
3105 'maxlength="40" required id="id_url"></div>',
3106 )
3107 # to_field_name should also work on ModelMultipleChoiceField ##################
3108
3109 field = forms.ModelMultipleChoiceField(
3110 Inventory.objects.all(), to_field_name="barcode"
3111 )
3112 self.assertEqual(
3113 tuple(field.choices), ((86, "Apple"), (87, "Core"), (22, "Pear"))
3114 )
3115 self.assertSequenceEqual(field.clean([86]), [apple])
3116
3117 form = SelectInventoryForm({"items": [87, 22]})
3118 self.assertTrue(form.is_valid())
3119 self.assertEqual(len(form.cleaned_data), 1)
3120 self.assertSequenceEqual(form.cleaned_data["items"], [core, pear])
3121
3122 def test_model_field_that_returns_none_to_exclude_itself_with_explicit_fields(self):
3123 self.assertEqual(list(CustomFieldForExclusionForm.base_fields), ["name"])
3124 self.assertHTMLEqual(
3125 str(CustomFieldForExclusionForm()),
3126 '<div><label for="id_name">Name:</label><input type="text" '
3127 'name="name" maxlength="10" required id="id_name"></div>',
3128 )
3129
3130 def test_iterable_model_m2m(self):
3131 class ColourfulItemForm(forms.ModelForm):
3132 class Meta:
3133 model = ColourfulItem
3134 fields = "__all__"
3135
3136 colour = Colour.objects.create(name="Blue")
3137 form = ColourfulItemForm()
3138 self.maxDiff = 1024
3139 self.assertHTMLEqual(
3140 form.as_p(),
3141 """
3142 <p>
3143 <label for="id_name">Name:</label>
3144 <input id="id_name" type="text" name="name" maxlength="50" required></p>
3145 <p><label for="id_colours">Colours:</label>
3146 <select multiple name="colours" id="id_colours" required>
3147 <option value="%(blue_pk)s">Blue</option>
3148 </select></p>
3149 """ % {"blue_pk": colour.pk},
3150 )
3151
3152 def test_callable_field_default(self):
3153 class PublicationDefaultsForm(forms.ModelForm):
3154 class Meta:
3155 model = PublicationDefaults
3156 fields = ("title", "date_published", "mode", "category")
3157
3158 self.maxDiff = 2000
3159 form = PublicationDefaultsForm()
3160 today_str = str(datetime.date.today())
3161 self.assertHTMLEqual(
3162 form.as_p(),
3163 """
3164 <p><label for="id_title">Title:</label>
3165 <input id="id_title" maxlength="30" name="title" type="text" required>
3166 </p>
3167 <p><label for="id_date_published">Date published:</label>
3168 <input id="id_date_published" name="date_published" type="text" value="{0}"
3169 required>
3170 <input id="initial-id_date_published" name="initial-date_published"
3171 type="hidden" value="{0}">
3172 </p>
3173 <p><label for="id_mode">Mode:</label> <select id="id_mode" name="mode">
3174 <option value="di" selected>direct</option>
3175 <option value="de">delayed</option></select>
3176 <input id="initial-id_mode" name="initial-mode" type="hidden" value="di">
3177 </p>
3178 <p>
3179 <label for="id_category">Category:</label>
3180 <select id="id_category" name="category">
3181 <option value="1">Games</option>
3182 <option value="2">Comics</option>
3183 <option value="3" selected>Novel</option></select>
3184 <input id="initial-id_category" name="initial-category" type="hidden"
3185 value="3">
3186 """.format(today_str),
3187 )
3188 empty_data = {
3189 "title": "",
3190 "date_published": today_str,
3191 "initial-date_published": today_str,
3192 "mode": "di",
3193 "initial-mode": "di",
3194 "category": "3",
3195 "initial-category": "3",
3196 }
3197 bound_form = PublicationDefaultsForm(empty_data)
3198 self.assertFalse(bound_form.has_changed())
3199
3200
3201 class ModelFormCustomErrorTests(SimpleTestCase):
3202 def test_custom_error_messages(self):
3203 data = {"name1": "@#$!!**@#$", "name2": "@#$!!**@#$"}
3204 errors = CustomErrorMessageForm(data).errors
3205 self.assertHTMLEqual(
3206 str(errors["name1"]),
3207 '<ul class="errorlist" id="id_name1_error">'
3208 "<li>Form custom error message.</li></ul>",
3209 )
3210 self.assertHTMLEqual(
3211 str(errors["name2"]),
3212 '<ul class="errorlist" id="id_name2_error">'
3213 "<li>Model custom error message.</li></ul>",
3214 )
3215
3216 def test_model_clean_error_messages(self):
3217 data = {"name1": "FORBIDDEN_VALUE", "name2": "ABC"}
3218 form = CustomErrorMessageForm(data)
3219 self.assertFalse(form.is_valid())
3220 self.assertHTMLEqual(
3221 str(form.errors["name1"]),
3222 '<ul class="errorlist" id="id_name1_error">'
3223 "<li>Model.clean() error messages.</li></ul>",
3224 )
3225 data = {"name1": "FORBIDDEN_VALUE2", "name2": "ABC"}
3226 form = CustomErrorMessageForm(data)
3227 self.assertFalse(form.is_valid())
3228 self.assertHTMLEqual(
3229 str(form.errors["name1"]),
3230 '<ul class="errorlist" id="id_name1_error">'
3231 "<li>Model.clean() error messages (simpler syntax).</li></ul>",
3232 )
3233 data = {"name1": "GLOBAL_ERROR", "name2": "ABC"}
3234 form = CustomErrorMessageForm(data)
3235 self.assertFalse(form.is_valid())
3236 self.assertEqual(form.errors["__all__"], ["Global error message."])
3237
3238
3239 class CustomCleanTests(TestCase):
3240 def test_override_clean(self):
3241 """
3242 Regression for #12596: Calling super from ModelForm.clean() should be
3243 optional.
3244 """
3245
3246 class TripleFormWithCleanOverride(forms.ModelForm):
3247 class Meta:
3248 model = Triple
3249 fields = "__all__"
3250
3251 def clean(self):
3252 if not self.cleaned_data["left"] == self.cleaned_data["right"]:
3253 raise ValidationError("Left and right should be equal")
3254 return self.cleaned_data
3255
3256 form = TripleFormWithCleanOverride({"left": 1, "middle": 2, "right": 1})
3257 self.assertTrue(form.is_valid())
3258 # form.instance.left will be None if the instance was not constructed
3259 # by form.full_clean().
3260 self.assertEqual(form.instance.left, 1)
3261
3262 def test_model_form_clean_applies_to_model(self):
3263 """
3264 Regression test for #12960. Make sure the cleaned_data returned from
3265 ModelForm.clean() is applied to the model instance.
3266 """
3267
3268 class CategoryForm(forms.ModelForm):
3269 class Meta:
3270 model = Category
3271 fields = "__all__"
3272
3273 def clean(self):
3274 self.cleaned_data["name"] = self.cleaned_data["name"].upper()
3275 return self.cleaned_data
3276
3277 data = {"name": "Test", "slug": "test", "url": "/test"}
3278 form = CategoryForm(data)
3279 category = form.save()
3280 self.assertEqual(category.name, "TEST")
3281
3282
3283 class ModelFormInheritanceTests(SimpleTestCase):
3284 def test_form_subclass_inheritance(self):
3285 class Form(forms.Form):
3286 age = forms.IntegerField()
3287
3288 class ModelForm(forms.ModelForm, Form):
3289 class Meta:
3290 model = Writer
3291 fields = "__all__"
3292
3293 self.assertEqual(list(ModelForm().fields), ["name", "age"])
3294
3295 def test_field_removal(self):
3296 class ModelForm(forms.ModelForm):
3297 class Meta:
3298 model = Writer
3299 fields = "__all__"
3300
3301 class Mixin:
3302 age = None
3303
3304 class Form(forms.Form):
3305 age = forms.IntegerField()
3306
3307 class Form2(forms.Form):
3308 foo = forms.IntegerField()
3309
3310 self.assertEqual(list(ModelForm().fields), ["name"])
3311 self.assertEqual(list(type("NewForm", (Mixin, Form), {})().fields), [])
3312 self.assertEqual(
3313 list(type("NewForm", (Form2, Mixin, Form), {})().fields), ["foo"]
3314 )
3315 self.assertEqual(
3316 list(type("NewForm", (Mixin, ModelForm, Form), {})().fields), ["name"]
3317 )
3318 self.assertEqual(
3319 list(type("NewForm", (ModelForm, Mixin, Form), {})().fields), ["name"]
3320 )
3321 self.assertEqual(
3322 list(type("NewForm", (ModelForm, Form, Mixin), {})().fields),
3323 ["name", "age"],
3324 )
3325 self.assertEqual(
3326 list(type("NewForm", (ModelForm, Form), {"age": None})().fields), ["name"]
3327 )
3328
3329 def test_field_removal_name_clashes(self):
3330 """
3331 Form fields can be removed in subclasses by setting them to None
3332 (#22510).
3333 """
3334
3335 class MyForm(forms.ModelForm):
3336 media = forms.CharField()
3337
3338 class Meta:
3339 model = Writer
3340 fields = "__all__"
3341
3342 class SubForm(MyForm):
3343 media = None
3344
3345 self.assertIn("media", MyForm().fields)
3346 self.assertNotIn("media", SubForm().fields)
3347 self.assertTrue(hasattr(MyForm, "media"))
3348 self.assertTrue(hasattr(SubForm, "media"))
3349
3350
3351 class StumpJokeForm(forms.ModelForm):
3352 class Meta:
3353 model = StumpJoke
3354 fields = "__all__"
3355
3356
3357 class CustomFieldWithQuerysetButNoLimitChoicesTo(forms.Field):
3358 queryset = 42
3359
3360
3361 class StumpJokeWithCustomFieldForm(forms.ModelForm):
3362 custom = CustomFieldWithQuerysetButNoLimitChoicesTo()
3363
3364 class Meta:
3365 model = StumpJoke
3366 fields = ()
3367
3368
3369 class LimitChoicesToTests(TestCase):
3370 """
3371 Tests the functionality of ``limit_choices_to``.
3372 """
3373
3374 @classmethod
3375 def setUpTestData(cls):
3376 cls.threepwood = Character.objects.create(
3377 username="threepwood",
3378 last_action=datetime.datetime.today() + datetime.timedelta(days=1),
3379 )
3380 cls.marley = Character.objects.create(
3381 username="marley",
3382 last_action=datetime.datetime.today() - datetime.timedelta(days=1),
3383 )
3384
3385 def test_limit_choices_to_callable_for_fk_rel(self):
3386 """
3387 A ForeignKey can use limit_choices_to as a callable (#2554).
3388 """
3389 stumpjokeform = StumpJokeForm()
3390 self.assertSequenceEqual(
3391 stumpjokeform.fields["most_recently_fooled"].queryset, [self.threepwood]
3392 )
3393
3394 def test_limit_choices_to_callable_for_m2m_rel(self):
3395 """
3396 A ManyToManyField can use limit_choices_to as a callable (#2554).
3397 """
3398 stumpjokeform = StumpJokeForm()
3399 self.assertSequenceEqual(
3400 stumpjokeform.fields["most_recently_fooled"].queryset, [self.threepwood]
3401 )
3402
3403 def test_custom_field_with_queryset_but_no_limit_choices_to(self):
3404 """
3405 A custom field with a `queryset` attribute but no `limit_choices_to`
3406 works (#23795).
3407 """
3408 f = StumpJokeWithCustomFieldForm()
3409 self.assertEqual(f.fields["custom"].queryset, 42)
3410
3411 def test_fields_for_model_applies_limit_choices_to(self):
3412 fields = fields_for_model(StumpJoke, ["has_fooled_today"])
3413 self.assertSequenceEqual(fields["has_fooled_today"].queryset, [self.threepwood])
3414
3415 def test_callable_called_each_time_form_is_instantiated(self):
3416 field = StumpJokeForm.base_fields["most_recently_fooled"]
3417 with mock.patch.object(field, "limit_choices_to") as today_callable_dict:
3418 StumpJokeForm()
3419 self.assertEqual(today_callable_dict.call_count, 1)
3420 StumpJokeForm()
3421 self.assertEqual(today_callable_dict.call_count, 2)
3422 StumpJokeForm()
3423 self.assertEqual(today_callable_dict.call_count, 3)
3424
3425 @isolate_apps("model_forms")
3426 def test_limit_choices_to_no_duplicates(self):
3427 joke1 = StumpJoke.objects.create(
3428 funny=True,
3429 most_recently_fooled=self.threepwood,
3430 )
3431 joke2 = StumpJoke.objects.create(
3432 funny=True,
3433 most_recently_fooled=self.threepwood,
3434 )
3435 joke3 = StumpJoke.objects.create(
3436 funny=True,
3437 most_recently_fooled=self.marley,
3438 )
3439 StumpJoke.objects.create(funny=False, most_recently_fooled=self.marley)
3440 joke1.has_fooled_today.add(self.marley, self.threepwood)
3441 joke2.has_fooled_today.add(self.marley)
3442 joke3.has_fooled_today.add(self.marley, self.threepwood)
3443
3444 class CharacterDetails(models.Model):
3445 character1 = models.ForeignKey(
3446 Character,
3447 models.CASCADE,
3448 limit_choices_to=models.Q(
3449 jokes__funny=True,
3450 jokes_today__funny=True,
3451 ),
3452 related_name="details_fk_1",
3453 )
3454 character2 = models.ForeignKey(
3455 Character,
3456 models.CASCADE,
3457 limit_choices_to={
3458 "jokes__funny": True,
3459 "jokes_today__funny": True,
3460 },
3461 related_name="details_fk_2",
3462 )
3463 character3 = models.ManyToManyField(
3464 Character,
3465 limit_choices_to=models.Q(
3466 jokes__funny=True,
3467 jokes_today__funny=True,
3468 ),
3469 related_name="details_m2m_1",
3470 )
3471
3472 class CharacterDetailsForm(forms.ModelForm):
3473 class Meta:
3474 model = CharacterDetails
3475 fields = "__all__"
3476
3477 form = CharacterDetailsForm()
3478 self.assertCountEqual(
3479 form.fields["character1"].queryset,
3480 [self.marley, self.threepwood],
3481 )
3482 self.assertCountEqual(
3483 form.fields["character2"].queryset,
3484 [self.marley, self.threepwood],
3485 )
3486 self.assertCountEqual(
3487 form.fields["character3"].queryset,
3488 [self.marley, self.threepwood],
3489 )
3490
3491 def test_limit_choices_to_m2m_through(self):
3492 class DiceForm(forms.ModelForm):
3493 class Meta:
3494 model = Dice
3495 fields = ["numbers"]
3496
3497 Number.objects.create(value=0)
3498 n1 = Number.objects.create(value=1)
3499 n2 = Number.objects.create(value=2)
3500
3501 form = DiceForm()
3502 self.assertCountEqual(form.fields["numbers"].queryset, [n1, n2])
3503
3504
3505 class FormFieldCallbackTests(SimpleTestCase):
3506 def test_baseform_with_widgets_in_meta(self):
3507 """
3508 Using base forms with widgets defined in Meta should not raise errors.
3509 """
3510 widget = forms.Textarea()
3511
3512 class BaseForm(forms.ModelForm):
3513 class Meta:
3514 model = Person
3515 widgets = {"name": widget}
3516 fields = "__all__"
3517
3518 Form = modelform_factory(Person, form=BaseForm)
3519 self.assertIsInstance(Form.base_fields["name"].widget, forms.Textarea)
3520
3521 def test_factory_with_widget_argument(self):
3522 """Regression for #15315: modelform_factory should accept widgets
3523 argument
3524 """
3525 widget = forms.Textarea()
3526
3527 # Without a widget should not set the widget to textarea
3528 Form = modelform_factory(Person, fields="__all__")
3529 self.assertNotEqual(Form.base_fields["name"].widget.__class__, forms.Textarea)
3530
3531 # With a widget should not set the widget to textarea
3532 Form = modelform_factory(Person, fields="__all__", widgets={"name": widget})
3533 self.assertEqual(Form.base_fields["name"].widget.__class__, forms.Textarea)
3534
3535 def test_modelform_factory_without_fields(self):
3536 """Regression for #19733"""
3537 message = (
3538 "Calling modelform_factory without defining 'fields' or 'exclude' "
3539 "explicitly is prohibited."
3540 )
3541 with self.assertRaisesMessage(ImproperlyConfigured, message):
3542 modelform_factory(Person)
3543
3544 def test_modelform_factory_with_all_fields(self):
3545 """Regression for #19733"""
3546 form = modelform_factory(Person, fields="__all__")
3547 self.assertEqual(list(form.base_fields), ["name"])
3548
3549 def test_custom_callback(self):
3550 """A custom formfield_callback is used if provided"""
3551 callback_args = []
3552
3553 def callback(db_field, **kwargs):
3554 callback_args.append((db_field, kwargs))
3555 return db_field.formfield(**kwargs)
3556
3557 widget = forms.Textarea()
3558
3559 class BaseForm(forms.ModelForm):
3560 class Meta:
3561 model = Person
3562 widgets = {"name": widget}
3563 fields = "__all__"
3564
3565 modelform_factory(Person, form=BaseForm, formfield_callback=callback)
3566 id_field, name_field = Person._meta.fields
3567
3568 self.assertEqual(
3569 callback_args, [(id_field, {}), (name_field, {"widget": widget})]
3570 )
3571
3572 def test_bad_callback(self):
3573 # A bad callback provided by user still gives an error
3574 with self.assertRaises(TypeError):
3575 modelform_factory(
3576 Person,
3577 fields="__all__",
3578 formfield_callback="not a function or callable",
3579 )
3580
3581 def test_inherit_after_custom_callback(self):
3582 def callback(db_field, **kwargs):
3583 if isinstance(db_field, models.CharField):
3584 return forms.CharField(widget=forms.Textarea)
3585 return db_field.formfield(**kwargs)
3586
3587 class BaseForm(forms.ModelForm):
3588 class Meta:
3589 model = Person
3590 fields = "__all__"
3591
3592 NewForm = modelform_factory(Person, form=BaseForm, formfield_callback=callback)
3593
3594 class InheritedForm(NewForm):
3595 pass
3596
3597 for name in NewForm.base_fields:
3598 self.assertEqual(
3599 type(InheritedForm.base_fields[name].widget),
3600 type(NewForm.base_fields[name].widget),
3601 )
3602
3603 def test_custom_callback_in_meta(self):
3604 def callback(db_field, **kwargs):
3605 return forms.CharField(widget=forms.Textarea)
3606
3607 class NewForm(forms.ModelForm):
3608 class Meta:
3609 model = Person
3610 fields = ["id", "name"]
3611 formfield_callback = callback
3612
3613 for field in NewForm.base_fields.values():
3614 self.assertEqual(type(field.widget), forms.Textarea)
3615
3616 def test_custom_callback_from_base_form_meta(self):
3617 def callback(db_field, **kwargs):
3618 return forms.CharField(widget=forms.Textarea)
3619
3620 class BaseForm(forms.ModelForm):
3621 class Meta:
3622 model = Person
3623 fields = "__all__"
3624 formfield_callback = callback
3625
3626 NewForm = modelform_factory(model=Person, form=BaseForm)
3627
3628 class InheritedForm(NewForm):
3629 pass
3630
3631 for name, field in NewForm.base_fields.items():
3632 self.assertEqual(type(field.widget), forms.Textarea)
3633 self.assertEqual(
3634 type(field.widget),
3635 type(InheritedForm.base_fields[name].widget),
3636 )
3637
3638
3639 class LocalizedModelFormTest(TestCase):
3640 def test_model_form_applies_localize_to_some_fields(self):
3641 class PartiallyLocalizedTripleForm(forms.ModelForm):
3642 class Meta:
3643 model = Triple
3644 localized_fields = (
3645 "left",
3646 "right",
3647 )
3648 fields = "__all__"
3649
3650 f = PartiallyLocalizedTripleForm({"left": 10, "middle": 10, "right": 10})
3651 self.assertTrue(f.is_valid())
3652 self.assertTrue(f.fields["left"].localize)
3653 self.assertFalse(f.fields["middle"].localize)
3654 self.assertTrue(f.fields["right"].localize)
3655
3656 def test_model_form_applies_localize_to_all_fields(self):
3657 class FullyLocalizedTripleForm(forms.ModelForm):
3658 class Meta:
3659 model = Triple
3660 localized_fields = "__all__"
3661 fields = "__all__"
3662
3663 f = FullyLocalizedTripleForm({"left": 10, "middle": 10, "right": 10})
3664 self.assertTrue(f.is_valid())
3665 self.assertTrue(f.fields["left"].localize)
3666 self.assertTrue(f.fields["middle"].localize)
3667 self.assertTrue(f.fields["right"].localize)
3668
3669 def test_model_form_refuses_arbitrary_string(self):
3670 msg = (
3671 "BrokenLocalizedTripleForm.Meta.localized_fields "
3672 "cannot be a string. Did you mean to type: ('foo',)?"
3673 )
3674 with self.assertRaisesMessage(TypeError, msg):
3675
3676 class BrokenLocalizedTripleForm(forms.ModelForm):
3677 class Meta:
3678 model = Triple
3679 localized_fields = "foo"
3680
3681
3682 class CustomMetaclass(ModelFormMetaclass):
3683 def __new__(cls, name, bases, attrs):
3684 new = super().__new__(cls, name, bases, attrs)
3685 new.base_fields = {}
3686 return new
3687
3688
3689 class CustomMetaclassForm(forms.ModelForm, metaclass=CustomMetaclass):
3690 pass
3691
3692
3693 class CustomMetaclassTestCase(SimpleTestCase):
3694 def test_modelform_factory_metaclass(self):
3695 new_cls = modelform_factory(Person, fields="__all__", form=CustomMetaclassForm)
3696 self.assertEqual(new_cls.base_fields, {})
3697
3698
3699 class StrictAssignmentTests(SimpleTestCase):
3700 """
3701 Should a model do anything special with __setattr__() or descriptors which
3702 raise a ValidationError, a model form should catch the error (#24706).
3703 """
3704
3705 def test_setattr_raises_validation_error_field_specific(self):
3706 """
3707 A model ValidationError using the dict form should put the error
3708 message into the correct key of form.errors.
3709 """
3710 form_class = modelform_factory(
3711 model=StrictAssignmentFieldSpecific, fields=["title"]
3712 )
3713 form = form_class(data={"title": "testing setattr"}, files=None)
3714 # This line turns on the ValidationError; it avoids the model erroring
3715 # when its own __init__() is called when creating form.instance.
3716 form.instance._should_error = True
3717 self.assertFalse(form.is_valid())
3718 self.assertEqual(
3719 form.errors,
3720 {"title": ["Cannot set attribute", "This field cannot be blank."]},
3721 )
3722
3723 def test_setattr_raises_validation_error_non_field(self):
3724 """
3725 A model ValidationError not using the dict form should put the error
3726 message into __all__ (i.e. non-field errors) on the form.
3727 """
3728 form_class = modelform_factory(model=StrictAssignmentAll, fields=["title"])
3729 form = form_class(data={"title": "testing setattr"}, files=None)
3730 # This line turns on the ValidationError; it avoids the model erroring
3731 # when its own __init__() is called when creating form.instance.
3732 form.instance._should_error = True
3733 self.assertFalse(form.is_valid())
3734 self.assertEqual(
3735 form.errors,
3736 {
3737 "__all__": ["Cannot set attribute"],
3738 "title": ["This field cannot be blank."],
3739 },
3740 )
3741
3742
3743 class ModelToDictTests(TestCase):
3744 def test_many_to_many(self):
3745 """Data for a ManyToManyField is a list rather than a lazy QuerySet."""
3746 blue = Colour.objects.create(name="blue")
3747 red = Colour.objects.create(name="red")
3748 item = ColourfulItem.objects.create()
3749 item.colours.set([blue])
3750 data = model_to_dict(item)["colours"]
3751 self.assertEqual(data, [blue])
3752 item.colours.set([red])
3753 # If data were a QuerySet, it would be reevaluated here and give "red"
3754 # instead of the original value.
3755 self.assertEqual(data, [blue])