Django: how do you serve media / stylesheets and link to them within templates
I just had to figure this out myself.
settings.py:
MEDIA_ROOT = 'C:/Server/Projects/project_name/static/'MEDIA_URL = '/static/'ADMIN_MEDIA_PREFIX = '/media/'
urls.py:
from django.conf import settings...if settings.DEBUG: urlpatterns += patterns('', (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
template file:
<link rel="stylesheet" type="text/css" href="/static/css/style.css" />
With the file located here:
"C:/Server/Projects/project_name/static/css/style.css"
Django already has a context process for MEDIA_URL, see Django's documentation.
It should be availbale by default (unless you've customized CONTEXT_PROCESSORS and forgot to add it) in a RequestContext.
I usually make my own Template simple tag because Django isn't giving CSS/JavaScript files. Apache does it so my media url is usually http://static.mysite.com.
yourApp/templatetags/media_url.py:
from django.template import Libraryfrom yourapp.settings import MEDIA_URLregister = Library()@register.simple_tagdef media_url(): return MEDIA_URL
And in my template file:
{% load media_url %}<link href="{{ media_url }}css/main.css" rel="stylesheet" type="text/css">
You could also make your own context preprocessor to add the media_url variable in every template.