Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't Django sites be embedded inside another HTML(iframe)?

I tried embedding a django form in another html page but it does not work. I tried my other django sites. But nothing works. Also tested for some other sites. Is django restricted to be used in iframe? How to make it work? form needed to be embedded Programming competition form

Template:

<form method="post">
  {% csrf_token %}
  <b>{{form.as_p}}</b>
  <input type="submit" value="Submit" title="Submit" />
</form>

Try to embedded as:

<html>
<iframe frameborder="1" src="http://form.classof20.cf/Programming_Competition/"></iframe>
</html>

It give a border and nothing inside.

like image 420
Sagar Devkota Avatar asked Sep 06 '17 16:09

Sagar Devkota


1 Answers

Here is the error in webkit inspector after trying to load your HTML:

Refused to display 'http://form.classof20.cf/Programming_Competition/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.
Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE

And indeed, here's a dump of the response headers by curl:

$ curl -I http://form.classof20.cf/Programming_Competition/

HTTP/1.1 200 OK
Server: nginx/1.10.3 (Ubuntu)
Date: Wed, 06 Sep 2017 19:44:16 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 765
Connection: keep-alive
Vary: Cookie
X-Frame-Options: SAMEORIGIN
Set-Cookie: csrftoken=UJZltdTzJMe6961QMNRSgZ7vKWa1vUEf2lEB8lmaaZXgROf1zyALsuwsKpvtcby6; expires=Wed, 05-Sep-2018 19:44:16 GMT; Max-Age=31449600; Path=/

So, where does it come from ? It comes from Django clickjacking protection.

Solution 0: make sure your django response allows your other site in X-Frame-Options, ie:

X-Frame-Options: ALLOW-FROM http://your-other-site-which-embeds/

Solution 1: exempt your form view from clickjacking protection:

When using the middleware there may be some views where you do not want the X-Frame-Options header set. For those cases, you can use a view decorator that tells the middleware not to set the header:

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.")
like image 111
jpic Avatar answered Oct 25 '22 16:10

jpic