Reputation: 1509
I have the following test...
def test_contact_form(self):
form_data = {'name': 'Reiss Johnson',
'email': '[email protected]',
'_type': 'General Enquiry',
'content': 'This is some content'}
form = ContactForm(data=form_data)
self.assertTrue(form.is_valid())
This was originally passing as '_type' was a CharField, however it is now a ModelChoiceField & so does anybody know why this is failing? Im guessing im inputting the '_type' into the dictionary incorrectly now?
How could I get the above test to pass again?
My form is as so...
class ContactForm(forms.Form):
name = forms.CharField(max_length=50)
email = forms.EmailField()
content = forms.CharField()
_type = forms.ModelChoiceField(queryset=EnquiryType.objects.values_list('text', flat=True), empty_label=None)
Upvotes: 1
Views: 1508
Reputation: 110
I had the same issue. To expand on Shang's answer:
Yes, it looks like using the primary key of the model you're referencing will work.
Here's what I did:
valid_pk = NameOfModel.objects.all()[0].pk
# You may need to replace 0 with the right number.
form_data = {'name': 'Reiss Johnson',
'email': '[email protected]',
'_type': str(valid_pk),
'content': 'This is some content'}
Upvotes: 4
Reputation: 25549
I think the problem is that you didn't understand what does ModelChoiceField
do. It would generate a list of id
(which is the Primary Key for that model) that corresponds to each object that the model has, so when you save, it saves the id
as foreign key. You can't feed the form field with a text
, which is only a field of model EnquiryType
. Think about it, if you don't refer to the primary key of another table but .text
, which object should the ModelChoiceField
select? What if you create another object that has the same text
?
The easy fix would change your test data with the id
of the object that has General Enquiry
as .text
.
Upvotes: 0