5

I have deployed my Django app on AWS EC2 Instance using this guide.

Everything is working fine but the error arises when I download an excel file. (Excel is created using opnenpyxl library).

While downloading an xlsx file the application is returning download.htm file. Everything work great on a development server.

I tried

  1. Adding and removing the download tag. <a href="{% url 'download_estimate_excel_file' project.id project.name %}" class="dropdown-item" download> Download Excel </a>. [Didn't Work]
  2. Adding [service] Environment="LANG=ru_RU.UTF-8" to gunicorn.service file (found this on StackOverflow also). [Didn't Work]

EDIT:

Path for Gunicorn config: /etc/systemd/system/gunicorn.service

>> GUNICRON CONFIG

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=sammy
Group=www-data
WorkingDirectory=/home/sammy/myprojectdir
ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          myproject.wsgi:application
Environment="LANG=ru_RU.UTF-8"

[Install]
WantedBy=multi-user.target

Path for Nginx config: /etc/nginx/sites-available/<myproject>

>> NGINX CONFIG

server {
    listen 80;
    server_name server_domain_or_IP;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/sammy/myprojectdir;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}
>> download_estimate_excel_file function

@login_required
def download_estimate_excel_file(request, project_id, project_name):
    project_tnc_obj = ProjectTermsAndConditions.objects.filter(
        project=project_id)
    date_time_obj = datetime.now()
    current_date = date_time_obj.strftime('%x')
    current_time = date_time_obj.strftime('%X')

    filename = project_name + '_' + str(current_date).replace('/', "-") + '_' + str(current_time).replace(":", "-") + ".xlsx"

    file_path = "media/excel/" + filename

    ...
    ...

    sheet.append([""])

    workbook.save(filename=str(file_path))
    workbook.close()
    file_ecxel = FileResponse(open(file_path, 'rb'))
    delete_file = os.remove(file_path)
    return file_ecxel

>> UPDATED download_estimate_excel_file function

@login_required
def download_estimate_excel_file(request, project_id, project_name):
    project_tnc_obj = ProjectTermsAndConditions.objects.filter(
        project=project_id)
    date_time_obj = datetime.now()
    current_date = date_time_obj.strftime('%x')
    current_time = date_time_obj.strftime('%X')

    filename = project_name + '_' + str(current_date).replace('/', "-") + '_' + str(current_time).replace(":", "-") + ".xlsx"

    file_path = "media/excel/" + filename

    ...
    ...

    sheet.append([""])

    workbook.save(filename=str(file_path))
    workbook.close()

    with open(file_path, "rb") as excel:
        data = excel.read()
    delete_file = os.remove(file_path)

    return HttpResponse(data, headers={
        'Content-Type': 'application/vnd.ms-excel',
        'Content-Disposition': 'attachment; filename= "{}"'.format(
            filename),
    })

Thanks in advance.

Strike
  • 164
  • 1
  • 13
  • 2
    Do you an error code ? Do you have logs file so we can help you better ? – Gaëtan GR Sep 05 '22 at 05:51
  • No actually, No error code. I am new to using gunicorn and the entire deployment, ergo cannot locate the exact location of the logs(if present). – Strike Sep 05 '22 at 07:26
  • `@GaëtanGR` Can you guide on how can I fetch the logs? – Strike Sep 05 '22 at 07:32
  • Can you share the server block of your nginx configuration? Especially the location block of your files endpoint. – Marco Sep 05 '22 at 07:52
  • 1
    chek this directory `cd var/log/nginx`, `/var/log/gunicorn` – Hemal Patel Sep 05 '22 at 12:16
  • @Marco Please have a look at the config, and you can also look at the blog that I referred to while configuring (Link is mentioned in the question- line 1). – Strike Sep 05 '22 at 21:25
  • 1
    Looks good so far. Please provide the handling view behind `download_estimate_excel_file`. Especially how you build the response. – Marco Sep 05 '22 at 21:47
  • Hi, @Marco Please do check the function. I have updated it. – Strike Sep 07 '22 at 05:05
  • You can set headers on the response to tell the client that the file is expected to be downloaded, and suggest the name of the file it should be saved as: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition – Marcel Besixdouze Sep 07 '22 at 05:06
  • @HemalPatel I've checked the mentioned directories `var/log/nginx` and couldn't find anything that stands out or shows an error. Also couldn't find `var/log/gunicorn` directory. – Strike Sep 07 '22 at 05:08
  • @MarcelBesixdouze I am not familiar with using Headers, Could you be able to tell me in detail? Especially how and where to put the headers! Thanks. – Strike Sep 07 '22 at 05:10
  • 1
    @Aditya I can point you to the django docs: https://docs.djangoproject.com/en/4.1/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment They use an excel file in their example. – Marcel Besixdouze Sep 07 '22 at 05:11
  • @MarcelBesixdouze I tried following the documentation where you pointed out, now upon downloading it is giving `Server Error 500` – Strike Sep 09 '22 at 19:37

0 Answers0