问题
I have an html file located at
/static/templates/usersPostsSection.html
in my app directory. The first few lines of usersPostsSection.html are:
{% load static %}
<link rel='stylesheet' type='text/css' href="{% static 'css/cssReset.css' %}" />
<link rel='stylesheet' type='text/css' href="{% static 'css/homePageBase.css' %}" />
<script type='text/javascript' src="{% static 'js/jquery.js' %}"></script>
<form class='voteForm' method="post" action="/post/likePost/">{% csrf_token %}
<button class="voteButton" type="submit">
</button>
<input type="hidden" name="postID" value="{{ post.id}}" />
</form>
<script type='text/javascript'>
$('.voteForm').click( function() {
event.preventDefault();
$.post('/post/likePost/', $('.voteForm').serialize(), function(data) {
$('#content').hide();
$('#content').load('/static/templates/usersPostsSection.html');
});
});
</script>
When going to the URL /home/, I see usersPostSection.html perfectly fine. However, once I click the form button and the JS is run, it works up until the last line of the function:
$('#content').load('/static/templates/usersPostsSection.html');
Once it reloads usersPostsSection.html, nothing shows up on the page and when I use the 'inspect element' on Chrome, it gives errors saying:
GET http://127.0.0.1:8000/home/%7B%%20static%20'js/jquery.js'%20%%7D?_=1403660483401 404 (NOT FOUND)
Uncaught SyntaxError: Unexpected token < jquery.js:2
GET http://127.0.0.1:8000/home/%7B%%20static%20'css/cssReset.css'%20%%7D 404 (NOT FOUND) jquery.js:3
GET http://127.0.0.1:8000/home/%7B%%20static%20'css/homePageBase.css'%20%%7D 404 (NOT FOUND) jquery.js:3
I'm pretty sure it is giving this error because it is checking for the static files in
http://127.0.0.1:8000/home/
rather than using the static location which I have set in my settings.py:
STATICFILES_DIRS = (
'/home/user/Documents/djcode/aS/aSa/static'
)
any idea how to stop getting these 404 errors After the .load function is called?
回答1:
Your problem is that staticfiles doesn't interpret django template tags in a static html file, so you'll need to write /static/templates/usersPostsSection.html
as plain html.
%7B%%20static%20'js/jquery.js'%20%%7D
is just the url-escaped value of {% static 'js/jquery.js' %}
.
Alternately, you could serve that file via a django view (do you already do this at /home/
?) and load it from there, instead of as a static file.
来源:https://stackoverflow.com/questions/24399084/django-gives-404-error-when-loading-static-files-after-jquery-load-is-called