1

I've made a website with Django and React JS. I'm trying to pass an array pict from my JavaScript frontend to Django, the Python backend.

let pict = [];

pictureEl.addEventListener(`click`, function () {
  console.log(`Take Pic`);
  pict += webcam.snap();
  console.log(pict);
});

pict is an array of images taken by the camera. How would I pass it to the backend?

2 Answers 2

5
+100

You can communicate with your backend using an HTTP request library (e.g axios, fetch, ajax requests, etc)

Communication over HTTP is done through several different verbs (i.e GET, POST, PUT, PATCH, DELETE, etc) I'm agnostic of how your endpoint is handling the request so I'll assume your endpoint expects a POST. NOTES:

  • The example below use axios as HTTP request library for JS
  • I'm suggesting a change to your original code to use picts
# urls.py
from django.urls import path

from . import views

url_patterns = [
  path('path/to/my_endpoint', views.my_endpoint),
]
# views.py
from django.http import HttpResponse

def my_endpoint(request):
    pict = request.POST.getlist('pict[]')
    process_pict(pict)
    return HttpResponse('Success')

In this case you can send the request to your server as follows:

// api.js
import axios from 'axios'

export function sendPict(pict) {
  const payload = {'pict[]': pict}
  return axios.post('path/to/my_endpoint', payload)
}

Then you can send your pict anywhere from your app:

import sendPict from './api'
const pict = [];
pictureEl.addEventListener(`click`, function () {
  console.log(`Take Pic`);
  pict.push(webcam.snap());
  console.log(pict);
  console.log('sending pict to server')
  sendPict(pict)
    .then(response => console.log(`The success server response is: ${response}`))
    .catch(error => alert(`Oh noes: ${error}`))
});
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for the well detailed response. Though I'm still a bit confused. Can you give me an example path for axios.post('path/to/my_endpoint', payload)?
Absolutely, I edited the answer above to include a snippet that adds the django view (my_endpoint) to a url that will serve it. - Django view reference: docs.djangoproject.com/en/3.2/topics/http/views - Django url reference: docs.djangoproject.com/en/3.2/topics/http/urls
Thank you very much. Though I was getting a Forbidden (CSRF token missing or incorrect.): /path/to/my_endpoint error so I added @csrf_exempt above the my_endpoint function. It fixed the error, but now when I print(pict) I get an empty list.
Make sure: 1. Using the same key you used on the frontend (e.g pict[]) on both your backend and frontend 2. The value you are sending from the backend is the same you are receiving on the backend. You can do this by taking a look at your network tab the browser's console and by printing request.POST
Hi Carlos. Its actually because I'm not loading the data properly in views.py. It should be data = json.loads(request.body) and pict = data['pict[]']. Thanks for your help!
0
    import React from 'react'
    import axios from 'axios'
    
    postPict = (pict) => {

        //data is a json object which will have your pict array set to 'data' keyword
        
        const data= {'data': pict}

        //the next line would return a promise to 'http://localhost:8000' with the data object defined above

        return axios.post('http://localhost:8000', data)
    }
    
    pictureEl.addEventListener(`click`, function () {
        console.log(`Take Pic`);
        pict += webcam.snap();
        console.log(pict);

//here you call the function defined as postPic to access the promise and add the necessary code in the respective blocks of then(will contain success condition codes) and catch(will contain error condition codes)

        postPic(pict)
            .then(res => {
                console.log(res)
                //Do whatever you want
            })
            .catch(err => {
                console.log(err)
                //Do whatever you want
            })
    
    });

You can access this data like you access json data in Django along with 'data' keyword

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.