Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

325
Visualizações
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

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

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

over 4 years ago · Santiago Trujillo Relatório

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
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda