Django forms unit tests with ForeignKey

I have ModelFormone that contains some ForeignKey, for example, for a User object, but it can be for any other model. I have a unit test class for this form, but when I try to pass its data, I get an error Select a valid choice. That choice is not one of the available choices. The test looks like this:

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 tried any number of permutations for user, but I get the same error.

What am I missing?

+4
source share
1 answer

You should be able to assign a value to the 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}
    ...
+6
source

Source: https://habr.com/ru/post/1620396/


All Articles