为什么 Django 站点不能嵌入到另一个 HTML(iframe)中?

Sag*_*ota 5 html python django iframe

我尝试在另一个 html 页面中嵌入一个 django 表单,但它不起作用。我尝试了我的其他 Django 网站。但没有任何作用。还测试了其他一些网站。django 是否限制在 iframe 中使用?如何使它工作?表格需要嵌入编程竞赛表格

模板:

<form method="post">
  {% csrf_token %}
  <b>{{form.as_p}}</b>
  <input type="submit" value="Submit" title="Submit" />
</form>
Run Code Online (Sandbox Code Playgroud)

尝试嵌入为:

<html>
<iframe frameborder="1" src="http://form.classof20.cf/Programming_Competition/"></iframe>
</html>
Run Code Online (Sandbox Code Playgroud)

它给了一个边界,里面什么都没有。

jpi*_*pic 15

这是尝试加载 HTML 后 webkit 检查器中的错误:

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
Run Code Online (Sandbox Code Playgroud)

事实上,这是 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=/
Run Code Online (Sandbox Code Playgroud)

那么,它来自哪里?它来自Django 点击劫持保护

解决方案 0:确保您的 Django 响应允许您在 X-Frame-Options 中的其他站点,即:

X-Frame-Options: ALLOW-FROM http://your-other-site-which-embeds/
Run Code Online (Sandbox Code Playgroud)

解决方案 1:免除您的表单视图的点击劫持保护:

使用中间件时,可能有些视图不需要 X-Frame-Options 标头集。对于这些情况,您可以使用视图装饰器告诉中间件不要设置标头:

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.")
Run Code Online (Sandbox Code Playgroud)