What are these files? How do we collect static files? How will we deploy our static files? And how can we use them to our projects? Know the answers here!
Previous Lesson: Lesson 50: Give Blog Posts A URL
Websites generally need to serve additional files such as images, JavaScript, or CSS. In Django, we refer to these files as “static files”.
Create Your Own Static Files
- Write something about something. It may be about yourself, about your portfolio website, or about anything. Entitle it About or About Me. And then download this document as a PDF file.
- After doing that, look for your own picture (or you can take your own picture or selfie now). And also download it as a jpg or png file.
- Make sure that these two files are close together since we’re gonna do something about them.
Okay? Good.
Static Folder
So here I’m inside our portfolio-project:
And then here inside our portfolio folder:
We’ll create a new folder and name it static:
Now, let’s grab our static files (the About.pdf and your picture) and place them right inside this folder:
To summarize, it’s located right here: Other Projects/portfolio-project/portfolio/static. Now, we can go to our text editor and see these static files there:
Do you see that these files are colored green? It just means that these are new added files. Now here on our settings.py:
We’ll say these:
On Line 131, we specified STATIC_ROOT and then we had a URL for the static. On Line 127 down to Line 129, we added STATICFILES_DIRS.
This informs Django about the static files regarding their locations. That’s why we did the portfolio/static/, because our static files are inside the static folder, which is inside the portfolio folder.
Collect Static Files
Open up the Terminal:
Here, we’ll say python3 manage.py collectstatic:
ENTER:
By doing this, all our static files are now copied from our static folders into the STATIC_ROOT directory. Cool! Now as you can see here, this command created a new folder for us:
You can go ahead and open this folder up. When I opened it up, I found my About.pdf:
And I also found my own picture:
Oh yeah. Looking sharp eh? I’m showing these to you so that you will not get surprised once I have uploaded these files to my portfolio. And then, we have this new admin stuffs:
We don’t need to worry about these in this project.
GitIgnore Saves the Day!
You maybe wondering: “Why was this new static folder created out the portfolio folder? That’s because of this baby right here:
Remember? We did that. And that’s okay because we don’t want anyone to see our admin folder and everything in it. However, the static folder inside the portfolio folder will still be committed to GitHub. Take a look at the files as you commit our changes in them:
See? Our About.pdf and image gets committed but not our admin folder! How cool is that? On the next lesson, we’ll place our image on the homepage. See you there!