Django 1.9 AJAX form CSRF token 403 error - "CSRF cookie not set"
<p>I've seen a lot about this on SO, but nothing can fix my problem.</p>

<p><strong>Problem:</strong></p>

<p>With CSRF middleware enabled, Django responds with 403 on AJAX form request, stating:</p>

<blockquote>
  <p>"CSRF cookie not set."</p>
</blockquote>

<p>Following the <a href="https://docs.djangoproject.com/en/1.9/ref/csrf/#ajax" rel="noreferrer">documentation</a>, a JS functionality was implemented, that sets custom <strong>"X-CSRFToken"</strong> header.</p>

<p>It works as expected, gets <strong>"csrftoken"</strong> cookie from browser and posts it along with AJAX request:</p>

<pre><code>x-csrftoken: 1a0u7GCQG0wepZHQNThIXeYpMy2lZOf2
</code></pre>

<p>But response is still 403.</p>

<p><strong>Tried solutions:</strong></p>

<p>I've tried everything I could find on SO or web, specifically:</p>

<ul>
<li><p>Checking that middleware is enabled:</p>

<pre><code>MIDDLEWARE_CLASSES = [
    ...
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    ...
]
</code></pre></li>
<li><p>Different browsers with cookies enabled;</p></li>
<li><p>Decorating my view with <code>@ensure_csrf_cookie</code>;</p></li>
<li><p>Setting <code>{% csrf_token %}</code> in my template;</p></li>
<li><p>Using <code>render</code> shortcut which takes right request context;</p></li>
<li><p>Setting custom <code>CSRF_COOKIE_NAME</code> and <code>CSRF_HEADER_NAME</code> in my <code>settings.py</code>;</p></li>
<li><p>Explicitly setting <code>CSRF_COOKIE_SECURE = False</code> and <code>CSRF_COOKIE_HTTPONLY = False</code>;</p></li>
<li><p>Explicitly setting <code>CSRF_TRUSTED_ORIGINS</code> setting;</p></li>
<li><p>Testing on development and production server;</p></li>
<li><p>Even <code>request.META["CSRF_COOKIE_USED"] = True</code> in my view, as someone suggested.</p></li>
</ul>

<p>And still got nothing.</p>

<p><strong>Headers:</strong></p>

<p>If I use <code>@csrf_exempt</code> and <code>print(request.META)</code> in my view, it's clear that custom header <strong>"X-CSRFToken"</strong> is present in request and formatted according to Django documentation, with "HTTP_" prefix, replaced hyphens with underscores, all uppercase: <strong>"HTTP_X_CSRFTOKEN"</strong>.</p>

<p>Even more, it's value matches with cookie set by Django.</p>

<p><strong>Cookies:</strong></p>

<p>Strange thing is, if I try to <code>print(request.COOKIES)</code> in my view, on page  and form load I can see <strong>"csrftoken"</strong> cookie there, but dictionary is <strong>empty on AJAX request</strong>. Can it be the problem?</p>

<p>Desperate to find what is actually wrong. Thank you for reading this.</p>