Django Unable to find static resource files after using templates

  • 2021-07-22 10:56:06
  • OfStack

Environment configuration

Django Version 1.11 python version 3.6. 2

Preface

When writing the Django Web site, there was no problem with the simple examples when it came to templates, but they all had one thing in common, that is, the templates used did not have the required static resource files. When it comes to static resource files needed in templates, such as css, js and other files, if we don't do anything, we will put them into templates files directly according to the front-end ones, that is, the following form:


|templates

|----js

|--------xxxx.js

|----css

|--------xxxx.css

|----xxxx.html

When running the website, we will find that everything that needs to be loaded is not loaded. The reason is that when rendering the page, the processor of Django corresponds to the root directory, so we actually use the static resource file under the root directory (actually there is no one), so there will be 404 errors.

Solution

First, there should be the following code in the settings. py file


STATIC_URL = '/static/'

This is used to define the static directory URL, which has been given

In each template to use static resources, we should change the path to the directory under static, such as


/static/my_app/example.jpg

Or


 {% load static %}
 <img src="{% static "my_app/example.jpg" %}" alt="My image"/>  

Of course, without using static, you can define your own directory for storing static resource files, as follows:


 STATICFILES_DIRS = [
 os.path.join(BASE_DIR, "static"),
 '/var/www/static/',
 ]

What we need to pay attention to is that, The static folder here is the static folder under the app of the template you referenced, Try not to put resources in the static folder under the root directory, because the static folder 1 under the root directory is generally used to copy all the files in all the folders in STATICFILES_DIRS and the files in static in each app, so that it is more convenient to put these files into 1 and deploy them with apache, as follows


STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static')

We define an collected_static to collect all static resource files in the root directory.


Related articles: