How to configure X-Frame-Options in Django to allow iframe embedding of one view?
Asked Answered
S

3

42

I'm trying to enable django to allow one specific view to be embedded on external sites, preferabilly without sites restrictions.

In my views.py file, I have added the following code, where the view futurebig is the one I want to enable to be embedded:

from django.views.decorators.clickjacking import xframe_options_sameorigin
...
@xframe_options_sameorigin
def futurebig(request):
    ...
    return render_to_response('templates/iframe/future_clock_big.html', context_dict, context)

which doesn't help as I understand because it only enables embedding in the same server.

How can I set the headers for that specific view to enable it to be embedded in any website?

For the record, I'm just a frontend developer, the backend developer who developed the site is no longer working with me and refused to document his code, so, If anyone could help me and explain carefully where and what modifications I should do, I'll apreciatte it very much.

Thanks.

As far as I know, the Django version is 1.6

Sanyu answered 21/10, 2015 at 19:12 Comment(0)
S
86

You are going in the right direction, but exact decorator which you will need to achieve this is 'xframe_options_exempt'.

from django.http import HttpResponse
from django.views.decorators.clickjacking import xframe_options_exempt

@xframe_options_exempt
def ok_to_load_in_a_frame(request):
    return HttpResponse("This page is safe to load in a frame on any site.")

PS: DJango 1.6 is no longer supported. It is good time to get an upgrade.

Stammel answered 21/10, 2015 at 19:44 Comment(1)
I think, we need decorator for ALLOW-FROM of iframe options developer.mozilla.org/ru/docs/Web/HTTP/Headers/X-Frame-Options to define acceptable domains, not just remove X-Frame Header, please, somebody, create ticket (i have no access)Tartuffe
S
27

Apparently you can set a rule in your settings telling the following:

X_FRAME_OPTIONS = 'ALLOW-FROM https://example.com/'

Also nowadays you should consider moving to CSP

Content-Security-Policy: frame-ancestors 'self' example.com *.example.net ;

See https://mcmap.net/q/181255/-x-frame-options-allow-from-multiple-domains

Schramm answered 9/2, 2018 at 14:5 Comment(2)
ALLOW-FROM will not support chrome and safariLaic
And ALLOW-FROM should NOT be used anymore: developer.mozilla.org/en-US/docs/Web/HTTP/Headers/… . As the @Schramm said: Move to CSP!Chloris
M
1

If you want to allow the frame in specific view you can add Content-Security-Policy to your view response, so your code will be something like this

def MyView(request):
    ....
    ....
    response = render(request,'MyViewHtml.html' ,{...})
    response ['Content-Security-Policy'] = "frame-ancestors 'self' https://example.com"
Microtome answered 13/2, 2021 at 20:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.