Wednesday 14 May 2014

Django Collectstatic usage

Django Collect Static Usage
After some project completed and had a common project template layout directory , usually we will want to reuse the previous project template. But there are some static files which not belong to new project anymore. This needs time to fix.

The question is, can we put the static files for an application in their own static folder, not in the project static file it self? so when we use the app in django project, we also no need to copy to project wide static folders, which served by the webserver, usually Nginx or apache.

So come the rescue Collectstatic command in the Django admin. These feature available since Django1.3, but i actually never used it until now i understand how to implement it, and it's smart. So how to use it? I will share the step-by-step to make the collectstatic run without hassle and give speed up in development. This run with Django < 1.6 as i write this.

Step 1 :

in your settings.py :

STATIC_ROOT = '/usr/local/www/1millionproject/collected_static'



Then let say you have an app called ordernow

Step2 :

create a static folder and put any static directory or files in the folder.

ordernow/static/orderstyle.css
ordernow/static/images/produt1.png

So what happend and how to get the static file in the correct path inside project ?

Step 3 :

From your project root directory run the collectstatic command :

$python manage.py collectstatic

Then you will get a prompt and warning if you want to proceed to collect all the static files in your application folder and put it in the STATIC_ROOT location you state in Step 1.

Then make sure you set the STATIC_ROOT accessible from the webserver which will serve the static files.

In your Django code, use it as usuall with {{ STATIC_URL }} in your template files.

So the benefit of using collectstatic command is you won't need the copy command to your initial project files. Also when deploy to the production server, just issue collectstatic command and all the static files will copied from the app folder to your public static folder.

This is one of some nice features Django have. I love it especially you have many reusable app with its own static files. All will be in 1 place in the application specific directory.

How about your way, you can give a comment and share.

Thanks for reading.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More