2017-08-29 61 views
0

在使用Django的模板中包含javascript文件時出現一些錯誤。我在下面解釋我的錯誤。使用Django和Python包含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/文件夾。

+0

嘗試把你的文件 –

+1

'{%負載靜態%}頂部載荷靜'有間'{空間'和'%' – dirkgroten

+0

@dirkgroten:非常感謝您的支持。 – satya

回答

3

包括{% load static %}您的模板的頂部

+0

我把它放在'<!DOCTYPE html>'之前,但同樣的錯誤。 – satya

+0

嘗試一下:'http://127.0.0.1:8000/static/js/jquery.js'如果你會得到js - 所有的設置都可以。你可以在這裏粘貼代碼在哪裏進行加載? – AndMar

+0

我已更新我的代碼。請檢查。 – satya

-1

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

+0

我也是按照你的方式嘗試,但同樣的錯誤。 – satya

相關問題