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

编程入门 行业动态 更新时间:2024-10-28 04:17:27
本文介绍了如何使用测试客户端和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表单

本文发布于:2023-11-24 11:30:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625024.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:测试   表单   如何使用   客户端   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!