@@ -57,6 +57,31 @@ def _get_template_name_description(template_name):
5757 return template_name
5858
5959
60+ def _normalize_context (context ):
61+ # type: (Dict[str, Any]) -> Dict[str, Any]
62+ """
63+ Filter out non-primitive types from `context`.
64+ """
65+ new_context = {}
66+ for key , value in context .items ():
67+ if isinstance (value , list ):
68+ new_context [key ] = [
69+ item
70+ for item in value
71+ if isinstance (item , (str , int , float , bool , type (None )))
72+ ]
73+ elif isinstance (value , dict ):
74+ new_context [key ] = {
75+ k : v
76+ for k , v in value .items ()
77+ if isinstance (v , (str , int , float , bool , type (None )))
78+ }
79+ elif isinstance (value , (str , int , float , bool , type (None ))):
80+ new_context [key ] = value
81+
82+ return new_context
83+
84+
6085def patch_templates ():
6186 # type: () -> None
6287 from django .template .response import SimpleTemplateResponse
@@ -73,13 +98,7 @@ def rendered_content(self):
7398 name = _get_template_name_description (self .template_name ),
7499 origin = DjangoIntegration .origin ,
75100 ) as span :
76- new_context = {}
77- for k , v in self .context_data .items ():
78- # Only include primitive types to avoid
79- # large payloads and long serialization times
80- if type (v ) in (str , int , float , bool , list , dict ):
81- new_context [k ] = v
82-
101+ new_context = _normalize_context (self .context_data )
83102 span .set_data ("context" , new_context )
84103
85104 return real_rendered_content .fget (self )
@@ -109,13 +128,7 @@ def render(request, template_name, context=None, *args, **kwargs):
109128 name = _get_template_name_description (template_name ),
110129 origin = DjangoIntegration .origin ,
111130 ) as span :
112- new_context = {}
113- for k , v in context .items ():
114- # Only include primitive types to avoid
115- # large payloads and long serialization times
116- if type (v ) in (str , int , float , bool , list , dict ):
117- new_context [k ] = v
118-
131+ new_context = _normalize_context (context )
119132 span .set_data ("context" , new_context )
120133
121134 return real_render (request , template_name , context , * args , ** kwargs )
0 commit comments