【问题标题】:Django not finding static js scripts in the correct folderDjango 在正确的文件夹中找不到静态 js 脚本
【发布时间】:2020-02-14 08:02:07
【问题描述】:

我已经运行 collectstatic 并在我的 urls.py 中创建了静态目录,并且所有其他静态文件都可以正常工作(引导程序、自定义 CSS),并且同一目录中的其他脚本也可以正常工作。

这是控制台中的错误代码。

Failed to load resource: the server responded with a status of 404 (Not Found) ... jquery.formset.js:1

(http://localhost:8000/static/js/django-dynamic-formset/jquery.formset.js)

(index):86 Uncaught TypeError: $(...).formset is not a function
    at (index):86

对于第二个错误,我之前遇到过类似的问题。将 jQuery CDN 标签移到脚本本身上方解决了当时的问题,但现在无法正常工作。

这是我的根 urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('showroom/', include('showroom.urls')),
    path('', RedirectView.as_view(url='/showroom/', permanent=True)),       # Redirect homepage to showroom
    path('accounts/', include('allauth.urls')),                             
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

# Static and media files
STATIC_URL = '/static/'
STATIC_ROOT = (
    os.path.join(BASE_DIR, 'static')
    )
MEDIA_URL = '/media/'
MEDIA_ROOT = (
    os.path.join(BASE_DIR, 'media')
)

Django html

{% block scripts %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>    
{% load static %}
    <script src="{% static '/js/django-dynamic-formset/jquery.formset.js' %}"></script>
{% endblock %}

这是呈现的 html 中的脚本部分

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> 
<script src="/static/js/django-dynamic-formset/jquery.formset.js"></script> <script type="text/javascript">
        $('.formset_row-image_set').formset({
            addtext: 'add another',
            deleteText: 'remove',
            prefix: 'image_set',
        });
    </script> </body>

对于上下文,这是一个对象创建表单。该脚本允许动态创建服务器端表单集,因此用户可以上传单个图像。

如果有任何其他必要的上下文,请告诉我。

【问题讨论】:

    标签: python django templates django-templates


    【解决方案1】:

    Django 以自己的方式处理static 文件,您无需提供该位置的完整路径。 尝试用这一行替换:

    <script src="{% static 'js/django-dynamic-formset/jquery.formset.js' %}"></script>
    

    还要确保您在文件顶部添加了{% load static %}

    根据文档:https://docs.djangoproject.com/en/2.2/howto/static-files/#configuring-static-files

    【讨论】:

    • 谢谢!这是呈现的 html 文件(取自 chrome 的页面源)。我已更新问题以包含模板文件。
    • @Rene 最好在模板顶部加载静态。
    • loadstatic 实际上是与我的 css 和其他静态(在页面顶部)。我只是把它放在这里以获得更多的背景信息。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 2022-01-18
    • 2016-04-01
    • 2014-07-30
    • 1970-01-01
    • 2021-08-27
    • 2014-11-10
    相关资源
    最近更新 更多