gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:06:18 27 4
gpt4 key购买 nike

我已经运行了collectstatic并在urls.py中创建了静态目录,所有其他静态文件都工作正常( Bootstrap 、自定义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>

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

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

最佳答案

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

<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

关于python - Django 在正确的文件夹中找不到静态 js 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58431945/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com