From 9d9658f128476e72aedd62ee60ca2506c5e4bae1 Mon Sep 17 00:00:00 2001 From: Clinton Blackburn Date: Mon, 11 Apr 2016 23:04:20 -0400 Subject: [PATCH] Added support for custom CSRF cookie names Instead of hardcoding the CSRF cookie name, the value is passed to the template as a context variable, rendered as a JavaScript variable, and read by csrf.js. Fixes #4048 --- rest_framework/renderers.py | 4 +++- rest_framework/static/rest_framework/js/csrf.js | 2 +- rest_framework/templates/rest_framework/admin.html | 5 +++++ rest_framework/templates/rest_framework/base.html | 5 +++++ 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index 68af417da..53bbb1390 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -12,6 +12,7 @@ import json from collections import OrderedDict from django import forms +from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.paginator import Page from django.http.multipartparser import parse_header @@ -657,7 +658,8 @@ class BrowsableAPIRenderer(BaseRenderer): 'display_edit_forms': bool(response.status_code != 403), - 'api_settings': api_settings + 'api_settings': api_settings, + 'csrf_cookie_name': settings.CSRF_COOKIE_NAME, } return context diff --git a/rest_framework/static/rest_framework/js/csrf.js b/rest_framework/static/rest_framework/js/csrf.js index 4e8da0de5..73d1ef67d 100644 --- a/rest_framework/static/rest_framework/js/csrf.js +++ b/rest_framework/static/rest_framework/js/csrf.js @@ -33,7 +33,7 @@ function sameOrigin(url) { !(/^(\/\/|http:|https:).*/.test(url)); } -var csrftoken = getCookie('csrftoken'); +var csrftoken = getCookie(window.drf.csrfCookieName); $.ajaxSetup({ beforeSend: function(xhr, settings) { diff --git a/rest_framework/templates/rest_framework/admin.html b/rest_framework/templates/rest_framework/admin.html index a86adbc60..a21ea57be 100644 --- a/rest_framework/templates/rest_framework/admin.html +++ b/rest_framework/templates/rest_framework/admin.html @@ -230,6 +230,11 @@ {% if filter_form %}{{ filter_form }}{% endif %} {% block script %} + diff --git a/rest_framework/templates/rest_framework/base.html b/rest_framework/templates/rest_framework/base.html index eccadc3cc..21431b70c 100644 --- a/rest_framework/templates/rest_framework/base.html +++ b/rest_framework/templates/rest_framework/base.html @@ -258,6 +258,11 @@ {% block script %} +