Pasdian
Pasdian

Reputation: 529

How to test two django forms that are in the same view

So I have a view that handles two different forms in the same POST request.

Previously the testing was easy because i had only one form so it would be something like:

def test_post_success(self):
    response = self.client.post("/books/add/", data={"title": "Dombey and Son"})

    self.assertEqual(response.status_code, HTTPStatus.FOUND)
    self.assertEqual(response["Location"], "/books/")

If i have a second form with a 'prefix' how would i construct the data object of the request.

Im thinking of:

form_1_data = {foo}
form_2_data = {bar}
response = self.client.post("/books/add/", data={form_1_data, form_2_data)

But it clearly does not work

Upvotes: 0

Views: 163

Answers (2)

Leonardo Barros
Leonardo Barros

Reputation: 1

In my case I solved it this way:

class RegisterTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.data = {
            **{'username': 'J0hnDo3', 'first_name': 'John', 'last_name': 'Doe',
            'email': '[email protected]', 'password1': 'secureP4ssword123', 'password2': 'secureP4ssword123'},
            **{'company': 2, 'phone': '', 'type_user': 'student', 'branch': 2}
        }

def test_register_success(self):
    response = self.client.post(reverse('register'), data=self.data)
    self.assertRedirects(response, '/login/', 302)

I'm realized the update in:

response = self.client.post(
    reverse('register'),
    data=json.dumps(self.data),
    content_type='application/json'
)

to

response = self.client.post(reverse('register'), data=self.data)

Upvotes: 0

NixonSparrow
NixonSparrow

Reputation: 6368

You can combine dictionaries with ** mark. Like this:

>>> data_1 = {"title": "Dombey and Son"}
>>> data_2 = {"character": "Donald Duck"}
>>> {**data_2, **data_1}
{'character': 'Donald Duck', 'title': 'Dombey and Son'}

Upvotes: 0

Related Questions