Skip to content

Commit

Permalink
ModelForm now checks whether instance is correct on __init__ (Fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
selwin committed Aug 20, 2012
1 parent bfc380b commit 0208682
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 0 deletions.
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() self.instance = opts.model()
object_data = {} object_data = {}
else: 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 self.instance = instance
object_data = model_to_dict(instance, opts.fields, opts.exclude) object_data = model_to_dict(instance, opts.fields, opts.exclude)
# if initial was provided, it should override the values from instance # if initial was provided, it should override the values from instance
Expand Down
4 changes: 4 additions & 0 deletions tests/regressiontests/forms/tests/models.py
Expand Up @@ -114,6 +114,10 @@ def test_unicode_filename(self):
self.assertEqual(m.file.name, 'tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt') self.assertEqual(m.file.name, 'tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt')
m.delete() 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): def test_boundary_conditions(self):
# Boundary conditions on a PostitiveIntegerField ######################### # Boundary conditions on a PostitiveIntegerField #########################
class BoundaryForm(ModelForm): class BoundaryForm(ModelForm):
Expand Down

0 comments on commit 0208682

Please sign in to comment.