Static Files in Django Explained

Mangabo Kolawole - May 18 '22 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player