Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for #6702: ModelForm now checks instance on __init__ #296

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions django/forms/models.py
Expand Up @@ -236,6 +236,9 @@ def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
self.instance = opts.model()
object_data = {}
else:
if not isinstance(instance, opts.model):
raise ValueError('"instance" must be an instance of {0}'.format(
opts.model._meta.object_name))
self.instance = instance
object_data = model_to_dict(instance, opts.fields, opts.exclude)
# if initial was provided, it should override the values from instance
Expand Down
10 changes: 7 additions & 3 deletions tests/regressiontests/forms/tests/models.py
Expand Up @@ -106,16 +106,20 @@ def test_initial_instance_value(self):

class FormsModelTestCase(TestCase):
def test_unicode_filename(self):
# FileModel with unicode filename and data #########################
# FileModel with unicode filename and data
f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))}, auto_id=False)
self.assertTrue(f.is_valid())
self.assertTrue('file1' in f.cleaned_data)
m = FileModel.objects.create(file=f.cleaned_data['file1'])
self.assertEqual(m.file.name, 'tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt')
m.delete()

def test_incorrect_instance_raises_exception(self):
# ModelForm with incorrect instance raises ValueError on init
self.assertRaises(ValueError, ChoiceFieldForm, instance=Group)

def test_boundary_conditions(self):
# Boundary conditions on a PostitiveIntegerField #########################
# Boundary conditions on a PostitiveIntegerField
class BoundaryForm(ModelForm):
class Meta:
model = BoundaryModel
Expand All @@ -128,7 +132,7 @@ class Meta:
self.assertFalse(f.is_valid())

def test_formfield_initial(self):
# Formfield initial values ########
# Formfield initial values
# If the model has default values for some fields, they are used as the formfield
# initial values.
class DefaultsForm(ModelForm):
Expand Down