开发者

How to include external css, image, etc in django template?

In django, all urls are parsed from urls.py file. So, there is no directory structure as such.

So, what if you have to include a css file in your template ?

Is there a way without adding it to url.py file ?

I开发者_如何学Gof no, then will you make new entry in urls.py for every resource ?


See the Django HOWTO on static files.

Basically, in your configuration file, you specify a special directory to store static files in. The example in the docs is:

STATIC_ROOT = "/home/jacob/projects/mysite.com/sitestatic"

You put CSS files, images, etc. in there, and the server will know to serve URLs that match your static URL pattern from that directory.


You no longer need to specify STATIC_ROOT (for djangor > 1.10). Simply, make sure

django.contrib.staticfiles

is included in INSTALLED_APPS

and

STATIC_URL = '/static/'

in your settings.py

Create a directory called "static" in your app directory, and inside the created static directory, another subdirectory named your app and include the static files there (you could also create js, img, css subdirectories inside the last directory based on your preference if you need)

Then, include the correct path in the template file. For ex:

src = "/static/my_app/example.js"

or

src = "/static/my_app/js/example.js"

(assuming your javascript files are in a directory called js)

Alternatively (much better), define the path using the static template tag:

{% load static %}
<script src="{% static "my_app/js/example.js" %}"></script>

All you need to know:

https://docs.djangoproject.com/en/1.10/howto/static-files/


In my root urls.py file, I use this pattern to serve static files when developing locally. I also add a setting called SERVE_STATIC_MEDIA so I can separate it from DEBUG.

if settings.SERVE_STATIC_MEDIA:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', 'django.views.static.serve', \
            {'document_root' : settings.MEDIA_ROOT}),
    )

Then in a template, you can access css, js, images, as such:

<link type="text/css" href="{{ MEDIA_URL }}css/foo.css" media="screen,projection" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜