Question

Django + nginx + gunicorn - Media Files Not Working

Posted March 22, 2019 5k views
Nginx Django Deployment Ubuntu 16.04

Hello, I have deployed a Django project on Ubuntu 16.04 with Nginx and Gunicorn. I have gotten everything, including the static files but my media files will not serve properly.

settings.py

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

In my project I allow users to upload a file through a Model, which gets passed into a ModelForm and the code for the model field is below.

models.py

resume_upload = models.FileField(blank=False, upload_to='resumes', null=True, validators=[FileExtensionValidator(allowed_extensions=['pdf']), validate_file_size])

What I have listed in /etc/nginx/sites-available/ is


server {
    listen 80;
    server_name website.com www.website.com ;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/syed/btawebsite;
    }

    location = /media/ {
        root /home/syed/btawebsite;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/syed/myproject.sock;
    }
}

I would like go on the admin, click on the uploaded file and be able to view the file in the browser. Anyone have any ideas on how I can achieve this? I have verified through using the terminal and looking through the directories that the files are in fact adding to ~btawebsite/media/resumes but I am unable to view them when I click the admin url.

When I click on that url I get an error:

Not Found
The requested resource was not found on this server.

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

1 answer

Greetings!

I think it may be the trailing slashes. Try changing this:

    location /static/ {
        root /home/syed/btawebsite;
    }

To this:

    location /static {
        root /home/syed/btawebsite;
    }

Jarland

Submit an Answer