'How to test a Django form with a ModelChoiceField using test client and post method

How do I use Django test client.post to test a form that has a ModelChoiceField? How should the data dictionary passed to the post method be written? The way I am doing does not select any value at all.

I have a form with the following field:

country = forms.ModelChoiceField(
        label="País",
        queryset=Country.objects.all().order_by('name'),
        required=True,
        widget=forms.Select(attrs={
            'onchange': "Dajaxice.party.update_country(Dajax.process, {'option':this.value})"
            },
        )

I also have the following test case:

def test_party_profile_sucessfully_saved(self):
    self.client.login(username='Party1', password='BadMotherF')
    response = self.client.post(reverse('party'), data={'slx_legal_type': '1', 'city':  'Belo Horizonte', 'country': '32',
                                        'mobile': '+55-31-55555555', 'name':    'Roberto Vasconcelos Novaes',
                                        'phone': '+55-31-55555555', 'slx_cnpj': '', 'slx_cpf': '056846515',
                                        'slx_ie': '', 'slx_im': '', 'slx_rg': 'MG9084545', 'street':
                                        'Rua Palmira, 656 - 502', 'streetbis': 'Serra', 'subdivision': '520',
                                        'zip': '30220110'},
                               follow=True)
    self.assertContains(response, 'Succesfully Saved!')

This form works all right. But when I test it using the aforementioned test case, the choice passed as data for the Model Choice Field (Country) does not get chosen. I have tried to pass the value (32) and the name of the country ('Brasil') or whatever.



Solution 1:[1]

I guess you need to pass the ID of the country or the model instance.

If you have a country 'Brazil' with id 32 you can pass in

{....
    'country' : 32
....}

or

you can first get the country by using

country = Country.objects.get(id=32)
{....
    'country': country
....}

Solution 2:[2]

I myself encountered such a problem when solving the problem. When specifying specific attributes, for example, <ModelName>.objects.get(<attr>='<...>').<something> when running django test, no post submit is formed and <ModelName>.objects.count() remains unchanged. In a practical way, I noticed that ChoiceField in the POST works only if you specify the id of the required <ModelName>.objects. But I passed the id as '32'. Therefore, it seems to me that the problem is a little different, not that the wrong value for 'country' is passed. P.S. I apologize in advance that with a separate answer, there is not enough reputation for commenting

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zaphod100.10
Solution 2 febqij