Home > Software design >  Django render_to_string not working inside update of djangoRestFramework serializer
Django render_to_string not working inside update of djangoRestFramework serializer

Time:09-29

I try to use the render_to_string method of django to generate a html. This function is actually called inside a signal which is sent inside the update method of a djangoRestFramework serializer. By doing that I got the error:

AttributeError: 'functools.partial' object has no attribute '__module__'

I tried to debug and what I see is that the render_to_string method does not work inside the update block of the serializer. As I use a generic from rest_framework UpdateAPIView I did not manage to put break points inside the view. But before calling the url and the view the render_to_string works well. I tried to find the error from the django source code but couldn't find where it comes from.

Here is the part of the code where I call the render_to_string function:

class AnalysisSerializer(serializers.ModelSerializer):
    class Meta:
        model = Object
        fields = '__all__'
        depth = 1

    def update(self, instance, validated_data):
        t = render_to_string('template/order.html')

CodePudding user response:

Ensure that you have properly configured template path in TEMPLATE config in settings.py

CodePudding user response:

Ok I understood why. The error was not caused by the render_to_string method but by the tests. I was actually having this issue by using it inside a pytest process. The function causing this error is

django/test/utils.py:100: in instrumented_test_render
    template_rendered.send(sender=self, template=self, context=context)

Which is called during testing. Mocking this function in the test of the url and testing the signal itself on another test solved the issue.

  • Related