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

646
Visualizações
How to properly append django csrf_token to form in inline javascript?

I have created form element dynamically in javascript:

var selectform = document.createElement("form")

I have added other input elements and these attributes to selectform:

   submitnselection.setAttribute('type',"submit");
   submitnselection.setAttribute('value',"Submit");
   submitnselection.setAttribute("name","submitnpage");
   selectform.setAttribute("method", "post")
   selectform.setAttribute = ("action", "/test")
   "{% csrf_token %}";

In HTML, adding {% csrf_token %} template tag would work, but in this case of javascript i got 403 forbidden error:

CSRF token missing or incorrect.

I have found some solutions but nothing was working for me, is there any way to add {% csrf_token %} to form with only using Django, Javascript and plain Jquery? Also note that this script is inside html, so i think {% csrf_token %} template tag will work.

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

This should work:

var inputElem = document.createElement('input');
inputElem.type = 'hidden';
inputElem.name = 'csrfmiddlewaretoken';
inputElem.value = '{{ csrf_token }}';
selectform.appendChild(inputElem);

You see, the csrf_token is nothing more that a string which is the value of a hidden input element of a form. That's all!

about 4 years ago · Santiago Trujillo Relatório

0

You can try to append an input field to the form:

// declare an input field 
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'csrfmiddlewaretoken';
input.value = '{% csrf_token %}';

// attach field to the form 
selectform.appendChild(input);

// submit
about 4 years ago · Santiago Trujillo Relatório

0

If I understand everything, you need to send a csrf token but you don't have any to send to the server from javascript.

From the code in a Django template is very easy to generate a csrf token with the usual {% csrf_token %} Django tag, but this is because the template is being processed in the server to create the final HTML which will be sent to the browser.

When you are in Javascript you can't generate a csrf token so, I think the best solution is creating an invisible tag in the template, probably a hidden input.

<input id="token" type="hidden" value="{% csrf_token %}" ></input>

And when in jQuery get the value with $('#token').attr('value'), I have an example with a jQuery POST method:

token = $('#token').attr('value');
$.post(url, { 
             'personId': personId,
             'csrfmiddlewaretoken': token // This is the important thing
            }, function() {}
);

No matter how you do it, you have to send the token with the 'csrfmiddlewaretoken' name and the token value along with the other info you want to send to the server.

I'm editing this with a pure JS solution if you need it. Just say it.

about 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