问题
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.
回答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
....}
来源:https://stackoverflow.com/questions/21034938/how-to-test-a-django-form-with-a-modelchoicefield-using-test-client-and-post-met