Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

321
Vistas
Django CSRF Token Missing Only in Production

I am getting a missing CSRF_Token error that only occurs in production mode on my server. However everything works great when I am running it from my computer terminal using the runserver command. I've read through many of the other questions pertaining to this with no luck. It seems that my case is slightly different than others, since it works locally but not in production.

I get the error when submitting an Ajax form that submits to the "submit" in views.py. Does anybody know what could be causing this? Also, looking at my cookies in Production mode, the CSRF_Token is not even there to begin with. Locally it is. Thanks for any help.

Here is my views.py

from django.shortcuts import render

from django.http import HttpResponse


def index(request):

    return render(request, 'index.html')


def submit(request):
    #Receive Request 
    inputone = request.POST['randominfo']
    inputtwo = request.POST['randominfo2']

    #Some more code here that setups response. 
    #Deleted since Im posting to StackOverflow

    return response

Code Pertaining to the Ajax Submit

$(function () {
    $.ajaxSetup({
        headers: { "X-CSRFToken": getCookie("csrftoken") }
    });
});

function getCookie(c_name)
{
    if (document.cookie.length > 0)
    {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1)
        {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
 }
function submitAjax(event){

        $.ajax({
            type:'POST',
            url:'/submit/',
            data:{
                randominfo:document.getElementById('Random').innerHTML,
                randominfo2:document.getElementById('Random2').innerHTML,

            },
            dateType: 'json',
            success:function() {
                  # Url here  

            }

        })
    };

Solution that fixed this problem.

Adding "from django.views.decorators.csrf import ensure_csrf_cookie" in views.py and then "@ensure_csrf_cookie" above the view that returns the html file that contained the ajax form

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

The error ocurs because you are not setting the csrf token, to prevent this we have to check some details

First of all, you have to set the csrf token to your form, in your html you have to set some as follow:

<form id="id" name="form">
    {% csrf_token %}
    <!-- Form body here -->
</form>

Second the approach to set the csrf cookie to your request header is ok, i only suggest that instead you set your data field one by one, use method serialize of jquery

data: $("#your-form-id").serialize()

I would like to recommend you to read this post about ajax request with django that is very helpful

about 4 years ago · Santiago Trujillo Denunciar

0

There are 2 things you can do:

1.) Submit a CSRF token in your ajax call. You have to use a getCookie() javascript function to get it. Luckily the django documentation has some code you can copy and paste. javascript

$.ajax({
        type:'POST',
        url:'/submit/',
        data:{
            randominfo:document.getElementById('Random').innerHTML,
            randominfo2:document.getElementById('Random2').innerHTML,
            'csrfmiddlewaretoken': getCookie('csrftoken'), // add this
...

2.) Disable csrf for your /submit view. You can do this with a decorator. Note that this is less secure so make sure there's no confidential data.

views.py:

from django.views.decorators.csrf import csrf_exempt
...
@csrf_exempt
def your_submit_view(request):
  #view code
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda