Nested router and APIRequestFactory context
I have the following routes and CRUD views working nicely using DRF nested routers:
/pages//pages/<page_id>//pages/<page_id>/menus/
In my menu serializer I use the page_id from the route to fetch the corresponding page:
class MenuSerializer(serializers.ModelSerializer):
def to_internal_value(self, data):
resp = super().to_internal_value(data)
resp['page'] = Page.objects.get(pk=self.context['view'].kwargs['page_id'])
return resp
In normal use this works fine - context['view'].kwargs contains the page_id as expected.
Now, I'm trying to write integration tests using rest_framework.test.APIRequestFactory like this:
request = APIRequestFactory().post(
f'/pages/{page_id}/menus/?format=json', menu_data, format='json'
)
response = MenuViewSet.as_view({'post': 'create'})(request)
Now, the MenuSerializer.to_internal_value method fails because page_id does not exist in the view context.
How should I proceed?
No idea. Sorry. Do you think APIRequestFactory is misbehaving?
Question: Is this related to Nested Routers? I saw no relation with it, just with Django Rest Framework. Maybe this issue should be opened there.
I haven't had time to look into the DRF nested router`s codebase much but I suppose it's a question of who's business it is to but the subroute into the view context. Maybe the APIRequestFactory could be subclassed in DRF nested router's code to make testing easier?
What I mean is: Your exemple does not involve a nested route. So, do it work in a scenario without drf-nested-routers?
If yes, we can bake a test and debug up to the point it starts to "not work as expected". If not, you should file an issue on https://github.com/encode/django-rest-framework, not here.
Sorry. I just realised that the MenuSerializer is the nested resource.
Let me think a bit then.
@aleehedl Did you come to the resolution of this issue? Asking since I am also facing this issue.
Not really @GauravWaghmare. I never went to this road of usage. Sorry.
Having a minimal automated test expressing the failing behavior would help I guess.