Last Updated: February 25, 2016
·
1.206K
· djiit

Django-enabled Polymer core-ajax variant

Using Django with CSRF protection enabled (you should!) ? This polymer element extends core-ajax and inject the CSRF token into each ajax calls.

<link rel="import" href="/static/bower_components/polymer/polymer.html">
<link rel="import" href="/static/bower_components/core-ajax/core-ajax.html">

<polymer-element name="django-ajax" extends="core-ajax">
    <script>
        Polymer({
            getCSRFCookie: function() {
                b = document.cookie.match('(^|;)\\s*csrftoken\\s*=\\s*([^;]+)');
                return b ? b.pop() : '';
            },
            ready: function() {
                this.super();
                this.headers = {
                    "X-CSRFToken": this.getCSRFCookie(),
                    "X-Requested-With": "XMLHttpRequest"
                };
            }
        });
    </script>
</polymer-element>