Codementor Events

Using bower to manage static files with Django

Published Feb 23, 2018
Using bower to manage static files with Django

Using bower to manage static files with Django
Sharing a way to manage libraries like bootstrap, jquery with bower without using any external app.
first of all create aur django project by usign virtualenv . Make sure you have bower installed in your system

virtualenv env_demo
source env_demo/bin/activate
pip install django==1.10
django-admin.py startproject demo
cd demo
bower init

Now we are good to install any library with bower,
try

bower install bootstrap --save
bower install jquery --save

This will create bower_components folder in our django project directory and we will have libraries files there.
— save option forces bower to mark them inside bower.json as well, which is important (as you’ll see in later part of this blog post).
Now lets setup our django project to use them. we need to add these to settings.py file

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'bower_components'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

In layman terms
STATICFILES_DIRS : where django looks for files to be collected from.
STATIC_ROOT : where collectstatic command collects the static files from locations mentioned in static files directories.
So basically, we have configured collectstatic to transfer our bower components to static folder.
Now lets run collectstatic
python manage.py collectstatic
Now we have our library files in static folder,.
which can be used in django templates using static tag, example :

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

We should add bower_components directory to .gitignore, any peer working on your project (or you yourself on the server) can install libraries by just running
bower install
That’s all we need to manage static files 😃

Discover and read more posts from siddhesh suthar
get started
post commentsBe the first to share your opinion
Show more replies