How to Display Static Files of a Django Project on a Live Server 


               


How to Display Static Files of a Django Project on a Live Server



Python


In this article, we show how to display static files of a Django project on a live server.

So you may notice that when you're putting your website live on the internet, everything works well and transfers well, except for static files, such as images, CSS files, and Javascript files.

So in order to rectify this and display static files, we need to do a lot of changes.

For one, we need to add a STATIC_ROOT variable into our settings.py file.

Another thing is, we need to do is run the command, python3 manage.py collectstatic

We talk about both of these below.


Settings.py File

So we need to make a change to the settings.py file.

What we need to do is add a variable, STATIC_ROOT, to the settings.py file.

The assumption that is made is that the static directory is in the same directory as all the apps. This is the directory right after the topmost directory of the project.

So if this is true that the static directory is in the same folder as all the apps, then you place the following line in the settings.py file.



This makes the static root in the folder after the topmost directory.

If your static directory is located somewhere else other than here, then simply specify this path for the STATIC_ROOT variable.

Next, we have to go to the command terminal.


Command Terminal

So we've done the update to the settings.py file.

Now we go to the command terminal and type in the following line.



What this line does is it aggregates all static files from all static directories of all apps in the project and then has them all in one folder, the one you specified in the settings.py file. This allows the static files to be served in a production environment.

So now after you run this command, you should get output of the number of files that has been collected.

When you now go back to your site, you should see static files appear on your website.

Basically, in order to show static files on a live server (in a production environment), then you need to create a STATIC_ROOT variable in the settings.py file, in which you specify the one static directory where all static files will be kept. Also, you must run, python3 manage.py collectstatic, in order for all static files in all static directories in all of the apps to be aggregated into the static directory specified in the STATIC_ROOT variable in the settings.py file.

So this is how to display static files of a django project on a live server.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...