Import HttpResponse file from HTML button without refresh page

Hello everyone,

For a Django project, I have a page that allows to load an XLS file and generate an HTML table that appears on the page, as well as an HttpResponse object of the same file in XLSX format.

I manage to display my HTML table but I would like that, with a “import” button, we can import the file in HttpResponse.

My problem is that when I put my “Import” button in a form type=POST, it refreshes the page and my html table disappears as well as the file inside the input button.

I thought of importing it by a simple button with Javascript but I can’t…

Do you have any ideas on how I could successfully import my file without refreshing the page? Or maybe how can I improve my idea to make it easier to do?

Thanks in advance!

template.html

<form method='POST' enctype="multipart/form-data">{% csrf_token %}
    <input type='file' name='InputFile' accept='.xls'>
</form>

<div id=table>
    {{ table }}
</div>

<form method='POST' enctype="multipart/form-data">{% csrf_token %}
    <input type='submit' name='importXLSXFile' value='{{ myHttpResponse }}'>
</form>

views.py

def main(request):
    if request.method == 'POST' and request.FILES.get('InputFile') != None: 
        #some_scripts
        return render(request, 'template.html',{'table':table,'myHttpResponse ': HttpResponse })

    if request.method == 'POST' and "importXLSXFile" in request.POST :
        #i_dont_know_what_to_do_here

You would need to submit that file as an AJAX submission. You’ll need to write some JavaScript to submit that file and handle the response.

1 Like

You don’t need to write JavaScript to do the AJAX. Try htmx, which lets you describe requests to make with HTML attributes. I’m the author of Django-htmx, which can help you integrate htmx with Django. It has some examples.

1 Like

True - poor wording on my part. It would have been better had I said that JavaScript needs to be used to make an AJAX submission.

Whether you write the JavaScript yourself, or use a library or framework of some kind (htmx, Alpine.js, etc) - JavaScript needs to be involved. This can’t be done from the Django side.