Plotly graph not plotting when returning plot_div from function

I am creating a polar chart with plotly. The chart plots fine if I render it by passing plot_div to the template directly from the code that generates it. However, if I use the same code as a function, pass values to the function from another section of the program, and then return plot_div, nothing gets rendered. Looking at the HTML it appears all that is sent to the template is the < character.

I can put the code in the base code and it works fine, but that means I can’t reuse it easily to generate multiple graphs.

Here’s the code for the function:

def results_plotly(user_id,survey):
    user = user_id
    survey = survey
    values = list(Final_Result.objects.filter(user_id=user, survey=survey).values_list('scores', flat=True).order_by('order'))
    first_value = values[0] #Get first value
    values.append(first_value) #add to end to close graph, repeat for each set of points
    titles = list(Final_Result.objects.filter(user_id=user, survey=survey).values_list('area', flat=True).order_by('order'))
    first_value = titles[0]
    titles.append(first_value)
    colors = list(Final_Result.objects.filter(user_id=user, survey=survey).values_list('overall_color', flat=True).order_by('order'))
    first_value = colors[0]
    colors.append(first_value)
    fig = go.Figure(data=go.Scatterpolar(
    r = values,
    theta = titles,
    mode =  'lines+markers',
    line_color="black",


    marker= dict(
        color = colors,
        size = 10,



    ),




        ))

    fig.update_layout(
        title = 'Project',
        polar=dict(
            radialaxis=dict(
            visible=True,
            range=[0, 3],
            ),
            angularaxis=dict(
            rotation=90, # Rotates the axis 90 degrees counterclockwise
            direction="clockwise"

        )
        ),
        showlegend=False,
        height = 600,

        )



    plot_div = pyo.plot(fig, output_type='div')

    return plot_div