Fix Static File(CSS, JavaScript, Image) Error in Django Production with Nginx

preview_player
Показать описание
# How to Deploy Django in Production (Worst Nightmare of All Time!)
Hello internet! Checkout the blog for better view of th description.
If you are a python Django developer, you know that everything goes wrong when you do this:
```
DEBUG = False
```
Your javascript, css, images, these static contents stop working. Today, we'll put an end to this using nginx.
For demonstrating purposes, I'll be using Ubuntu Server 18.04.2 in my virtual box ( SAY NO XAMPP!!! One should NEVER use XAMPP!!! ). Follow my instructions precisely, and you should be just fine.

## Prerequisites:
1. Django basics
2. Linux basics
3. working with terminals
4. working with a terminal based editor (eg, vim, nano etc. ) I'll be using vim as I'm used to it. But feel free to use whatever you like.
## Steps

2. install ubuntu server (or anything else of your choice) in a virtual box. Make sure you keep a clone of your newly installed os as you are probably going to break things. The backup will probably save you some time.
3. install nginx:
``` sudo apt-get install nginx ```
4. Bring your project inside the virtualbox. In my case,
I cloned it somewhere, say, ```/home/(user-name)/```, so the project root is ```/home/(user-name)/(project-name)```, and in my case it is ```/home/fahimfarhan/webapp```

5. goto ```$ cd /etc/nginx/sites-available ```
We need to create some files here. Remenber, this location has permission related issues. So, either change permissions, or use sudo command. I'll stick to sudo.
```$ sudo touch (project-name)```, in my case, that is
```$ sudo touch webapp```. Then ``` $ sudo vim webapp```

6. Now type in this:

server {
listen 8000;
server_name 0.0.0.0;

location /static/ {
root /home/(user-name)/(project);
}

location / {
include proxy_params;
}
}

Adjust (username) , (project) as needed.
7. If you have multiple projects, you will have to change the port number.
8. save the file, and create a link:
``` sudo ln -s /etc/nginx/sites-available/webapp /etc/nginx/sites-enabled ```
After that, restart nginx:
``` $ sudo service nginx restart ```
9. Goto your project root directory, ``` $ cd ~/webapp/``` and run this command:
``` gunicorn --daemon --workers 1 --bind unix:/home/(username)/(project)/(project).sock (project).wsgi ```

This should do the trick.
10. (Optional) To automate things, you can simply write a script file, add the commands in the file, and use crontab.
## References
Рекомендации по теме
Комментарии
Автор

It was really helpful sir... couldn't find this anywhere... Thank u... <3

mainakdebnath
Автор

very nice... i was struggling setting up static files... saw several videos and read forums.. nothing worked .. And then i stumbled upon this video... and viola thing worked like a charm! Thanks a ton!

subeed
Автор

Vaiya kali linux er kichu tutorial lagbe

geniusgamer
Автор

502 Bad Gateway :/ why I got this problem

angeldavid