使用Django和Python包含javascript文件时出错

时间:2017-08-29 17:40:50

标签: javascript python django

我在使用Django在模板中包含javascript文件时遇到了一些错误。我在下面解释我的错误。

错误:

TemplateSyntaxError at /
Invalid block tag on line 6: 'static'. Did you forget to register or load this tag?
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 1.11.2
Exception Type: TemplateSyntaxError
Exception Value:    
Invalid block tag on line 6: 'static'. Did you forget to register or load this tag?
Exception Location: C:\Python34\lib\site-packages\django\template\base.py in invalid_block_tag, line 571
Python Executable:  C:\Python34\python.exe
Python Version: 3.4.4

我正在解释下面的代码。

settings.py:

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

PROJECT_DIR = os.path.dirname(__file__)

""" Internationalization """

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


""" Static files (CSS, JavaScript, Images) """

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')

urls.py:

"""Neuclear plant URL Configuration"""
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
admin.autodiscover()

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('plant.urls')),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

base.html:

 <!DOCTYPE html>
<html lang="en">
  <head>
<meta charset="utf-8">
{ % load static %}
<script type="text/javascript" src="{% static 'js/jquery.js' %}"></script>
  </head>
  <body>
    <header>
      <h1>Nuclear Reactor</h1>
      {% if count > 0  %}
      <b>Hi, {{ user.username }}</b>
        <a href="{% url 'home' %}">Home</a>
        <a href="{% url 'view_reactor' %}">View Reactor status</a>
        <a href="{% url 'logout' %}">logout</a>
      {% else %}
        <a href="{% url 'login' %}">login</a> / <a href="{% url 'signup' %}">signup</a>
      {% endif %}
      <hr>
    </header>
    <main>
      {% block content %}
      {% endblock %}
    </main>
  </body>
</html>

在上面的模板文件中,我收到错误。在这里,我需要在此模板中包含js文件。我的项目目录中还有static/js/文件夹。

2 个答案:

答案 0 :(得分:3)

在模板顶部添加{% load static %}

答案 1 :(得分:-1)

在urls.py中添加urlpatterns += staticfiles_urlpatterns()