Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelForm is_valid() always return false during unit testing

I have a simple Django code.

there is my model and form in models.py file:

from django.db import models
from django.forms import ModelForm

class Supplier(models.Model):
    name = models.CharField(max_length=55)
    comment = models.TextField(blank=True)

class SupplierForm(ModelForm):
    class Meta:
        model = Supplier

and there is my test.py:

from django.test import TestCase
from mysite.myapp.models import Supplier, SupplierForm

class SupplierTest(TestCase):
    def test_supplier(self):
        supplier = Supplier(name="SomeSupplier")
        supplier_form = SupplierForm(instance = supplier)
        self.assertEquals(supplier_form.is_valid(), True)

When I start test through manage.py, is_valid() always returns False, but I expect True.

What the reasons for fail is_valid() in this case ? I use Django 1.3.

like image 245
mt_serg Avatar asked May 10 '11 13:05

mt_serg


1 Answers

All forms constructed without data are "invalid" because they have nothing to validate :-) You need to supply valid input to form's constuctor:

supplier_form = SupplierForm({'name': 'NewSupplier'}, instance=supplier)
like image 92
catavaran Avatar answered Sep 19 '22 14:09

catavaran