django url 没有尾部斜杠显示页面未找到

问题描述 投票:0回答:2

在最后没有尾部斜杠的 django url 中,我得到这个结果“找不到页面 404” 同一项目和一台电脑上的相同代码我得到不同的结果。 这段代码是当我得到没有斜杠的页面时:

from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('about', views.about, name='about'),
]

这是相同的代码,但我应该添加斜杠

from django.urls import path
from . import views

urlpatterns = [
path('', views.index, name='index'),
path('about/', views.about, name='about'),
]

我在前端等待的是我的观点。py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def about(request):
return HttpResponse('about page')

我正在等待你们的帮助

python django
2个回答
3
投票

此行为由

APPEND_SLASH
设置控制。在默认设置中,
APPEND_SLASH
设置为
True
,这意味着如果请求的 URL 与
urls.py
中设置的任何路径不匹配,HTTP 重定向将发出到带有尾部斜杠的同一 URL。

例如: 假设如果提供的 URL

/foo.com/bar
是无效的 URL 模式,则对
/foo.com/bar/
的请求将重定向到
/foo.com/bar

文档指出

请注意,重定向可能会导致 POST 请求中提交的任何数据丢失。

仅当安装了

APPEND_SLASH
 时才使用 
CommonMiddleware
设置(请参阅中间件)。另请参阅
PREPEND_WWW

请阅读文档以获取进一步说明。


0
投票

问题

在 Django 中,当您返回自定义 404 视图时,Django 期望 HTTP 响应具有 404 状态代码来表示“未找到”。但是,如果您没有在响应中显式设置

status=404
,Django 会将其视为
200 OK
响应,即使您打算将其作为“未找到页面”视图。

误导HTTP响应:如果没有status=404,页面将返回200 OK,这表明请求成功,误导用户和搜索引擎。

如果您使用自定义404模板

from django.shortcuts import render

def custom_404_view(request, exception):
    return render(request, '404.html', status=404)  # Set status=404 here

无模板解决方案

from django.http import HttpResponseNotFound

def custom_404_view(request, exception):
    return HttpResponseNotFound("Custom 404 page not found")
© www.soinside.com 2019 - 2024. All rights reserved.