Rene
Rene

Reputation: 400

Django not finding static js scripts in the correct folder

I've already run collectstatic and created the static directory in my urls.py, and all other static files work fine (bootstrap, the custom CSS) and other scripts in the same directory work perfectly fine.

This is the error code in the console.

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

For the second error, I've run into a similar problem before. Moving the jQuery CDN tags above the script itself solved the issue then, but it's not working now.

This is my root 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 %}

This is the script section from the rendered 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>

For context, this is an object creation form. The script allows dynamically created server-side formsets so users can upload individual images.

If there's any additional context necessary, just let me know.

Upvotes: 1

Views: 548

Answers (1)

Kostas Charitidis
Kostas Charitidis

Reputation: 3113

Django handles static files in its own way you do not need to provide the full path to the location. Try replacing with this line:

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

also make sure you added on top of your file {% load static %}

As per documentation : https://docs.djangoproject.com/en/2.2/howto/static-files/#configuring-static-files

Upvotes: 1

Related Questions