1

I have an index.html in my templates folder. In the HTML file's head tag is <script src="scripts/main.js"></script>.

When I open a terminal in templates/ and run python manage.py runserver, the HTML loads just fine. But I get a 404 error like this: GET /PATH/TO/scripts/main.js HTTP/1.1" 404 2446

index.html can't find my JS file. Without editing index.html, how do I make the HTML file load the JS file?

1 Answer 1

1

You should use static and {% load static from staticfiles %},

like this:

{% load static from staticfiles %}
<script src="{% static 'scripts/main.js' %}"></script>

NOTE: This is NOT suggested in Deploy/Production service.

REF: https://docs.djangoproject.com/en/1.10/howto/static-files/#serving-static-files-during-development

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [ ... ]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # media file

You have to set STATIC_URL and STATIC_ROOT in your settings.py before add those to urls.py.

NOTE: This works with DEBUG=False in settings.py

You have to run runserver --insecure to let django serve static files.

So you can add with this:

<script src="/static/scripts/main.js"></script>

/static/ may be replaced with your STATIC_URL

Sign up to request clarification or add additional context in comments.

8 Comments

Yes, in your index.html. put {% load static from staticfiles %} on your 1st line of HTML, and put <script src="{% static 'scripts/main.js' %}"></script> in your <head> tag.
How do I accomplish what I need without having to edit 'index.html'?
You want not using Django Template Engine? then you should set DEBUG=False and set STATIC_ROOT to your static directory, and set django url to serve static files manually. OR you can set NginX or Apache2 to serve your static files when approach to STATIC_URL.
I really suggest you to use static method in your Django Template.
How do I set Django URL to serve static files manually? How do set NginX or Apache2 to serve static files in the way you described? Why would I need to use the static method?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.