Django在正确的文件夹中找不到静态js脚本

时间:2019-10-17 11:48:52

标签: python django templates django-templates

我已经运行了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>

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

如果还有其他需要的地方,请告诉我。

1 个答案:

答案 0 :(得分: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