gpt4 book ai didi

python - 显示 403 模板而不是 404

转载 作者:行者123 更新时间:2023-12-01 04:43:39 24 4
gpt4 key购买 nike

我希望能够在发生任何其他请求时显示 404 页面。但是,当我运行服务器并在 chrome 上使用 POSTMAN 扩展执行 POST 请求时,Django 显示 403,而不是我创建的模板。

enter image description here

proj/urls.py

urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'', include("index.urls")),
url(r'auth/', include("userapp.urls"))
)

索引/urls.py

 urlpatterns = patterns('',
url(r'^$', load_index),
url(r'^admin/', include(admin.site.urls)),

)

索引/views.py

def load_index(request):
if request.method == "GET":
form = RegistrationForm(auto_id=False)
return render(request, "index/index.html", {"form": form})
else:
# output 404 error
return render(request, "error/404.html", status=404)

最佳答案

当您创建 Django Web 应用程序时,POST/PUT/DELETE 需要 csrf token 。这是 Django 遵循的一种安全策略。

现在,为什么需要这样做?因为,按照惯例,django Web 应用程序是在运行时牢记显示和使用上下文的应用程序。

您尝试使用的是像POSTMAN这样的客户端,它主要用于测试REST服务。 (这并不意味着您无法触发对托管为 Html 模板的 Web 应用程序的请求)。

现在,如果您想从 Django Web 应用程序提供POSTAPI,请考虑使用 @csrf_exempt。主题的最佳名称:csrf-protection-should-be-disabled-for-just-a-few-views .

如果您希望您的应用程序将其用作 RESTFul 服务,请确保您使用正确的工具,可能是 Django Rest Framework 。 (注意:如果您要向站点提供 API,那么使用 @csrf_extempt 也是一种适合您的方法,这将提供一些 View 作为 POST/PUT 的 API)。

关于python - 显示 403 模板而不是 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29980209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com