@xframe_options_exempt not working for Django view/template that displays an iFrame?

Viewed 38

I am displaying an iFrame on my template, the contents of which is from a local .html that I have uploaded as a media file.

I have X_FRAME_OPTIONS = 'SAMEORIGIN' set in my settings to allow the displaying of the contents, however when I run the --check deploy check, I get this message:

WARNINGS:
?: (security.W019) You have 'django.middleware.clickjacking.XFrameOptionsMiddleware' in your 
MIDDLEWARE, but X_FRAME_OPTIONS is not set to 'DENY'. Unless there is a good reason for your site
to serve other parts of itself in a frame, you should change it to 'DENY'.

Seems like I should be keeping this set to DENY when I go to production, however by doing that, my iFrame is "unable to connect" to display the content.

I've read the documentation here that says you can set exemptions on the view level if you set it to DENY, however it's not working for me.

On the view function, I've tried using the decorators @xframe_options_sameorigin and @xframe_options_exempt like:

# @xframe_options_sameorigin # Doesn't work
# @xframe_options_exempt # Also doesn't work
# Setting X_FRAME_OPTIONS = 'SAMEORIGIN'
# and use @xframe_options_deny also doesn't work
def work_detail(request, pk):
    work = Work.objects.get(pk=pk)
    context = {
        'work': work
    }
    return render(request, 'work_detail.html', context)

...but all of them still do not connect the iFrame. What else can I try?

1 Answers

This doesn't solve the issue, but as a workaround, instead of using an iframe, I found this solution worked for me in the template.html file:

  1. <div w3-include-html="{{ work.html.url }}"></div>
  2. Define the javascript on top of the template, but below {% block page_content %}
  3. Add
<script>
    includeHTML();
</script>

to the bottom of the page, but before {% endblock %}. 4. Clear cache and restart runserver. I can use that in place of the iframe, but would be nice to know why the exempts weren't working as desired?

Related