Friday, March 29, 2013

Confusion about Static Files

I am experienced with Python but new to Django and web development in general. I am struggling to understand its static files system from the documentation. It seems like I have to set multiple settings variables and create multiple folders in order to get the server to accomplish the simple task of "finding" these files. After toying with it for a few hours I haven't been able to get the static files system to work and and have resorted to the following system which is probably a very bad idea:

In views.py:

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
import datetime
import os.path
import settings

statictypes = {".css": "text/css",
               ".js": "text/javascript"}

def servestatic(request, filename):
    fullfilename = os.path.join(settings.STATIC_ROOT, filename)
    ext = os.path.splitext(filename)[1]
    return HttpResponse(open(fullfilename).read(), content_type=statictypes[ext])

And in urls.py:

from django.conf.urls import patterns, include, url
import mysite.views as views

staticextensions = [ext[1:] for ext in views.statictypes.keys()]
staticextstring = '|'.join(staticextensions)

urlpatterns = patterns('',
...
    (r"([^/]+\.(?:%s))$" % staticextstring, views.servestatic)
)

This actually works (and I could optimize it by caching the static file contents in memory rather than continually rereading them), but of course it's circumventing Django's built-in system for managing static files. My project architecture looks like this:

mysite
|
|--manage.py
|--mysite
   |
   |__init__.py
   |settings.py
   |urls.py
   |views.py
   |wgsi.py
   |--static
   |  |
   |  |--jquery.js
   |  |--TestFormat.css
   |
   |--templates
      |
      |--TestTemplate.html

At the beginning, the documentation page mentions, "For small projects, this isn't a big deal, because you can just keep the static files somewhere your web server can find it." This sounds like the simple solution I'm looking for; what does it mean and how do I do it? I'm also frequently confused by how when I created the project it created two nested folders with the same name. Which is considered to be the "project root"?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments:

Post a Comment