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

237
Vistas
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 Respuestas
Responde la pregunta

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 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