Forums

Referencing CSS, images etc from static file in django

Hi I have a responsive web page with links to style sheets, scripts and images in it and have created a templateview. The page is appearing at /about/ but all the links are broken inc CSS and scripts. How do I correctly reference them? In the file system I have to go one level up and then down into /images, /css etc so have used ../images and ../css etc. but this doesn't work.

in recharge/recharge: settings.py ... 'django.contrib.staticfiles', ...


views.py: from django.http import HttpResponse from django.views.generic import TemplateView

class AboutView(TemplateView): template_name = "facilities_list.html"


urls.py from django.conf.urls import patterns, include, url from recharge.views import AboutView

urlpatterns = patterns('', (r'^about/', AboutView.as_view()),


Finally facilities_list.html is in recharge/templates and the folders containing the scripts, css etc are in recharge/images, recharge/css etc

What am I doing wrong?

thanks

The place to do this is the "Static files" section of your web app on the "Web" tab. There you specify which URLs map to which static files -- so for example, you could have /css mapping to /home/lz7cjc/something/somethingelse/css/. Then, in your template, you'd just refer to the static files as /css/myfile.css.

Take a look at that and I think you should be able to sort things out pretty quickly. And the advantage of serving your static files via that part of the "Web" tab is that it's much faster than serving them via Django.

thanks for the quick response - that does sound easy! So I have created the following on the web tab under static files: css /home/lz7cjc/recharge/css/
images /home/lz7cjc/recharge/images/
scripts /home/lz7cjc/recharge/scripts/
fonts /home/lz7cjc/recharge/fonts/

I then set up a test page to check this worked ahead of making all the required changes to paths called where.html

However I still get a broken link when I do the following: <img src="/images/map.png"> I still get a broken link - i assume I have got the physical paths wrong but not sure how

You should probably put a / before all of those URLs, ie. /images instead of images.

i have checked and have leading / in both the html file and also the mappings. Have I missed something? <img src="/images/map.png">

i have checked and have leading / in both the html file and also the mappings. Have I missed something? <img src="/images/map.png">

Hmm, it looks like the directory you have for /images is /home/lz7cjc/images/. Should it not be something more similar to the others, with a subdirectory name between lz7cjc and images?

d'oh - thank you

No problem!