【问题标题】:Django gives 404 error when loading static files AFTER jquery .load is called调用 jquery .load 后加载静态文件时,Django 出现 404 错误
【发布时间】:2014-08-15 10:48:56
【问题描述】:

我有一个 html 文件位于

/static/templates/usersPostsSection.html 

在我的应用程序目录中。 usersPostsSection.html 的前几行是:

{% 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>

访问 URL /home/ 时,我看到 usersPostSection.html 非常好。但是,一旦我单击表单按钮并运行 JS,它就会一直运行到函数的最后一行:

$('#content').load('/static/templates/usersPostsSection.html');

一旦它重新加载 usersPostsSection.html,页面上什么也没有显示,当我在 Chrome 上使用“检查元素”时,它会给出错误提示:

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

我很确定它会给出这个错误,因为它正在检查

中的静态文件
http://127.0.0.1:8000/home/ 

而不是使用我在 settings.py 中设置的静态位置:

STATICFILES_DIRS = (
    '/home/user/Documents/djcode/aS/aSa/static'
)

知道如何在调用 .load 函数后停止收到这些 404 错误吗?

【问题讨论】:

    标签: jquery ajax django django-staticfiles


    【解决方案1】:

    您的问题是 staticfiles 不会解释静态 html 文件中的 django 模板标签,因此您需要将 /static/templates/usersPostsSection.html 编写为纯 html。

    %7B%%20static%20'js/jquery.js'%20%%7D 只是 {% static 'js/jquery.js' %} 的 url 转义值。

    或者,您可以通过 django 视图提供该文件(您是否已经在 /home/ 执行此操作?)并从那里加载它,而不是作为静态文件。

    【讨论】:

    • 是的,在 /home/ (homePage.html) 我刚刚在模板中添加了 {% include 'usersPostsSection.html' %} .. 所以我决定做的是创建一个视图(它得到在呈现 usersPostsSection.html 的 URL /temp/usersPosts/) 处调用并更改了“$('#content').load('/static/templates/usersPostsSection.html');”到 "$('#content').load('/temp/usersPosts/');".. 这就是您所说的“或者,您可以通过 django 视图提供该文件并从那里加载它,而不是作为一个静态文件。”,对吗?
    猜你喜欢
    • 2014-10-20
    • 1970-01-01
    • 2020-01-14
    • 2016-03-30
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 2020-05-07
    相关资源
    最近更新 更多