Reputation: 21
in django urls without a trailing slash in the end i get this result "Page not found 404" the same project and the same code in one pc i get different result. this code is when i get the page without slash:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('about', views.about, name='about'),
]
and this the same code but i should to add slash
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('about/', views.about, name='about'),
]
what i am waiting in the frontend its my views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def about(request):
return HttpResponse('about page')
i am waiting for your help guys
Upvotes: 2
Views: 1800
Reputation: 36
The Problem
In Django, when you return a custom 404 view, Django expects the HTTP response to have a 404 status code to signify "Not Found." However, if you don't explicitly set status=404
in the response, Django will treat it as a 200 OK
response, even though you intended it as a "page not found" view.
It Misleading HTTP Response: Without status=404, the page will return 200 OK, which signals that the request was successful, misleading both users and search engines.
If you are using custom 404 template
from django.shortcuts import render
def custom_404_view(request, exception):
return render(request, '404.html', status=404) # Set status=404 here
Solution without Template
from django.http import HttpResponseNotFound
def custom_404_view(request, exception):
return HttpResponseNotFound("Custom 404 page not found")
Upvotes: 0
Reputation: 1215
This behaviour is controlled by the APPEND_SLASH
setting. In the default setting APPEND_SLASH
is set to True
which means if the requested URL does not match any paths set in urls.py
an HTTP redirect will issue to the same URL with a trailing slash.
Eg:
Assume a request to /foo.com/bar
will redirect to /foo.com/bar/
in case the provided URL /foo.com/bar
is an invalid URL pattern.
Documentation states that
Note that the redirect may cause any data submitted in a POST request to be lost.
The
APPEND_SLASH
setting is only used ifCommonMiddleware
is installed (see Middleware). See alsoPREPEND_WWW
.
please read the documentation for further clarification.
Upvotes: 3