I'm starting a project and following the documentation I didn't succeed to include javascript.
Here is my settings:
STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_ROOT = '/static/' TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), )
So I have a static folder create in my project with a javascript file.
myproject/static/app.js
my urls.py:
urlpatterns = [ url(r'^$', 'app.views.home'), url(r'^admin/', include(admin.site.urls)), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
and in my template: this is myproject/templates/base.html:
<!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>
My other template:
{% block content %} hello world {% endblock %}
I have the "hello world" on
http://127.0.0.1:8000/
but i do not have my image or script.
I tried so many different things but I never succeed
We wanted Django's template language to be usable for more than just XML/HTML templates. You can use the template language for any text-based format such as emails, JavaScript and CSV.
Adding JavaScript to Our Django Template js file, put it in a js folder that you need to create in the static folder of your application. We use the static template tag to specify the relative URL to the JS file.
You cannot use python code in django template. This is by design, Django's idea of template is to isolate the presentation logic from the programming code.
urls.py
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With