Model:
class Session(models.Model):
tutor = models.ForeignKey(User)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
def __unicode__(self):
return u'%s - %s' % (self.tutor, self.start_time)
Form:
class SessionForm(forms.ModelForm):
class Meta:
model = Session
exclude = ['tutor']
Testing:
>>> ses = Session.objects.get(pk=1)
>>> ses
<Session: Robert - 2012-03-22 13:00:00>
>>> form = SessionForm(instance=ses)
>>> form.is_valid()
false
>>> form.errors
{}
What's wrong ?
You have not passed any data to the form, so it is not valid. The instance argument is not used to set the form data, just the initial data.
This is a humble attempt to provide a little background for Daniel Roseman's answer above.
As you can see in the source, BaseForm.is_valid()
does the following:
return self.is_bound and not self.errors
So, if is_valid()
returns False
, even though there are no errors, then is_bound
must be False
.
Now, the value for is_bound
is assigned in BaseForm.__init__()
(source):
self.is_bound = data is not None or files is not None
From the forms documentation:
A Form instance is either bound to a set of data, or unbound.
- If it’s bound to a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the HTML.
- If it’s unbound, it cannot do validation (because there’s no data to validate!), but it can still render the blank form as HTML.
Also note that errors
is a property, which calls the full_clean()
method (source), which does the actual validation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With