About Calling Async Django Views from a Browser

Async views with ASGI are usually used for those views which take longer, for example, connecting to external APIs, converting an image, or reading and processing data from an Excel file.

To call an async view, you can use the default JavaScript fetch API, e.g.:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
async function readExcelFile() {
  console.log('Uploading...');
  const formData = new FormData();
  const fileField = document.querySelector('input[type="file"]');
  formData.append('excel_file', fileField.files[0]);
  const csrftoken = document.querySelector(
    '[name="csrfmiddlewaretoken"]'
  ).value;
  try {
    const response = await fetch('https://example.com/read-excel/', {
      method: 'POST',
      body: formData,
      headers: {'X-CSRFToken': csrftoken},
      mode: 'same-origin'
    });
    const data = await response.json();
    console.log('File data:', data);
  } catch (error) {
    console.error('Error:', error);
  }
}
document.getElementById('submit').addEventListener('click', readExcelFile);

Tips and Tricks Programming Development Django 5.x Django 4.2 Django 3.2 JavaScript ASGI