首页 > 解决方案 > 在 Django 中使用 JS 库

问题描述

我在 django 中使用 js 库时遇到问题。我正在尝试使用particle.js库为主页生成粒子背景,我尝试按照本教程进行操作。

我在我的静态文件夹中创建了一个particle.jsonand 。style.css

更新版本(带有静态文件)

主页.html

<!-- templates/home.html --> 
{% load socialaccount %}
{% load account %} 
{% load static %}

<head>
    <link rel="stylesheet" href="{% static 'style.css' %}"> </head>

<body>
    <div id="particles-js">

        {% if user.is_authenticated %}
        <p>Welcome {{ user.username }} !!!</p>


        <a href="/accounts/logout/" >Logout</a>
        {% else %}
        <a href="{% provider_login_url 'github' %}">Log In with Github</a>
        <a href="{% provider_login_url 'twitter' %}">Log In with Twitter</a>
        <a href="{% provider_login_url 'facebook' %}">Log In with Facebook</a>
        <a href="{% provider_login_url 'linkedin' %}">Log In with LinkedIn</a>
        {% endif %}
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/particlesjs/2.2.2/particles.min.js"></script>
    <script>
        particlesJS.load('particles-js', '{% static 'particles.json' %}', function(){
            console.log('particles.json loaded...');
        });
    </script> </body>

定义了静态路径settings.py

STATIC_URL = '/static/'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

STATICFILES_DIRS = [
   os.path.join(BASE_DIR, 'artemis/static')
]

我是我的urls.py文件

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url('accounts/', include('allauth.urls')),
    url('', views.Home.as_view(), name='home'),
] + static(settings.STATIC_URL)

当我启动服务器时,我在控制台中收到以下错误:

GET http://127.0.0.1:8000/static/ net::ERR_ABORTED
Uncaught ReferenceError: particlesJS is not defined

项目结构:

在此处输入图像描述

我刚开始学习 django,所以我知道这听起来像是一个愚蠢的问题,但知道这里可能出了什么问题吗?

标签: javascriptdjango

解决方案


Django 无法解析余数:

{% static style.css %}这应该{% static 'style.css' %}带引号

{% static particles.json %}应该{% static 'particles.json' %}带引号


推荐阅读