Ticker

6/recent/ticker-posts

Django static files (CSS, JavaScript, images)

Django static files (CSS, JavaScript, images)
Websites generally need to serve additional files such as images, JavaScript, or CSS. In Django, we refer to these files as “static files”. Django provides django.contrib.staticfiles to help you manage them.

This page describes how you can serve these static files.

Configuring static files

1.      Make sure that django.contrib.staticfiles is included in your INSTALLED_APPS.

2.      In your settings file, define STATIC_URL, for example:

1.

STATIC_URL = 'static/'

4.      In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE.

5.

{% load static %}

6.

<img src="{% static 'my_app/example.jpg' %}" alt="My image">

7.      Store your static files in a folder called static in your app. For example my_app/static/my_app/example.jpg.

Serving the files
In addition to these configuration steps, you’ll also need to actually serve the static files.
During development, if you use django.contrib.staticfiles, this will be done automatically by runserver when DEBUG is set to True (see django.contrib.staticfiles.views.serve()).
This method is grossly inefficient and probably insecure, so it is unsuitable for production.
See How to deploy static files for proper strategies to serve static files in production environments.

Your project will probably also have static assets that aren’t tied to a particular app. In addition to using a static/ directory inside your apps, you can define a list of directories (STATICFILES_DIRS) in your settings file where Django will also look for static files. For example:

STATICFILES_DIRS = [

    BASE_DIR / "static",

    '/var/www/static/',

]

See the documentation for the STATICFILES_FINDERS setting for details on how staticfiles finds your files.

Serving the files
In addition to these configuration steps, you’ll also need to actually serve the static files.
During development, if you use django.contrib.staticfiles, this will be done automatically by runserver when DEBUG is set to True (see django.contrib.staticfiles.views.serve()).
This method is grossly inefficient and probably insecure, so it is unsuitable for production.
See How to deploy static files for proper strategies to serve static files in production environments.

Serving static files during development

If you use django.contrib.staticfiles as explained above, runserver will do this automatically when DEBUG is set to True. If you don’t have django.contrib.staticfiles in INSTALLED_APPS

Post a Comment

0 Comments