Detailed explanation of the configuration method of loading static files in Django template

  • 2021-07-24 11:16:37
  • OfStack

1. Add: django. contrib. staticfiles under settings.INSTALLED_APPS

2. Add: STATIC_URL = '/static/' under settings. py

3.

(1) Create a new folder static under APP, then create a folder with the name of APP under this static folder, and then put static files under this folder: (similar to Templates configuration)

Called in the template as follows:


{% load static %}
<img src="{% static 'front/logo.jpg' %}">

(2) Create a new folder static under the project, and then create a folder with the same name as APP, and put all the static files used by APP in it

If there are 1 static files that are not hooked to any APP. Then you can add STATICFILES_DIRS to settings. py, and DTL will look for static files in the path of this list later. For example, it can be set to: (similar to Templates configuration)


STATICFILES_DIRS = [
  os.path.join(BASE_DIR,"static")
]

Called in the template as follows:


{% load static %}
<link rel="stylesheet" href="{% static 'index.css' %}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >

4. If you don't want to use {% load static%} every time you load a static file in the template, turn the static tag into an Django built-in tag:

(1) Add under TEMPLATES/OPTIONS in settings. py 'builtins':['django.templatetags.static']

(2) You can use the static tag directly in the template


  <img src="{% static 'front/logo.jpg' %}">
  <link rel="stylesheet" href="{% static 'index.css' %}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >

The above is a detailed explanation, and the following is my favorite configuration method:

1. Add under settings.INSTALLED_APPS: django.contrib.staticfiles

2. Add under settings. py: STATIC_URL = '/static/'

3. Add: under settings. py (some here are not [], but brackets (), but the error of not loading will be reported)


STATICFILES_DIRS = [
  os.path.join(BASE_DIR,"static")
]

4. Create a new folder static under the project, and then create a folder with the same name as APP, and put all the static files used by APP in it

5. In settings. py TEMPLATES/OPTIONS Add under 'builtins':['django.templatetags.static']

6. Use static files in templates


 <img src="{% static 'front/logo.jpg' %}">
  <link rel="stylesheet" href="{% static 'index.css' %}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >

Summarize

The above is the site to introduce the detailed explanation of Django template loading static file configuration method, I hope to help you, if you have any questions welcome to leave me a message, this site will reply to you in time!


Related articles: