DEV Community

Cover image for Static Files in Django Explained
Mangabo Kolawole
Mangabo Kolawole Subscriber

Posted on • Originally published at Medium

Static Files in Django Explained

When adding styling or interactivity to your website using CSS or JavaScript, you need to understand the concept of static files in Django.

Static files includes files like CSS, JavaScript, and images that you may want to serve alongside your side. Before adding static files in your settings.py file.

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0.0/howto/static-files/

STATIC_URL = '/static/'
Enter fullscreen mode Exit fullscreen mode

This configuration makes static files available at localhost:8000/static/ when the server is launched. We need now to tell where Django can find the static files in the project.

STATIC_URL = '/static/'

# Add these new lines
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
Enter fullscreen mode Exit fullscreen mode

The STATICFILES_DIRS file tuples tell Django where to look for static files. In this case, the static files are stored in a folder called static at the root folder.

Django also comes with a mechanism for collecting static files into one place so they can be served efficiently. This is the goal of STATIC_ROOT.
When using the python manage.py collectstatic command, Django looks for all static files in the apps and collects them in the STATIC_ROOT path, then in the staticfiles.

This feature is handy for serving static files, especially in production settings.

You can learn more about static files in Django here.

Article posted using bloggu.io. Try it for free.

Top comments (7)

Collapse
 
mikolajbuchwald profile image
Mikołaj Buchwald

Nice! Maybe you can write the next one on serving Django's static files with Apache or Nginx? :)

Collapse
 
koladev profile image
Mangabo Kolawole

Hey, I hope you are doing well. Just wrote it with NGINX.

dev.to/koladev/serving-djangos-sta...

I haven't used Apache yet, but once it's done I'll write about it. :)

Collapse
 
mikolajbuchwald profile image
Mikołaj Buchwald

Nice, thank you!

The next level is dockerizing the whole thing, I think :) I already saw some posts on that (in fact I use a similar setup in one of my projects), but maybe you can do a better tutorial/showcase ;)

Thread Thread
 
mikolajbuchwald profile image
Mikołaj Buchwald

Pardon me, I see that you already used docker :)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Nice good info.

Collapse
 
sm0ke profile image
Sm0ke

cool

Collapse
 
koladev profile image
Mangabo Kolawole

🚀