Django tests AssertionError for update view

I tried to create Django test for UpdateView

but I have such problem as: self.assertEqual(application.credit_purpose, 'House Loan') AssertionError: 'Car Loan' != 'House Loan'

  • Car Loan
  • House Loa

      def test_application_update(self):
      application = Application.objects.create(customer=self.customer, credit_amount=10000, credit_term=12,
                                                    credit_purpose='Car Loan', credit_pledge=self.pledge,
                                                    number_request=2, date_posted='2020-01-01', reason='None',
                                                    repayment_source=self.repayment, possible_payment=1000,
                                                    date_refuse='2020-01-02', protokol_number='123457',
                                                    language=0, day_of_payment=1, credit_user=self.user)
      response =
          reverse('application_update', kwargs={'pk':}),
          {'credit_purpose': 'House Loan'})
      self.assertEqual(response.status_code, 200)
      self.assertEqual(application.credit_purpose, 'House Loan')

So, I also got stuck in this for a while. The main problem is at:

    response =
        reverse('application_update', kwargs={'pk':}),
        {'credit_purpose': 'House Loan'}

I was able to understand thanks to this answer. It happens because you are posting to a form and it expects to have all fields filled, otherwise it will fail validation and thus will not call .save().

What you can do is, after creating the object copy its data into a dictionary, then modify it before posting:

from django.forms.models import model_to_dict

class ApplicationTestCase(TestCase):
    def setUp(self):
        customer = Customer.objects.create(...)
        ... = {
            'customer': customer, 'credit_amount': 10000, 'credit_term': 12,
            'credit_purpose': 'Car Loan', ...

    def test_application_update(self):
        application = Application.objects.create(**

        post_data = model_to_dict(application)
        post_data['credit_purpose'] = 'House Loan'

        response =
                'app:view-name', kwargs={'pk':}),

        # print(application.credit_purpose)
        # application.refresh_from_db()
        # print(application.credit_purpose)

        # It returns a redirect so code is 302 not 200.
        self.assertEqual(response.status_code, 302)
        self.assertEqual(application.credit_purpose, 'House Loan')

Also, get_absolute_url() is set in the wrong place should be under models:

class Application(AbstractCredit):

    def get_absolute_url(self):
        return reverse('app:view-name', kwargs={'pk':})
Back to Top