Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

python - django how to include javascript in template

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...