Django Add js,css, pictures and other external files method
by White Shinhuata (http://blog.csdn.net/whiterbear) reprint should indicate the source, thank you.
When using Django to build a Web site, you often need to use some external files, such as js,css or pictures, to use them.
My Django version is: 1.8.2
Suppose we have a project as follows:
Sentiment_analysis
|-mysite
| |-mysite
| |-manage.py
| |-show_pages
| | | |-__init__.py
| | | |-admin.py
| | | |-models.py
| | | |-tests.py
| | | |-urls.py
| | | |-views.py
| | | |-tests.py
| | | |-templates
| | | | |-show_pages
| | | | | |-index.html
Under this project, suppose we need to use the external file such as JS in the index.html, can follow the following procedure to use. add an external file
Create a new static folder in the Apply Show_pages (with the manage.py sibling), where the external resource file (CSS,JS, etc.) is placed. Modify settings.py
Add the following lines to the settings.py file (one row already exists).
static_root= Os.path.join (Os.path.dirname (os.path.dirname (file)), ' Static '. Replace (' \ ', '/')
Static_url = '/static/'
Template_dirs = (
'/show_pages/templates ',
) Modify urls.py
Modify the urls.py file in the MySite directory as:
From Django.contrib Import admin
From django.conf.urls Import *
From django.conf Import settings
Urlpatterns = [
URL (r ' ^admin/', include (Admin.site.urls)),
URL (r ' ^show_pages/', include (' Show_pages.urls ')),
URL (r ' ^static/(?) p.*) $ ', ' django.views.static.server ', {' Document_root ': Settings. Static_root},name= ' static '),
] Modify manage.py
Modify the manage.py file in the MySite directory to add:
Reload = reload (SYS)
Sys.setdefaultencoding (' gb18030 ') #否则加载css文件仍会出错reference
Finally, when an external resource file is introduced into index.html, it is referenced in the following way: JS file: <script src= "/static/js/jquery.js" ></script> css file: <link href= "/static/css/bootstrap.min.css" rel= "stylesheet" > Pictures:
Or make the following reference:
First enter in the index.html file: {% load staticfiles%}, and then refer to the following method. JS file: <script src= "{% static ' js/jquery.js '%}" ></script> css file: <link href= "{% static ' css/ Bootstrap.min.css '%} ' rel= ' stylesheet ' > Pictures: