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

177
Vistas
How to get Images from AJAX and save it to Django

I'm trying to get an image with AJAX and save it to my django model. However, I can not see 'photo' variable that AJAX returns in the terminal although other variables (csrf, name...) are in there. So I can not process with 'photo' field and save it.

there is the querydict that I received from AJAX. csrf and name is in there but no 'photo' variable.

*** request.POST:  <QueryDict: {'csrfmiddlewaretoken': ['krnIBkcYUb1breFjMyoReCwXeH9DLFc1Pvg2x1U2SGZSxPxQSLOwOxs1aSMrvBkf'], 'name': ['fgdfdsfsdf']}>

js script

var clientCreateForm = document.getElementById('client-create-form')
var csrf = document.getElementsByName('csrfmiddlewaretoken')
var client_name = document.getElementById('name')
var image = document.getElementById('photo')

   clientCreateForm.addEventListener('submit', e => {
        e.preventDefault()
        console.log('submitted')
        var resim = image.files[0]
        console.log(resim)

        var fd = new FormData()
        fd.append('csrfmiddlewaretoken', csrf[0].value)
        fd.append('name', client_name.value)
        fd.append('photo', resim)

        $.ajax({
            type:'POST',
            url:'/clients/',
            enctype: 'multipart/form-data',
            data: fd,
            contentType: false,
            processData: false,
            success: function (response) {
                window.location.replace(response.instance_url)
            },
            error: function (error) {
                console.log("An error occurred")
            }
        })
    })

views.py

 def post(self, request, *args, **kwargs):
        if is_ajax(request=request): # if request.method == "POST":
            print("*** request.POST: ", request.POST)
            my_name = request.POST.get('name')
            my_foto = request.POST.get('photo')
            new_client = models.Client.objects.create(owner=self.request.user, name=my_name, sector=my_sector, foto=my_foto)
            new_client.save()
            slug = new_client.slug
            return JsonResponse({'instance_url': slug})
        return redirect('action-listview')
about 4 years ago · Juan Pablo Isaza
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