duduklein
duduklein

Reputation: 10604

Django test failing with request.user in get_inital in generic CreateView

I have a generic view like this:

class SaveView(CreateView):

    def get_initial(self):
        # Get the initial dictionary from the superclass method
        initial = super(SaveView, self).get_initial()
        # Copy the dictionary so we don't accidentally change a mutable dict
        initial = initial.copy()
        initial['user'] = self.request.user
        return initial

This view has the login_required decorator, so self.request.user is always valid.

When I'm accessing the page with the browser, everything is working fine, but my tests are failing. I have the following test setup:

from django.test import TestCase, client

class MyTest(TestCase):
    def setUp(self):
        self.client = client.Client()
    def test1(self):
        self.assertTrue(self.client.login(username='user1',password='password1'))
        data = {'name':'test 1'}
        response = self.client.post('/app/save/', data)
        self.assertEqual(response.status_code, 302)

'/app/save/' is the url that calls that view (it's working perfectly on the browser My model has 2 mandatory fields "name" and "user", so this should issue a redirect to the created object page, since I have passed the name through data and the user should be got from get_initial method.

Indeed this is what happens in the "real life", i.e. browser.

The only way I could make this test pass successfully passing the 'user' in the data dictionary.

Is this a bug in django.test module or this is the expected behavior and why?

Thanks in advance

Upvotes: 0

Views: 543

Answers (1)

Alasdair
Alasdair

Reputation: 308909

This is expected behaviour. From the Django docs on initial data:

The initial argument lets you specify the initial value to use when rendering this Field in an unbound Form.

When you post data in your test, you are using a bound form, so initial data is not used. The form is invalid because the required user field is missing, so a 200 response is returned that displays the form errors. This is same as what would happen if you cleared the user field in your browser, and submitted the form.

You need to include the user in your post data, then, the test will pass.

Upvotes: 1

Related Questions