Skip to main content
 首页 » 编程设计

python之如何使用测试客户端和 post 方法使用 ModelChoiceField 测试 Django 表单

2025年05月04日39thcjp

如何使用 Django test client.post 来测试具有 ModelChoiceField 的表单?传给post方法的数据字典应该怎么写?我这样做的方式根本没有选择任何值。

我有一个包含以下字段的表单:

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})" 
            }, 
        ) 

我还有以下测试用例:

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!') 

这个表格没问题。但是当我使用上述测试用例对其进行测试时,作为模型选择字段(国家/地区)数据传递的选择未被选中。我试图传递值 (32) 和国家名称(“巴西”)或其他任何内容。

请您参考如下方法:

我想您需要传递国家或模型实例的 ID。

如果你有一个 ID 为 32 的国家“巴西”,你可以传入

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

或

你可以先通过使用获取国家

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