Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

629
Visualizações
Django - download file without reloading the page

The flow looks like that:

  1. user is filling the form
  2. form is passed to the server by ajax
  3. form is saved to db, then the pdf with the form data is created and saved in the app folder (probably a bad move here...)
  4. ajax success causes the page to append a button 'Download' with value equal to current pdf's name so button 'Download' appears to the user
  5. If user presses the button the very pdf that was just saved is gonna download.
  6. Refreshing the page makes the button disappear.

I've got stuck on point 5. I have created another ajax (to avoid reloading the page) bound to the Download button. It correctly asks the server to look for the file, creates a django File object: pdf_file = File(open(file_path, 'rb')) and creates a HttpResponse with file, and content_type='application/pdf' or 'application/download'. response['Content-Disposition'] is attachment.

Then the ajax returns response - only it does not. Server raises no error but ajax error function is called.

I've read that downloading with ajax is not possible. Could you help me a bit to get it straight? If above snippets are not clear, I shall provide more code. Python 3.5, Django 1.10

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Do like

window.location.href = "/url/to/downloadfile/"

in javascript after success of posting form. OR

#html
<button onclick="myfiledownload()">Download</download>
#javascript
function myfiledownload(){
    window.location.href = "/url/to/downloadfile/"
}
over 4 years ago · Santiago Trujillo Relatório

0

Instead of using ajax to download the file bind the button to a download link where the file may be hosted

https://www.mywebsite/download/?fileid=3247023

You should at least seperate your file in a media root Note: in production you will have to use a cdn to host your static files

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda