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

238
Visualizações
django form.is_valid returns false when while using XMLHttpRequest

since bootstrap 5 no longer ships with jquery and recommends using the vanilla javascript XMLHttpRequest() to make dynamic requests that is what I am trying to do in django. All the other examples of doing this use the traditional .$ajax. I have a basic javascript function:

function sendPhoneVerification(_phone) {
    var http = new XMLHttpRequest();
    const params = {
            phone: _phone
    }
    http.open('POST', '/approvephone/', true)
    http.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
    http.setRequestHeader('Content-type', 'application/json')
    http.setRequestHeader('phone', _phone)
    http.send(JSON.stringify(params))
    http.onload = function() {
        alert(http.responseText)
    }
}

The CSRF middlware token is working fine, but the in the view, the form.is_valid() returns false and the error is that required field "phone" is missing. I can't tell how I am supposed to provide that value. The form being tested against is a simple form with one field

class AddPhoneForm(forms.Form):
    phone = PhoneNumberField()

relevant part of the view

@csrf_protect
@login_required
def approvephone(request):
    if request.method == 'POST':
        form = AddPhoneForm(request.POST)
        if form.is_valid()  #returns false and error is missing field "phone"

Any idea how I can correctly provide the phone fields in the POST response to make django happy?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

ok I feel stupid, but in django you need to send 'Content-type', 'application/x-www-form-urlencoded' as described here https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send

function sendPhoneVerification(_phone) {
    alert("Hello! I am an alert box!!" + _phone);
    var http = new XMLHttpRequest();
    http.open('POST', '/approvephone/', true)
    http.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    http.send("phone="+_phone)

    http.onload = function() {
        alert(http.responseText)
    }
about 4 years ago · Juan Pablo Isaza 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