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.:
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
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.