views:

41

answers:

1

Ok, I have been staring at this for hours trying to figure out what's going on, to no avail. I am trying to create a ModelForm using the 'instance' keyword to pass it an existing model instance and then save it. Here is the ModelForm (stripped considerably from the original in my attempts to identify the cause of this problem):

class TempRuleFieldForm(ModelForm):
    class Meta:
        model = RuleField

and here is the code I'm running:

>>> m = RuleField.objects.get(pk=1)
>>> f = TempRuleFieldForm(instance=m)
>>> f.is_valid()
False

The model object (m above) is valid and it saves just fine, but the form will not validate. Now, as far as I can tell, this code is identical to the Django docs example found here: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method, though obviously I am missing something. I would greatly appreciate some fresh eyes to tell me what I've got wrong.

Thanks

+1  A: 

Note that your link doesn't call f.is_valid(), it just saves directly. This is potentially a bit misleading.

The point is that instantiating a form with just an instance parameter but no data does not bind it to data, and the form is therefore not valid. You will see that f.is_bound is False.

Behind the scenes, instance is really just the same as passing initial data, which as the docs note is only used to display the data initially and is not used for saving. You would probably benefit from reading the notes on bound and unbound forms.

Daniel Roseman
+1. "instance does not imply bound": This is correct reasoning.
Manoj Govindan
Thank you, that makes perfect sense. I knew it would be something simple...
oogles
Just for clarification, the reason I was using f.is_valid() was simply to make the question more concise. Using f.save() fails with an AttributeError on the cleaned_data field, which does not exist until the form validates. So even when I was using the code _exactly_ as it is in the link I posted (using f.save() instead of f.is_valid()) it was still failing.
oogles