All the Django Deployment (web or rest frameworks) needs to have a setup for serving static files and most of the time it create trouble. There are 3-4 steps that will make it working :
- Setting into Django Project settings.py
- Setting into Nginx config file
- Collecting all static file
- (Optional) Moving the static file
1. Setting into Django Project settings.py
The default and most of tutorial suggest to have following configuration in project's settings.py
STATIC_URL = "static/"
import os
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
For this example, let's have same configuration.
Note: we assume that you are already setup your nginx and running it. For this example, the nginx is running on AWS's EC2.
2. Setting into Nginx config file
In your Nginx server confirguration block you will have following (or similar, depending upon the path of /static) configuration for serving static file.
Note: It is suggested to have static folder in a location that is under control by Ngnix without any trouble. for example i.e. /var/www/
location /static/ {
root /var/www/PROJECT_NAME;
}
3. Collecting all static file
To collect static file, you run following command:
$python manage.py collectstatic
The output of collectstatic depends upon the given path in step 1. i.e. (STATIC_ROOT = os.path.join(BASE_DIR, "static/")
So, the output will be stored inside the project root directory.
4. (Optional) Moving the static file
This step is optional if the path of collectstatic and nginx configuration is same. Ohterwise, we need to move the /static folder to /var/www/PROJECT_NAME (this is followed in this tutorial).
- Create project folder in /var/www/ (need root permission so use sudo) var/www$sudo mkdir project_name
- Move static from your project to /var/www/project_name project_name/$ sudo mv -r static/ /var/www/project_name
And your static files should be working. Restart gunicorn and ngnix for any changes to take effect.
Top comments (0)