Search code examples
djangodjango-formsdjango-testingdjango-unittest

How to POST data to a Django Form that contains checkboxes


I have a problem when I am testing my registration form in Django. I am trying to make a POST request but I cannot select a checkbox field.

self.response = self.client.post(url, {
        'username': 'testuser',
        'password': 'testuserpassword',
        'first_name': 'testtt',
        'last_name': 'userrr',
        'image': '',
        'email': '[email protected]',
        'gender': 'M',
        'dob': '10/10/1996',
        'hobby': 'Fishing'
    })

This is my line of code. The problem is at Hobby. The registration page is made of two forms. A profile form and a hobby form. There is a many-to-many relationship between Profile and Hobby models.

When I make the above POST request, I get this (Select a valid choice):

enter image description here

Thank you in advance!


Solution

  • According to the screenshot you've posted, the value for each hobby checkbox corresponds to an integer - 1, 2, 3, 4, etc. That would imply that the backend is expecting the hobby ID to be transmitted in the form. However, the test is not sending the hobby ID, it's sending the name.

    Change the name to the corresponding ID - e.g.

    self.response = self.client.post(url, {
            ...
            'hobby': 1  # Fishing
        })