""",
+ )
+
+ def test_initial_values(self):
+ self.create_basic_data()
+ # Initial values can be provided for model forms
+ f = ArticleForm(
+ auto_id=False,
+ initial={
+ "headline": "Your headline here",
+ "categories": [str(self.c1.id), str(self.c2.id)],
+ },
+ )
+ self.assertHTMLEqual(
+ f.as_ul(),
+ """
+
Headline:
+
+
+
Slug:
+
Pub date:
+
Writer:
+
Article:
+
+
Categories:
+
Status:
+ """
+ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
+ )
+
+ # When the ModelForm is passed an instance, that instance's current values are
+ # inserted as 'initial' data in each Field.
+ f = RoykoForm(auto_id=False, instance=self.w_royko)
+ self.assertHTMLEqual(
+ str(f),
+ '
+ """
+ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
+ )
+
+ f = ArticleForm(
+ {
+ "headline": "Test headline",
+ "slug": "test-headline",
+ "pub_date": "1984-02-06",
+ "writer": str(self.w_royko.pk),
+ "article": "Hello.",
+ },
+ instance=art,
+ )
+ self.assertEqual(f.errors, {})
+ self.assertTrue(f.is_valid())
+ test_art = f.save()
+ self.assertEqual(test_art.id, art_id_1)
+ test_art = Article.objects.get(id=art_id_1)
+ self.assertEqual(test_art.headline, "Test headline")
+
+ def test_m2m_initial_callable(self):
+ """
+ A callable can be provided as the initial value for an m2m field.
+ """
+ self.maxDiff = 1200
+ self.create_basic_data()
+
+ # Set up a callable initial value
+ def formfield_for_dbfield(db_field, **kwargs):
+ if db_field.name == "categories":
+ kwargs["initial"] = lambda: Category.objects.order_by("name")[:2]
+ return db_field.formfield(**kwargs)
+
+ # Create a ModelForm, instantiate it, and check that the output is as expected
+ ModelForm = modelform_factory(
+ Article,
+ fields=["headline", "categories"],
+ formfield_callback=formfield_for_dbfield,
+ )
+ form = ModelForm()
+ self.assertHTMLEqual(
+ form.as_ul(),
+ """
+
+
+
"""
+ % (self.c1.pk, self.c2.pk, self.c3.pk),
+ )
+
+ def test_basic_creation(self):
+ self.assertEqual(Category.objects.count(), 0)
+ f = BaseCategoryForm(
+ {
+ "name": "Entertainment",
+ "slug": "entertainment",
+ "url": "entertainment",
+ }
+ )
+ self.assertTrue(f.is_valid())
+ self.assertEqual(f.cleaned_data["name"], "Entertainment")
+ self.assertEqual(f.cleaned_data["slug"], "entertainment")
+ self.assertEqual(f.cleaned_data["url"], "entertainment")
+ c1 = f.save()
+ # Testing whether the same object is returned from the
+ # ORM... not the fastest way...
+
+ self.assertEqual(Category.objects.count(), 1)
+ self.assertEqual(c1, Category.objects.all()[0])
+ self.assertEqual(c1.name, "Entertainment")
+
+ def test_save_commit_false(self):
+ # If you call save() with commit=False, then it will return an object that
+ # hasn't yet been saved to the database. In this case, it's up to you to call
+ # save() on the resulting model instance.
+ f = BaseCategoryForm(
+ {"name": "Third test", "slug": "third-test", "url": "third"}
+ )
+ self.assertTrue(f.is_valid())
+ c1 = f.save(commit=False)
+ self.assertEqual(c1.name, "Third test")
+ self.assertEqual(Category.objects.count(), 0)
+ c1.save()
+ self.assertEqual(Category.objects.count(), 1)
+
+ def test_save_with_data_errors(self):
+ # If you call save() with invalid data, you'll get a ValueError.
+ f = BaseCategoryForm({"name": "", "slug": "not a slug!", "url": "foo"})
+ self.assertEqual(f.errors["name"], ["This field is required."])
+ self.assertEqual(
+ f.errors["slug"],
+ [
+ "Enter a valid “slug” consisting of letters, numbers, underscores or "
+ "hyphens."
+ ],
+ )
+ self.assertEqual(f.cleaned_data, {"url": "foo"})
+ msg = "The Category could not be created because the data didn't validate."
+ with self.assertRaisesMessage(ValueError, msg):
+ f.save()
+ f = BaseCategoryForm({"name": "", "slug": "", "url": "foo"})
+ with self.assertRaisesMessage(ValueError, msg):
+ f.save()
+
+ def test_multi_fields(self):
+ self.create_basic_data()
+ self.maxDiff = None
+ # ManyToManyFields are represented by a MultipleChoiceField, ForeignKeys and any
+ # fields with the 'choices' attribute are represented by a ChoiceField.
+ f = ArticleForm(auto_id=False)
+ self.assertHTMLEqual(
+ str(f),
+ """
+
Headline:
+
+
+
Slug:
+
+
+
Pub date:
+
+
+
Writer:
+
+
+
Article:
+
+
+
Categories:
+
+
+
Status:
+
+
+ """
+ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
+ )
+
+ # Add some categories and test the many-to-many form output.
+ new_art = Article.objects.create(
+ article="Hello.",
+ headline="New headline",
+ slug="new-headline",
+ pub_date=datetime.date(1988, 1, 4),
+ writer=self.w_royko,
+ )
+ new_art.categories.add(Category.objects.get(name="Entertainment"))
+ self.assertSequenceEqual(new_art.categories.all(), [self.c1])
+ f = ArticleForm(auto_id=False, instance=new_art)
+ self.assertHTMLEqual(
+ f.as_ul(),
+ """
+
Headline:
+
+
+
Slug:
+
+
+
Pub date:
+
+
Writer:
+
Article:
+
+
Categories:
+
Status:
+ """
+ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
+ )
+
+ def test_subset_fields(self):
+ # You can restrict a form to a subset of the complete list of fields
+ # by providing a 'fields' argument. If you try to save a
+ # model created with such a form, you need to ensure that the fields
+ # that are _not_ on the form have default values, or are allowed to have
+ # a value of None. If a field isn't specified on a form, the object created
+ # from the form can't provide a value for that field!
+ class PartialArticleForm(forms.ModelForm):
+ class Meta:
+ model = Article
+ fields = ("headline", "pub_date")
+
+ f = PartialArticleForm(auto_id=False)
+ self.assertHTMLEqual(
+ str(f),
+ '
+ """,
+ )
+ self.assertTrue(f.is_valid())
+ new_art = f.save()
+ self.assertEqual(new_art.id, art.id)
+ new_art = Article.objects.get(id=art.id)
+ self.assertEqual(new_art.headline, "New headline")
+
+ def test_m2m_editing(self):
+ self.create_basic_data()
+ form_data = {
+ "headline": "New headline",
+ "slug": "new-headline",
+ "pub_date": "1988-01-04",
+ "writer": str(self.w_royko.pk),
+ "article": "Hello.",
+ "categories": [str(self.c1.id), str(self.c2.id)],
+ }
+ # Create a new article, with categories, via the form.
+ f = ArticleForm(form_data)
+ new_art = f.save()
+ new_art = Article.objects.get(id=new_art.id)
+ art_id_1 = new_art.id
+ self.assertSequenceEqual(
+ new_art.categories.order_by("name"), [self.c1, self.c2]
+ )
+
+ # Now, submit form data with no categories. This deletes the existing
+ # categories.
+ form_data["categories"] = []
+ f = ArticleForm(form_data, instance=new_art)
+ new_art = f.save()
+ self.assertEqual(new_art.id, art_id_1)
+ new_art = Article.objects.get(id=art_id_1)
+ self.assertSequenceEqual(new_art.categories.all(), [])
+
+ # Create a new article, with no categories, via the form.
+ f = ArticleForm(form_data)
+ new_art = f.save()
+ art_id_2 = new_art.id
+ self.assertNotIn(art_id_2, (None, art_id_1))
+ new_art = Article.objects.get(id=art_id_2)
+ self.assertSequenceEqual(new_art.categories.all(), [])
+
+ # Create a new article, with categories, via the form, but use commit=False.
+ # The m2m data won't be saved until save_m2m() is invoked on the form.
+ form_data["categories"] = [str(self.c1.id), str(self.c2.id)]
+ f = ArticleForm(form_data)
+ new_art = f.save(commit=False)
+
+ # Manually save the instance
+ new_art.save()
+ art_id_3 = new_art.id
+ self.assertNotIn(art_id_3, (None, art_id_1, art_id_2))
+
+ # The instance doesn't have m2m data yet
+ new_art = Article.objects.get(id=art_id_3)
+ self.assertSequenceEqual(new_art.categories.all(), [])
+
+ # Save the m2m data on the form
+ f.save_m2m()
+ self.assertSequenceEqual(
+ new_art.categories.order_by("name"), [self.c1, self.c2]
+ )
+
+ def test_custom_form_fields(self):
+ # Here, we define a custom ModelForm. Because it happens to have the
+ # same fields as the Category model, we can just call the form's save()
+ # to apply its changes to an existing Category instance.
+ class ShortCategory(forms.ModelForm):
+ name = forms.CharField(max_length=5)
+ slug = forms.CharField(max_length=5)
+ url = forms.CharField(max_length=3)
+
+ class Meta:
+ model = Category
+ fields = "__all__"
+
+ cat = Category.objects.create(name="Third test")
+ form = ShortCategory(
+ {"name": "Third", "slug": "third", "url": "3rd"}, instance=cat
+ )
+ self.assertEqual(form.save().name, "Third")
+ self.assertEqual(Category.objects.get(id=cat.id).name, "Third")
+
+ def test_runtime_choicefield_populated(self):
+ self.maxDiff = None
+ # Here, we demonstrate that choices for a ForeignKey ChoiceField are determined
+ # at runtime, based on the data in the database when the form is displayed, not
+ # the data in the database when the form is instantiated.
+ self.create_basic_data()
+ f = ArticleForm(auto_id=False)
+ self.assertHTMLEqual(
+ f.as_ul(),
+ '
"""
+ % (
+ self.w_woodward.pk,
+ self.w_royko.pk,
+ ),
+ )
+
+ def test_assignment_of_none(self):
+ class AuthorForm(forms.ModelForm):
+ class Meta:
+ model = Author
+ fields = ["publication", "full_name"]
+
+ publication = Publication.objects.create(
+ title="Pravda", date_published=datetime.date(1991, 8, 22)
+ )
+ author = Author.objects.create(publication=publication, full_name="John Doe")
+ form = AuthorForm({"publication": "", "full_name": "John Doe"}, instance=author)
+ self.assertTrue(form.is_valid())
+ self.assertIsNone(form.cleaned_data["publication"])
+ author = form.save()
+ # author object returned from form still retains original publication object
+ # that's why we need to retrieve it from database again
+ new_author = Author.objects.get(pk=author.pk)
+ self.assertIsNone(new_author.publication)
+
+ def test_assignment_of_none_null_false(self):
+ class AuthorForm(forms.ModelForm):
+ class Meta:
+ model = Author1
+ fields = ["publication", "full_name"]
+
+ publication = Publication.objects.create(
+ title="Pravda", date_published=datetime.date(1991, 8, 22)
+ )
+ author = Author1.objects.create(publication=publication, full_name="John Doe")
+ form = AuthorForm({"publication": "", "full_name": "John Doe"}, instance=author)
+ self.assertFalse(form.is_valid())
+
+
+class FileAndImageFieldTests(TestCase):
+ def test_clean_false(self):
+ """
+ If the ``clean`` method on a non-required FileField receives False as
+ the data (meaning clear the field value), it returns False, regardless
+ of the value of ``initial``.
+ """
+ f = forms.FileField(required=False)
+ self.assertIs(f.clean(False), False)
+ self.assertIs(f.clean(False, "initial"), False)
+
+ def test_clean_false_required(self):
+ """
+ If the ``clean`` method on a required FileField receives False as the
+ data, it has the same effect as None: initial is returned if non-empty,
+ otherwise the validation catches the lack of a required value.
+ """
+ f = forms.FileField(required=True)
+ self.assertEqual(f.clean(False, "initial"), "initial")
+ with self.assertRaises(ValidationError):
+ f.clean(False)
+
+ def test_full_clear(self):
+ """
+ Integration happy-path test that a model FileField can actually be set
+ and cleared via a ModelForm.
+ """
+
+ class DocumentForm(forms.ModelForm):
+ class Meta:
+ model = Document
+ fields = "__all__"
+
+ form = DocumentForm()
+ self.assertIn('name="myfile"', str(form))
+ self.assertNotIn("myfile-clear", str(form))
+ form = DocumentForm(
+ files={"myfile": SimpleUploadedFile("something.txt", b"content")}
+ )
+ self.assertTrue(form.is_valid())
+ doc = form.save(commit=False)
+ self.assertEqual(doc.myfile.name, "something.txt")
+ form = DocumentForm(instance=doc)
+ self.assertIn("myfile-clear", str(form))
+ form = DocumentForm(instance=doc, data={"myfile-clear": "true"})
+ doc = form.save(commit=False)
+ self.assertFalse(doc.myfile)
+
+ def test_clear_and_file_contradiction(self):
+ """
+ If the user submits a new file upload AND checks the clear checkbox,
+ they get a validation error, and the bound redisplay of the form still
+ includes the current file and the clear checkbox.
+ """
+
+ class DocumentForm(forms.ModelForm):
+ class Meta:
+ model = Document
+ fields = "__all__"
+
+ form = DocumentForm(
+ files={"myfile": SimpleUploadedFile("something.txt", b"content")}
+ )
+ self.assertTrue(form.is_valid())
+ doc = form.save(commit=False)
+ form = DocumentForm(
+ instance=doc,
+ files={"myfile": SimpleUploadedFile("something.txt", b"content")},
+ data={"myfile-clear": "true"},
+ )
+ self.assertTrue(not form.is_valid())
+ self.assertEqual(
+ form.errors["myfile"],
+ ["Please either submit a file or check the clear checkbox, not both."],
+ )
+ rendered = str(form)
+ self.assertIn("something.txt", rendered)
+ self.assertIn("myfile-clear", rendered)
+
+ def test_render_empty_file_field(self):
+ class DocumentForm(forms.ModelForm):
+ class Meta:
+ model = Document
+ fields = "__all__"
+
+ doc = Document.objects.create()
+ form = DocumentForm(instance=doc)
+ self.assertHTMLEqual(
+ str(form["myfile"]), ''
+ )
+
+ def test_file_field_data(self):
+ # Test conditions when files is either not given or empty.
+ f = TextFileForm(data={"description": "Assistance"})
+ self.assertFalse(f.is_valid())
+ f = TextFileForm(data={"description": "Assistance"}, files={})
+ self.assertFalse(f.is_valid())
+
+ # Upload a file and ensure it all works as expected.
+ f = TextFileForm(
+ data={"description": "Assistance"},
+ files={"file": SimpleUploadedFile("test1.txt", b"hello world")},
+ )
+ self.assertTrue(f.is_valid())
+ self.assertEqual(type(f.cleaned_data["file"]), SimpleUploadedFile)
+ instance = f.save()
+ self.assertEqual(instance.file.name, "tests/test1.txt")
+ instance.file.delete()
+
+ # If the previous file has been deleted, the file name can be reused
+ f = TextFileForm(
+ data={"description": "Assistance"},
+ files={"file": SimpleUploadedFile("test1.txt", b"hello world")},
+ )
+ self.assertTrue(f.is_valid())
+ self.assertEqual(type(f.cleaned_data["file"]), SimpleUploadedFile)
+ instance = f.save()
+ self.assertEqual(instance.file.name, "tests/test1.txt")
+
+ # Check if the max_length attribute has been inherited from the model.
+ f = TextFileForm(
+ data={"description": "Assistance"},
+ files={"file": SimpleUploadedFile("test-maxlength.txt", b"hello world")},
+ )
+ self.assertFalse(f.is_valid())
+
+ # Edit an instance that already has the file defined in the model. This will not
+ # save the file again, but leave it exactly as it is.
+ f = TextFileForm({"description": "Assistance"}, instance=instance)
+ self.assertTrue(f.is_valid())
+ self.assertEqual(f.cleaned_data["file"].name, "tests/test1.txt")
+ instance = f.save()
+ self.assertEqual(instance.file.name, "tests/test1.txt")
+
+ # Delete the current file since this is not done by Django.
+ instance.file.delete()
+
+ # Override the file by uploading a new one.
+ f = TextFileForm(
+ data={"description": "Assistance"},
+ files={"file": SimpleUploadedFile("test2.txt", b"hello world")},
+ instance=instance,
+ )
+ self.assertTrue(f.is_valid())
+ instance = f.save()
+ self.assertEqual(instance.file.name, "tests/test2.txt")
+
+ # Delete the current file since this is not done by Django.
+ instance.file.delete()
+ instance.delete()
+
+ def test_filefield_required_false(self):
+ # Test the non-required FileField
+ f = TextFileForm(data={"description": "Assistance"})
+ f.fields["file"].required = False
+ self.assertTrue(f.is_valid())
+ instance = f.save()
+ self.assertEqual(instance.file.name, "")
+
+ f = TextFileForm(
+ data={"description": "Assistance"},
+ files={"file": SimpleUploadedFile("test3.txt", b"hello world")},
+ instance=instance,
+ )
+ self.assertTrue(f.is_valid())
+ instance = f.save()
+ self.assertEqual(instance.file.name, "tests/test3.txt")
+
+ # Instance can be edited w/out re-uploading the file and existing file
+ # should be preserved.
+ f = TextFileForm({"description": "New Description"}, instance=instance)
+ f.fields["file"].required = False
+ self.assertTrue(f.is_valid())
+ instance = f.save()
+ self.assertEqual(instance.description, "New Description")
+ self.assertEqual(instance.file.name, "tests/test3.txt")
+
+ # Delete the current file since this is not done by Django.
+ instance.file.delete()
+ instance.delete()
+
+ def test_custom_file_field_save(self):
+ """
+ Regression for #11149: save_form_data should be called only once
+ """
+
+ class CFFForm(forms.ModelForm):
+ class Meta:
+ model = CustomFF
+ fields = "__all__"
+
+ # It's enough that the form saves without error -- the custom save routine will
+ # generate an AssertionError if it is called more than once during save.
+ form = CFFForm(data={"f": None})
+ form.save()
+
+ def test_file_field_multiple_save(self):
+ """
+ Simulate a file upload and check how many times Model.save() gets
+ called. Test for bug #639.
+ """
+
+ class PhotoForm(forms.ModelForm):
+ class Meta:
+ model = Photo
+ fields = "__all__"
+
+ # Grab an image for testing.
+ filename = os.path.join(os.path.dirname(__file__), "test.png")
+ with open(filename, "rb") as fp:
+ img = fp.read()
+
+ # Fake a POST QueryDict and FILES MultiValueDict.
+ data = {"title": "Testing"}
+ files = {"image": SimpleUploadedFile("test.png", img, "image/png")}
+
+ form = PhotoForm(data=data, files=files)
+ p = form.save()
+
+ try:
+ # Check the savecount stored on the object (see the model).
+ self.assertEqual(p._savecount, 1)
+ finally:
+ # Delete the "uploaded" file to avoid clogging /tmp.
+ p = Photo.objects.get()
+ p.image.delete(save=False)
+
+ def test_file_path_field_blank(self):
+ """FilePathField(blank=True) includes the empty option."""
+
+ class FPForm(forms.ModelForm):
+ class Meta:
+ model = FilePathModel
+ fields = "__all__"
+
+ form = FPForm()
+ self.assertEqual(
+ [name for _, name in form["path"].field.choices], ["---------", "models.py"]
+ )
+
+ @skipUnless(test_images, "Pillow not installed")
+ def test_image_field(self):
+ # ImageField and FileField are nearly identical, but they differ slightly when
+ # it comes to validation. This specifically tests that #6302 is fixed for
+ # both file fields and image fields.
+
+ with open(os.path.join(os.path.dirname(__file__), "test.png"), "rb") as fp:
+ image_data = fp.read()
+ with open(os.path.join(os.path.dirname(__file__), "test2.png"), "rb") as fp:
+ image_data2 = fp.read()
+
+ f = ImageFileForm(
+ data={"description": "An image"},
+ files={"image": SimpleUploadedFile("test.png", image_data)},
+ )
+ self.assertTrue(f.is_valid())
+ self.assertEqual(type(f.cleaned_data["image"]), SimpleUploadedFile)
+ instance = f.save()
+ self.assertEqual(instance.image.name, "tests/test.png")
+ self.assertEqual(instance.width, 16)
+ self.assertEqual(instance.height, 16)
+
+ # Delete the current file since this is not done by Django, but don't save
+ # because the dimension fields are not null=True.
+ instance.image.delete(save=False)
+ f = ImageFileForm(
+ data={"description": "An image"},
+ files={"image": SimpleUploadedFile("test.png", image_data)},
+ )
+ self.assertTrue(f.is_valid())
+ self.assertEqual(type(f.cleaned_data["image"]), SimpleUploadedFile)
+ instance = f.save()
+ self.assertEqual(instance.image.name, "tests/test.png")
+ self.assertEqual(instance.width, 16)
+ self.assertEqual(instance.height, 16)
+
+ # Edit an instance that already has the (required) image defined in the
+ # model. This will not save the image again, but leave it exactly as it
+ # is.
+
+ f = ImageFileForm(data={"description": "Look, it changed"}, instance=instance)
+ self.assertTrue(f.is_valid())
+ self.assertEqual(f.cleaned_data["image"].name, "tests/test.png")
+ instance = f.save()
+ self.assertEqual(instance.image.name, "tests/test.png")
+ self.assertEqual(instance.height, 16)
+ self.assertEqual(instance.width, 16)
+
+ # Delete the current file since this is not done by Django, but don't save
+ # because the dimension fields are not null=True.
+ instance.image.delete(save=False)
+ # Override the file by uploading a new one.
+
+ f = ImageFileForm(
+ data={"description": "Changed it"},
+ files={"image": SimpleUploadedFile("test2.png", image_data2)},
+ instance=instance,
+ )
+ self.assertTrue(f.is_valid())
+ instance = f.save()
+ self.assertEqual(instance.image.name, "tests/test2.png")
+ self.assertEqual(instance.height, 32)
+ self.assertEqual(instance.width, 48)
+
+ # Delete the current file since this is not done by Django, but don't save
+ # because the dimension fields are not null=True.
+ instance.image.delete(save=False)
+ instance.delete()
+
+ f = ImageFileForm(
+ data={"description": "Changed it"},
+ files={"image": SimpleUploadedFile("test2.png", image_data2)},
+ )
+ self.assertTrue(f.is_valid())
+ instance = f.save()
+ self.assertEqual(instance.image.name, "tests/test2.png")
+ self.assertEqual(instance.height, 32)
+ self.assertEqual(instance.width, 48)
+
+ # Delete the current file since this is not done by Django, but don't save
+ # because the dimension fields are not null=True.
+ instance.image.delete(save=False)
+ instance.delete()
+
+ # Test the non-required ImageField
+ # Note: In Oracle, we expect a null ImageField to return '' instead of
+ # None.
+ if connection.features.interprets_empty_strings_as_nulls:
+ expected_null_imagefield_repr = ""
+ else:
+ expected_null_imagefield_repr = None
+
+ f = OptionalImageFileForm(data={"description": "Test"})
+ self.assertTrue(f.is_valid())
+ instance = f.save()
+ self.assertEqual(instance.image.name, expected_null_imagefield_repr)
+ self.assertIsNone(instance.width)
+ self.assertIsNone(instance.height)
+
+ f = OptionalImageFileForm(
+ data={"description": "And a final one"},
+ files={"image": SimpleUploadedFile("test3.png", image_data)},
+ instance=instance,
+ )
+ self.assertTrue(f.is_valid())
+ instance = f.save()
+ self.assertEqual(instance.image.name, "tests/test3.png")
+ self.assertEqual(instance.width, 16)
+ self.assertEqual(instance.height, 16)
+
+ # Editing the instance without re-uploading the image should not affect
+ # the image or its width/height properties.
+ f = OptionalImageFileForm({"description": "New Description"}, instance=instance)
+ self.assertTrue(f.is_valid())
+ instance = f.save()
+ self.assertEqual(instance.description, "New Description")
+ self.assertEqual(instance.image.name, "tests/test3.png")
+ self.assertEqual(instance.width, 16)
+ self.assertEqual(instance.height, 16)
+
+ # Delete the current file since this is not done by Django.
+ instance.image.delete()
+ instance.delete()
+
+ f = OptionalImageFileForm(
+ data={"description": "And a final one"},
+ files={"image": SimpleUploadedFile("test4.png", image_data2)},
+ )
+ self.assertTrue(f.is_valid())
+ instance = f.save()
+ self.assertEqual(instance.image.name, "tests/test4.png")
+ self.assertEqual(instance.width, 48)
+ self.assertEqual(instance.height, 32)
+ instance.delete()
+ # Callable upload_to behavior that's dependent on the value of another
+ # field in the model.
+ f = ImageFileForm(
+ data={"description": "And a final one", "path": "foo"},
+ files={"image": SimpleUploadedFile("test4.png", image_data)},
+ )
+ self.assertTrue(f.is_valid())
+ instance = f.save()
+ self.assertEqual(instance.image.name, "foo/test4.png")
+ instance.delete()
+
+ # Editing an instance that has an image without an extension shouldn't
+ # fail validation. First create:
+ f = NoExtensionImageFileForm(
+ data={"description": "An image"},
+ files={"image": SimpleUploadedFile("test.png", image_data)},
+ )
+ self.assertTrue(f.is_valid())
+ instance = f.save()
+ self.assertEqual(instance.image.name, "tests/no_extension")
+ # Then edit:
+ f = NoExtensionImageFileForm(
+ data={"description": "Edited image"}, instance=instance
+ )
+ self.assertTrue(f.is_valid())
+
+
+class ModelOtherFieldTests(SimpleTestCase):
+ def test_big_integer_field(self):
+ bif = BigIntForm({"biggie": "-9223372036854775808"})
+ self.assertTrue(bif.is_valid())
+ bif = BigIntForm({"biggie": "-9223372036854775809"})
+ self.assertFalse(bif.is_valid())
+ self.assertEqual(
+ bif.errors,
+ {
+ "biggie": [
+ "Ensure this value is greater than or equal to "
+ "-9223372036854775808."
+ ]
+ },
+ )
+ bif = BigIntForm({"biggie": "9223372036854775807"})
+ self.assertTrue(bif.is_valid())
+ bif = BigIntForm({"biggie": "9223372036854775808"})
+ self.assertFalse(bif.is_valid())
+ self.assertEqual(
+ bif.errors,
+ {
+ "biggie": [
+ "Ensure this value is less than or equal to 9223372036854775807."
+ ]
+ },
+ )
+
+ @ignore_warnings(category=RemovedInDjango60Warning)
+ def test_url_on_modelform(self):
+ "Check basic URL field validation on model forms"
+
+ class HomepageForm(forms.ModelForm):
+ class Meta:
+ model = Homepage
+ fields = "__all__"
+
+ self.assertFalse(HomepageForm({"url": "foo"}).is_valid())
+ self.assertFalse(HomepageForm({"url": "http://"}).is_valid())
+ self.assertFalse(HomepageForm({"url": "http://example"}).is_valid())
+ self.assertFalse(HomepageForm({"url": "http://example."}).is_valid())
+ self.assertFalse(HomepageForm({"url": "http://com."}).is_valid())
+
+ self.assertTrue(HomepageForm({"url": "http://localhost"}).is_valid())
+ self.assertTrue(HomepageForm({"url": "http://example.com"}).is_valid())
+ self.assertTrue(HomepageForm({"url": "http://www.example.com"}).is_valid())
+ self.assertTrue(HomepageForm({"url": "http://www.example.com:8000"}).is_valid())
+ self.assertTrue(HomepageForm({"url": "http://www.example.com/test"}).is_valid())
+ self.assertTrue(
+ HomepageForm({"url": "http://www.example.com:8000/test"}).is_valid()
+ )
+ self.assertTrue(HomepageForm({"url": "http://example.com/foo/bar"}).is_valid())
+
+ def test_url_modelform_assume_scheme_warning(self):
+ msg = (
+ "The default scheme will be changed from 'http' to 'https' in Django "
+ "6.0. Pass the forms.URLField.assume_scheme argument to silence this "
+ "warning."
+ )
+ with self.assertWarnsMessage(RemovedInDjango60Warning, msg):
+
+ class HomepageForm(forms.ModelForm):
+ class Meta:
+ model = Homepage
+ fields = "__all__"
+
+ def test_modelform_non_editable_field(self):
+ """
+ When explicitly including a non-editable field in a ModelForm, the
+ error message should be explicit.
+ """
+ # 'created', non-editable, is excluded by default
+ self.assertNotIn("created", ArticleForm().fields)
+
+ msg = (
+ "'created' cannot be specified for Article model form as it is a "
+ "non-editable field"
+ )
+ with self.assertRaisesMessage(FieldError, msg):
+
+ class InvalidArticleForm(forms.ModelForm):
+ class Meta:
+ model = Article
+ fields = ("headline", "created")
+
+ def test_https_prefixing(self):
+ """
+ If the https:// prefix is omitted on form input, the field adds it
+ again.
+ """
+
+ class HomepageForm(forms.ModelForm):
+ # RemovedInDjango60Warning.
+ url = forms.URLField(assume_scheme="https")
+
+ class Meta:
+ model = Homepage
+ fields = "__all__"
+
+ form = HomepageForm({"url": "example.com"})
+ self.assertTrue(form.is_valid())
+ self.assertEqual(form.cleaned_data["url"], "https://example.com")
+
+ form = HomepageForm({"url": "example.com/test"})
+ self.assertTrue(form.is_valid())
+ self.assertEqual(form.cleaned_data["url"], "https://example.com/test")
+
+
+class OtherModelFormTests(TestCase):
+ def test_media_on_modelform(self):
+ # Similar to a regular Form class you can define custom media to be used on
+ # the ModelForm.
+ f = ModelFormWithMedia()
+ self.assertHTMLEqual(
+ str(f.media),
+ ''
+ '',
+ )
+
+ def test_choices_type(self):
+ # Choices on CharField and IntegerField
+ f = ArticleForm()
+ with self.assertRaises(ValidationError):
+ f.fields["status"].clean("42")
+
+ f = ArticleStatusForm()
+ with self.assertRaises(ValidationError):
+ f.fields["status"].clean("z")
+
+ def test_prefetch_related_queryset(self):
+ """
+ ModelChoiceField should respect a prefetch_related() on its queryset.
+ """
+ blue = Colour.objects.create(name="blue")
+ red = Colour.objects.create(name="red")
+ multicolor_item = ColourfulItem.objects.create()
+ multicolor_item.colours.add(blue, red)
+ red_item = ColourfulItem.objects.create()
+ red_item.colours.add(red)
+
+ class ColorModelChoiceField(forms.ModelChoiceField):
+ def label_from_instance(self, obj):
+ return ", ".join(c.name for c in obj.colours.all())
+
+ field = ColorModelChoiceField(ColourfulItem.objects.prefetch_related("colours"))
+ with self.assertNumQueries(3): # would be 4 if prefetch is ignored
+ self.assertEqual(
+ tuple(field.choices),
+ (
+ ("", "---------"),
+ (multicolor_item.pk, "blue, red"),
+ (red_item.pk, "red"),
+ ),
+ )
+
+ def test_foreignkeys_which_use_to_field(self):
+ apple = Inventory.objects.create(barcode=86, name="Apple")
+ pear = Inventory.objects.create(barcode=22, name="Pear")
+ core = Inventory.objects.create(barcode=87, name="Core", parent=apple)
+
+ field = forms.ModelChoiceField(Inventory.objects.all(), to_field_name="barcode")
+ self.assertEqual(
+ tuple(field.choices),
+ (("", "---------"), (86, "Apple"), (87, "Core"), (22, "Pear")),
+ )
+
+ form = InventoryForm(instance=core)
+ self.assertHTMLEqual(
+ str(form["parent"]),
+ """""",
+ )
+ data = model_to_dict(core)
+ data["parent"] = "22"
+ form = InventoryForm(data=data, instance=core)
+ core = form.save()
+ self.assertEqual(core.parent.name, "Pear")
+
+ class CategoryForm(forms.ModelForm):
+ description = forms.CharField()
+
+ class Meta:
+ model = Category
+ fields = ["description", "url"]
+
+ self.assertEqual(list(CategoryForm.base_fields), ["description", "url"])
+
+ self.assertHTMLEqual(
+ str(CategoryForm()),
+ '