Using css, Javascript in Django templates
Test environment
(r’^css/(?P.*)$’, ‘django.views.static.serve’, {‘document_root’: ‘/var/www/django-demo/css ‘}),
(r’^js/(?P.*)$’, ‘django.views.static.serve’, {‘document_root’: ‘/var/www/ django-demo/js’}),
(r’^images/(?P.*)$’, ‘django.views.static.serve’, {‘document_root’: ‘ /var/www/django-demo/images’}),
Use the following method in the template:
Note: os. path.dirname(globals()[“__file__”]) to get the path of the current file, such as
(r’^css/(?P.*)$’, ‘django.views .static.serve’, {‘document_root’: os.path.dirname(globals()[“__file__”])+’/css’}),
You can use os.path.abspath() The function returns the absolute path of this path.
==============
To reference static files such as css, js, gif, etc. in django’s template file, first create a setting.py The DEBUG switch is turned on.
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/(?P. *)$’,’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:
Online environment
The use of css cannot be avoided in web projects developed with Django , Javascript, js and other static files. As for the processing of these static files, Django’s official website writes: Django itself doesn’t serve static (media) files, such as images, style sheets, or video. It leaves that job to whichever Web server you choose. That is to say, Django itself does not process static files such as pictures, style sheets, videos, etc. It hands over this work to the Web server you choose.
In the examples of Django projects processing static files searched on the Internet, everyone seems to be using the following method to let Django process static files:
?View Code PYTHON
urlpatterns += patterns('', |
As for the django.views.static.serve method, the django official website makes it very clear: Using this method is inefficient and insecure . Do not use this in a production setting. Use this only for development. This means that this method is inefficient and unsafe. Do not use this method in a production environment, only use it in a development environment.
At this time, we can only use the web server of our choice to process static files. For example, if you use nginx server, you can set it as follows:
First set settings.py, as follows,
Set settings.py
Then set the corresponding website of nginx The configuration part is as follows,
Configure nginx