使用静态模板标记在Django中加载Javascript

问题描述 投票:0回答:2

我正在尝试遵循https://docs.djangoproject.com/en/2.0/howto/static-files/上的说明,但我遇到了意想不到的结果。我有一个Django项目与应用程序dashboard像这样:

.
├── 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!”的警报。有人能指出我这个配置/实现有什么问题吗?

javascript python django
2个回答
1
投票

您需要此行中的更多报价

<script src={% static "dashboard/dashboard.js" %}></script>

它应该是

<script src="{% static "dashboard/dashboard.js" %}"></script>

当你开发它时,打开浏览器的开发工具(F12)并关闭缓存是一个好主意。

在生产中,如果您希望用户看到您的更改,则每次内容更改时都需要更改文件的名称。你可以这样做,例如通过添加版本号(即dashboard-v1.0.0.js)。 js-world中有很多工具可以进行缩小/版本控制等。为了你。


0
投票

过了一会儿,我发现Javascript确实有效(没有任何额外配置的STATIC_ROOT);浏览器可能只需要一些时间来“注册”更改。

© www.soinside.com 2019 - 2024. All rights reserved.