Reputation: 2509
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?
Upvotes: 1
Views: 2023
Reputation: 8285
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.
Upvotes: 2