Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!