djangorequestfactory

Django Test RequestFactory post with foreign key


I'm trying to test a view-function with django's RequestFactory's post-method. The view-function should create a new ObjA-instance. ObjA has a foreign key field to an ObjB.

My test currently looks like this (names changed for better reading):

request = self.factory.post('/create-objA/', data={'objB': objB.id, 'field1': 'dummy'})
request.user = self.user
request.POST.is_bound = True
create_objA(request)
self.assertTrue(ObjA.objects.filter(field1='dummy').exists())

objB does exist, this is tested few lines before in the same test function.

However the test in the snippet fails. The reason is that in the following create function form.is_valid() is never true:

def create_objA(request):
    if request.method == 'POST':
        form = ObjAFormCreate(request.POST)
        if form.is_valid():
            ....

So the ObjA is not created. Form is not valid because it has an error in the ObjB reference field:

Select a valid choice. That choice is not one of the available choices.

though objB.id is inside form.data.

Question: How should I write the test, so that the form would not have the error?

Model:

class ObjA(models.Model):
    id = models.BigAutoField(primary_key=True)
    obj_b_id = models.ForeignKey(ObjB, on_delete=models.CASCADE)
    field1 = models.CharField(max_length=10)

Form:

class ObjAFormCreate(ModelForm):
    objB = forms.ModelChoiceField(queryset=ObjB.objects.all())
    field1 = forms.CharField(max_length=10)


Solution

  • Answering my own question. It looks like the code is correct and there is a bug either in Django or in my IDE, because after some changes and tries it started to work with exactly the same code. I don't know why the behaviour is not deterministic at some points.