1

I am really confused why this form.is_valid() returns False:

Here is the django model I created:

class aModel(models.Model):
    some_id = models.IntegerField()

I turn the Model into a ModelForm, and create a ModelForm instance with an instance of the Model. Shouldn't this ModelForm instance be valid?

>>> class aModelForm(forms.ModelForm):
...     class Meta:
...             model = aModel
... 
>>> am = aModel.objects.get(id=1)
>>> for k,v in am.__dict__.items(): print k,v
... 
_state <django.db.models.base.ModelState object at 0x1020c8a50>
id 1
some_id 5
>>> form = aModelForm(instance=am)
>>> form.is_valid()
False
>>> am.save()
>>> am.some_id = 6
>>> am.save()
>>> 

Why isn't the form valid? What do I need to do to make the form valid?

1
  • form.errors returns {} Commented Dec 27, 2012 at 23:11

1 Answer 1

2

It looks like this form is not bound to data, so it cannot validate. You can verify by printing form.is_bound() just before form.is_valid() to verify.

If it is not bound, I don't think you can validate. To bind data, you need to add the data as a dictionary for the first argument to the form.

form = aModelForm({'some_id': am.some_id}, instance=am)
form.is_valid()

See Django - Forms API for more details.

Sign up to request clarification or add additional context in comments.

3 Comments

I have read the Forms API enough, but your simple answer helps so much in adding that insight which makes everything alot more clear. Thanks!
Can you elaborate on what the data should be? I'm not understanding why it needs anything other than my instance.
Well, I assume you are updating the data for the instance. Just simply getting the instance only assigns the instance to the ModelForm, but doesn't bind the data you are updating/validating from the request POST. You wouldn't validate an instance conforms to a ModelForm when that instance is not being changed in any way. It has already been validated the last time it was saved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.