Configuration method for Django static resource URL STATIC_ROOT

  • 2020-04-02 14:19:22
  • OfStack

The reason

When a novice learns Django, after configuring HTML pages, you need to use some static resources, such as images, JS files, CSS styles, etc., but using these resources in Django is not a direct reference to the good, but also to configure the path that is STATIC_URL if this configuration is not good, the request for these static resources will return HTTP 404.

Experience teaches

1. Output the STATIC_URL in the settings.py file to the HTML page to see what the physical path points to, usually out of the root directory. Here's a DEMO:


def home(request):
    t = get_template("index.html")
    html = t.render(Context({
        "template_dir":settings.TEMPLATE_DIRS[0],
        "title":"Home",
        "static_dir":settings.STATIC_ROOT}))
    return HttpResponse(html)

This way the visited HTML page can see the paths.

2. Configure the STATIC_ROOT variable


STATIC_ROOT = os.path.join(os.path.dirname(__file__), '..', 'templates/content').replace('\','/')

It is possible to modify the path correctly by adjusting the second and third parameters. (multiple debugging)

3. Configure the urlpatterns variable in the urls.py file (see highlighted line) :


urlpatterns = patterns('',
    url(r'^$', home),
    url(r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATIC_ROOT}),
)

4. Test the above configuration:


<head>
    <meta charset="UTF-8"/>
    <title>{{ title }} - Oger</title>
    <script type="text/javascript" src="/static/scripts/jquery-1.11.0.min.js"></script>
</head>

or

< The head >
      < Meta charset = "utf-8" / >
      < The title > {{title}} - Oger < / title >
      {% load staticfiles %}
      < Script type="text/javascript" SRC ="{% static 'scripts/jquery-1.11.0.min.js' %}" > < / script >
< / head >
[/ code]

Both are fine.

Django is handy for developing Web sites. Keep learning...


Related articles: