[英]Loading Javascript in Django using the static template tag
我正在嘗試按照https://docs.djangoproject.com/en/2.0/howto/static-files/上的說明進行操作,但遇到了意想不到的結果。 我有一個帶有應用程序dashboard
的 Django 項目,如下所示:
.
├── dashboard
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ ├── 0002_auto_20180227_2103.py
│ │ ├── 0003_auto_20180227_2304.py
│ │ └── __init__.py
│ ├── models.py
│ ├── static
│ │ └── dashboard
│ │ └── dashboard.js
│ ├── templates
│ │ └── dashboard
│ │ ├── checkin_detail.html
│ │ ├── checkin_form.html
│ │ └── checkin_list.html
│ ├── tests.py
│ └── views.py
├── db.sqlite3
├── manage.py
└── my_project
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
在我的項目的settings.py
中, STATIC_URL
是由django-admin startproject
創建的:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
dashboard.js
文件是一個簡單的測試腳本:
alert("Hello, world!");
我正在嘗試在checkin_form.html
模板中使用 Javascript,如下所示:
{% load static %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src={% static "dashboard/dashboard.js" %}></script>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Send message" />
</form>
我的視圖繼承自 Django 的通用視圖類:
from django.views import generic
from .models import CheckIn
class CheckInCreate(generic.CreateView):
model = CheckIn
fields = '__all__'
class CheckInUpdate(generic.UpdateView):
model = CheckIn
fields = '__all__'
但是,當我導航到該視圖呈現的 URL 時,我沒有看到帶有“Hello, world.”的警報? 有人可以向我指出此配置/實現有什么問題嗎?
您需要在這一行中添加更多引號
<script src={% static "dashboard/dashboard.js" %}></script>
它應該是
<script src="{% static "dashboard/dashboard.js" %}"></script>
當您進行開發時,最好打開瀏覽器的開發工具 (F12) 並關閉緩存。
在生產中,如果您希望用戶看到您的更改,則每次內容更改時都需要更改文件的名稱。 您可以通過添加版本號(即dashboard-v1.0.0.js
)來做到這一點。 js 世界中有很多工具可以進行縮小/版本控制等。 為你。
一段時間后,我發現 Javascript 確實有效(沒有任何額外的STATIC_ROOT
配置); 瀏覽器可能只需要一些時間來“注冊”更改。
請查看語法的答案 - 用法應該是雙引號內的單引號
src="{% static 'dashboard/dashboard.js' %}">
不是
src="{% static "dashboard/dashboard.js" %}">
這包含在“腳本/腳本”html 元素中
由於將字符串包含在字符串中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.