Django gives 404 error when loading static files AFTER jquery .load is called

一个人想着一个人 提交于 2019-12-13 05:50:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!