Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Form not valid but no error

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 ?

like image 323
Pierre de LESPINAY Avatar asked Mar 28 '12 14:03

Pierre de LESPINAY


2 Answers

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.

like image 166
Daniel Roseman Avatar answered Sep 29 '22 15:09

Daniel Roseman


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.

like image 21
djvg Avatar answered Sep 29 '22 16:09

djvg