Serving Static File in Django

You need ‘django.contrib.staticfiles’ in our INSTALLED_APPS if you want Django to serve static files.


# Application definition

INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)

Django will serve the static files at STATIC_URL. By default, STATIC_URL is set to ‘/static/’. It means your static contents like css, js or images are served using the url like http://127.0.0.1:8000/static/styles.css.

So, how does Django know where to read the static files or where to find the static files in your system?

You use STATICFILES_FINDERS property in your settings like the following

STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

Appdirectoriesfinder tells Django to look into static/ subdirectory of each app in INSTALLED_APPS. You would use this approach if you have separate static contents for each installed apps but if you have some common static content that you want to share across multiple apps within your project, you would use STATICFILES_DIRS

STATICFILES_DIRS = (
os.path.join(BASE_DIR, '../common_static'),
)

Add the following at the top of your template file
{% load staticfiles %}

You can reference your static files like the following example in your template files

<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">

Browse to your template file to see the change in effect.

 

 

Serving Static File in Django

Leave a Reply

Your email address will not be published. Required fields are marked *