I'm trying to unit test my update forms and views. I'm using Django Crispy Forms for both my Create and Update Forms. UpdateForm inherits CreateForm and makes a small change to the submit button text. The CreateView and UpdateView are very similar. They have the same model, template, and success_url. They differ in that they use their respective forms, and CreateView inherits django.views.generic.CreateView, and UpdateView inherits django.views.generic.edit.UpdateView.
The website works fine. I can create and edit an object without a problem. However, my second test shown below fails. How do I test my UpdateForm?
Any help would be appreciated. Thanks.
This test passes:
class CreateFormTest(TestCase):
def setUp(self):
self.valid_data = {
'x': 'foo',
'y': 'bar',
}
def test_create_form_valid(self):
""" Test CreateForm with valid data """
form = CreateForm(data=self.valid_data)
self.assertTrue(form.is_valid())
obj = form.save()
self.assertEqual(obj.x, self.valid_data['x'])
This test fails:
class UpdateFormTest(TestCase):
def setUp(self):
self.obj = Factories.create_obj() # Creates the object
def test_update_form_valid(self):
""" Test UpdateForm with valid data """
valid_data = model_to_dict(self.obj)
valid_data['x'] = 'new'
form = UpdateForm(valid_data)
self.assertTrue(form.is_valid())
case = form.save()
self.assertEqual(case.defendant, self.valid_data['defendant']
When pre-populating a ModelForm
with an object that has already been created you can use the instance
keyword argument to pass the object to the form.
form = SomeForm(instance=my_obj)
This can be done in a test, such as in the OP< or in a view to edit an object that has already been created. When calling save()
the existing object will updated instead of creating a new one.
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