7

I have customized save_model admin i.e.

class MyModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        # some more question code here
        obj.save()

Now, I would like to test MyModelAdmin save_model function. I tried posting like:

class MyModelAdminSaveTestCase(TestCase):
    def setUp(self):

        # setup code here

    def test_save_model(self):
        '''Test add employee
        '''
        my_obj = {
            'name': 'Tester',
            'address': '12 test Test',
            'city': 'New York',
            'state': 'NY',
        }

        self.client.login(username=self.user, password=self.pwd)
        response = self.client.post(reverse('admin:mymodel_mymodel_add'), my_obj, follow=True)

        self.assertEqual(response.status_code, 200)

        self.assertEqual(MyModel.objects.count(), 1)

However, test fails:

self.assertEqual(MyModel.objects.count(), 1)
AssertionError: 0 != 1
Elisa
  • 6,865
  • 11
  • 41
  • 56
  • can you write full code example? especially of this view : `admin:mymodel_mymodel_add` –  Nov 24 '16 at 16:13
  • 1
    actually you shouldn't follow redirects during save - 200 in your case might indicate some error in form (maybe some field is missing/invalid) - set `follow=False` and expect 302 status code. – Matthew Nov 24 '16 at 16:16
  • Print `response.content` in the test - that will show you whether there are any errors on the page. If the response is too long, you could try to get the form errors directly with something like `response.context[' 'adminform'].form.errors`. – Alasdair Nov 24 '16 at 16:58

1 Answers1

0

My answer is 5 years late, but maybe it helps someone else.

To access django admin users need to have is_staff=True. Non-staff users are redirected to login page (which is probably what happened in the example above).

Also, users need to have enough permissions to access specific admin pages (easy fix for this is to set is_superuser=True if you don't need to test permissions).

So client setup like this would have probably fixed the issue:

user = User.objects.create_superuser(username='super', 
                                     email='super@email.org', 
                                     password='pass')
client.login(username=user.username, password='pass')
# now you can access django admin

You can inspect response.context_data to get more information if something goes wrong.

But there's also a cleaner way to test save_model in my opinion, see this answer.

Ivan
  • 624
  • 4
  • 7