Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...