django how to include javascript in template django how to include javascript in template javascript javascript

django how to include javascript in template


urls.py

from django.conf.urls import include, urlfrom django.contrib import adminurlpatterns = [    url(r'^admin/', include(admin.site.urls)),]

settings.py

STATICFILES_DIRS = (    os.path.join(BASE_DIR, "static"),)STATIC_URL = '/static/'# remove STATIC_ROOT

base.html

Your title tag was not closed.

<!DOCTYPE html><head>  {% load static %}  <script src="{% static 'app.js' %}"></script>     <title>Site</title></head><body><img src="{% static 'img.png' %}" alt="Mon image" />  {% block content %}{% endblock %}</body></html>


Your template should say {% load staticfiles %} instead of {% load static %}

Source:https://docs.djangoproject.com/en/1.8/howto/static-files/

Also, os.path.join(BASE_DIR, "static"), only looks for static files in your apps, as in app/static/app/static.js. If you have static files that do not belong to any specific app, but rather to the project, you need to add the folder explicitly. See point 4 of 'Configuring static files' on the docs page I mentioned.


From my understanding, the STATICFILES_DIRS should be in the settings.py and defined like this:

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

Please check the documentation.