I’m trying to add .css and .js file in my HTML template files that made for Django. I have followed the official doc, so my configurations set to:
urls.py
urlpatterns = patterns('',
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_DOC_ROOT}),
settings.py
STATIC_DOC_ROOT = ''/myfirstapp/templates/seminar_form/'
But still I couldn’t get it right, those .css .js and image files are still doesn’t load in my HTML,but those files can access (perfectly viewable) from hitting the URL on browser
like this:
http://127.0.0.1:8000/site_media/images/calendar.png
Template code
<img src="{{ site_media }}images/calendar.png">
If you can view the files by hitting the URL directly in your browser, then I’d guess you’ve got your
MEDIA_URLsettings wrong, or there’s something wrong in your template code. What URL is your HTML referencing for your CSS/JS/Images?Make sure you’re passing through your
MEDIA_URLso it’s available in your template’s context, which you do by wrapping up the request passed to your view functions in aRequestContext, like this:Provided you’ve got your
MEDIA_URLsetting correct, and you are serving your media correctly (which your question suggests you are) you should be able to access media using things like:After edit to show template code:
From your template code, it looks like you’re trying to reference files rooted at a template variable called
site_media, which probably doesn’t exist.You need to put something like this in your
settings.py:Then change your template code to something like this:
and make sure you’re passing
MEDIA_URLto your template from your view function.After comment asking for clarification about
RequestContext:The online Django book has some helpful (though currently lacking in some parts) documentation about
RequestContext. Personally, I use therender_todecorator from django-annoying to avoid having to think about it. In place of my earlier sample view code, you can just do this:Essentially, you just decorate your view function, passing in the template you want rendered, and then just return a
dictcontaining the extra context variables you want set (i.e. context variables in addition to those that are set for you byRequestContext, such asMEDIA_URL).This approach obviously doesn’t work if your view might use different templates depending on some condition, but there are simple ways around that:
Can be rewritten as:
Which seems clearer to me, at least.