Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django forms unit tests with ForeignKey

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?

like image 401
Sardathrion - against SE abuse Avatar asked Dec 16 '15 17:12

Sardathrion - against SE abuse


1 Answers

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}
    ...
like image 132
Patrick Beeson Avatar answered Sep 19 '22 13:09

Patrick Beeson