I have a ModelForm
that contains some ForeignKey
, say to the User object but it could be to any other model. I have a unit test class for this form, but when I am trying to pass it data, I get a Select a valid choice. That choice is not one of the available choices
error. The test looks like so:
class Monkey(Model):
user = models.ForeignKey(User)
...
class MyForm(ModelForm):
class Meta:
model = Monkey
fields = ['user', ...]
def test_my_form_with_a_user(self):
...
data = {'user': User.objects.get(pk=1), ... } # Nope.
data = {'user': [u'1'], ... } # Nope.
data = {'user': [u'JaneDoe'], ... } # Nope.
form = MyForm(data, ...)
self.assertTrue(form.is_valid(), form.errors)
...
I have tried any number of permutation for the user
but am getting the same error.
What am I missing?
You should be able to assign a value to your user field in the test using the following:
def test_my_form_with_a_user(self):
user_pk = User.objects.get(pk=1).pk
data = {'user': user_pk}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With