Handling Static Files in Django
I have been working with Django for the past couple of months at work. Through this time, I have learned quite a bit, and solidified some other skills. I will be writing a few post to summarize what I l have learned as well as little notes on things, I will unfortunately forget as time goes on.
One simple thing that I have constantly having trouble with is dealing static files in development vs. static files in production.
So I am going to outline the final way I decided to deal with this in Django 1.3. This follows very closely to the documentation, just less ambiguous for me. So please don't nerd on the fact that the docs are clear, they are great. The way you want to have your django static files organized is as follows, each application has it own static directory, which contains files specific to that application.
Here is the structure of an app I have been working on.
I will get into how I like to structure my Django projects in the future; it has been a process of stealing and refining what I need over time. Anyways inside this project there are several application directories used for storing app logic. Shown below.
Nothing new here. The way I have found to have the best environment for storing and serving static files in development is to have a static directory for which each app, which deals with its static files. Now that being said that brings up a couple of other issues as to where to homepage and other generic views, I usually tend to write another simple application to hold simple navigation pages as well, for some specific reason these were avoided in this project.
So as you can see above within the game application, I have stored static files within the app! Which is automatically served by Django in development, due to this little magic.
Boom static files in development. Now you maybe wondering great you taught me this now how do I handle things when I am want to run them in production. Well what you would like to do in development is to have these files collected and stuck somewhere so they can be served.
Enter collectstatic command.
The -n option is for dry-run so you can see what will be copied, and make sure that the directories are being found and put in the correct spots and check for collisions. Then you simply point your server to this directory and all your static files will be served.
https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/
https://docs.djangoproject.com/en/dev/howto/static-files/
Hours spent trying to make sense of it after I forget again and again!