如何使用测试客户端和post方法使用ModelChoiceField测试Django表单 [英] How to test a Django form with a ModelChoiceField using test client and post method

查看:133
本文介绍了如何使用测试客户端和post方法使用ModelChoiceField测试Django表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Django测试client.post测试具有ModelChoiceField的表单?传递给post方法的数据字典应如何编写?我做的方式根本没有选择任何值.

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

我还有以下测试用例:

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)和国家名称(巴西")或其他任何内容.

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.

推荐答案

我想您需要传递国家/地区或模型实例的ID.

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

如果您有ID为32的国家巴西",则可以传入

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

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

您可以先使用来获取国家/地区

you can first get the country by using

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

这篇关于如何使用测试客户端和post方法使用ModelChoiceField测试Django表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆