[Django]-Why xframe_options_exempt doesn't work for my Django view?

2๐Ÿ‘

I just had the same problem. In my case, I was raising an Http404 error, which seems to somehow bypass the @xframe_options_exempt decorator. I suspect that if you are returning anything other than an HttpResponse object from your view, then your xframe_options_exempt decorator may not be performing as you might expect.

Note that the Http404 class, for example, does not inherit from HttpResponse.

๐Ÿ‘คJustin O Barber

1๐Ÿ‘

Include middleware in your settings.py file

MIDDLEWARE_CLASSES = (
    ...
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ...
)

Then include needed imports in your views.py file

from django.http import HttpResponse
from django.views.decorators.clickjacking import xframe_options_exempt
๐Ÿ‘คSilmaril

0๐Ÿ‘

Youโ€™ve probably already figured it out, but Django xframe_options_exempt sadly only works for HTTPResponse for current release (Mar. 2021).

An example of how to use it would be:

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.")

For sameorigin and deny, it would be:

from django.http import HttpResponse
from django.views.decorators.clickjacking import xframe_options_deny
from django.views.decorators.clickjacking import xframe_options_sameorigin

@xframe_options_deny
def view_one(request):
    return HttpResponse("Frame won't be displayed!")

@xframe_options_sameorigin
def view_two(request):
    return HttpResponse("Display onlly if from the same origin host.")

Referenced from Django Clickjacking Protection

๐Ÿ‘คvladthelad

Leave a comment