Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: how to include a static file in a template?

In a Django project, I would like to include a static file in a template. The following is the the project structure:

proj/
   main/
      static/
         main/
            js/
               main.js
   news/
      templates/
        news/
           news.html

In news.html, I would like to include the main.js with the following hypothetical format:

{% load staticfiles %}
...

{% include {% static 'main/js/main.js' %} %}

How do I do it?

like image 359
Randy Tang Avatar asked Apr 13 '16 06:04

Randy Tang


People also ask

How do you serve a static file?

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express. The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express.static.

Where are Django static files stored?

Files are searched by using the enabled finders . The default is to look in all locations defined in STATICFILES_DIRS and in the 'static' directory of apps specified by the INSTALLED_APPS setting.

What is {% load static %} in Django?

The {% static %} template tag generates the absolute URL of static files. That's all you need to do for development. Reload http://localhost:8000/polls/ and you should see that the question links are green (Django style!) which means that your stylesheet was properly loaded.

What is the difference between media and static files in Django?

Static files are meant for javascript/images etc, but media files are for user-uploaded content.


1 Answers

The include directive only searches file in template directories. What you could do (although I wouldn't) is to change your settings to also include the static files:

TEMPLATE_DIRS = [
    ...
    "path/to/your/statics",
]
like image 68
Tzach Avatar answered Oct 23 '22 07:10

Tzach