Home > Article > Backend Development > Using css and javascript in Django templates
Use css, javascript in Django template
(r'^css/(?Ppath.*)$', 'django.views.static.serve', {'document_root': '/var/www/django-demo /css'}),
(r'^js/(?P/pathpath.*)$', 'django.views.static.serve', {'document_root': '/var/www/django-demo/ js'}),
(r'^images/(?P/pathpath.*)$', 'django.views.static.serve', {'document_root': '/var/www/django-demo/images '}),
Use the following method in the template:
link href="/css/demo.css" type="text/css" rel="stylesheet"
Note: os.path can be used. dirname(globals()["__file__"]) to get the path of the current file, such as
(r'^css/(?Ppath.*)$', 'django.views.static.serve', {'document_root' : os.path.dirname(globals()["__file__"])+'/css'}),
You can use the os.path.abspath() function to return the absolute path of this path.
==============
To reference static files such as css, js, gif, etc. in django's template file, first turn on the DEBUG switch in setting.py.
1. Create a directory to store static files in the project directory, such as: medias
2. Add a line to url.py patterns:
(r'^site_media/(?Ppath.*)$',' django.views.static.serve',{'document_root':settings.STATIC_PATH}),
Also from django.conf import setting
3. Add a line to setting.py:
STATIC_PATH='./medias '
After setting this, you can reference the static files stored in media in the template file, such as:
img src='/site_media/django.gif'