I have dir template with all templates, and I have dir errors, with all templates with errors 404.html.
I found the following old solution:
In urls.py my app I wrote
from django.conf.urls import (handler400, handler403, handler404, handler500)
handler404 = 'my_app.views.page_not_found'
And in view my app
from django.shortcuts import (render_to_response)
from django.template import RequestContext
def page_not_found(request):
response = render_to_response(
'errors/404.html',
context_instance=RequestContext(request))
response.status_code = 404
return response
But I use Django 1.11 and this doesn't work.
If you follow the docs
You should return HttpResponseNotFound which is the same as HttpResonse except for status code. It worked for me.
def bad_request(request):
response = render_to_response(
'errors/404.html'
)
return HttpResponseNotFound(response.content)
Related
When I am trying to send data to my localhost using the ajax call in popup.js, I am getting an error :
Not Found: /sentiment/
"GET /sentiment/?number=219 HTTP/1.1" 404 1714
Even though I checked the url and it is correct and exists.
This is the snippet of my ajax call:
$.ajax({
url:"http://127.0.0.1:8000/sentiment/",
dataType:"json",
data:{
number:newTotal
},
crossDomain:true,
success:function(json)
{
$('#total').text(json.number)
}
})
and this is my urls.py file in django app :
from django.contrib import admin
from django.urls import path,include
from DetectHate import views
from django.urls import path,re_path
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^sentiment/$', views.sentiment,name="sentiment"),
]
and this is my views.py file -
import json
from django.http import Http404,HttpResponse
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def sentiment(request):
if request.is_ajax():
var=request.POST.get('number')+5
data={}
data['number']=var+5
return HttpResponse(json.dumps(data),content_type='application/json')
else:
raise Http404
When I load an inexistent url the page 404 does not show instead the page 500 is shown. Below my setups. Could you please guide me to turn Django on to show 404 page? Thanks
Ubuntu Server 16.04 ; Python 3.5.2 ; Django 2.0
cat contatoproj/urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from django.conf.urls import include
from django.conf.urls import handler404, handler500
from contatoapp import views
from contatoapp import views as myapp_views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index, name='index'),
url(r'^contato', views.contato, name='contato'),
]
handler404 = myapp_views.error_404
handler500 = myapp_views.error_500
cat contatoapp/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from django.contrib import messages
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from contatoapp.forms import ContatoForm
def error_404(request):
data = {}
return render(request, 'ops404.html', data)
def error_500(request):
data = {}
return render(request, 'ops500.html', data)
$ ls -la templates/ops*
-rwxr-xr-x 1 admweb admweb 614 Dec 13 15:31 templates/ops404.html
-rwxr-xr-x 1 admweb admweb 614 Dec 13 15:29 templates/ops500.html
cat contatoproj/settings.py
DEBUG = False
ALLOWED_HOSTS = ['*']
If you're getting a 500 error for missing pages then it's because there is an error happening when Django tries to handle that response.
From looking at your code, this is probably because your 404 error handler is wrongly defined - it needs to accept a second exception argument which is missing. Change it to:
def error_404(request, exception):
data = {}
return render(request, 'ops404.html', data)
Also note that you should be returning a HttpResponseNotFound, otherwise the client will not receive a HTTP 404 response.
You're getting an error in the process of handling the 404. This means you're getting a 500 instead.
As you're not doing anything special in your 500 or 404 views, you don't need to explicitly define the handler views for them using handler404/500.
Instead, you should define 404.html and 500.html in your templates directory. Django will use these instead of the default templates, and you don't need to re-implement the 404 and 500 views correctly.
So my app works fine in the development server when Debug=True, however, when I switch it to False, my homepage is giving me back a 400 back. I have some endpoints which return json and they work fine regardless of the debug value.
I'm using Django 1.10.2
urls.py
from django.conf.urls import url
from django.contrib import admin
from fim_table import views
urlpatterns = [
url(r'^$', views.create_home),
url(r'^data/', views.data),
...
]
views.py
from django.shortcuts import render
from django.views.decorators.csrf import csrf_protect
from lockdown.decorators import lockdown
from .models import Fim, FimDeleted
from django.http import HttpResponse
from django.db.models.functions import Lower
from django.template.context_processors import csrf
import json
#csrf_protect
def create_home(request):
return render(request, 'table.html', {'csrf': csrf})
# returns all of the data, unfiltered/response is json
#csrf_protect
def data(request):
# show distinct names only
fims = Fim.objects.annotate(name_lower=Lower('crib_name')).order_by('name_lower').distinct('name_lower')
# fims need to be not a queryset but an array of dicts to be json
dictionaries = [ idToString(name.as_dict()) for name in fims ]
mydata = {"aaData": dictionaries}
return HttpResponse(json.dumps(mydata), content_type='application/json')
settings.py
DEBUG = False
ALLOWED_HOSTS = ["*"]
update
I implemented some logging, and got:
The joined path (/DataTables/datatables.min.css) is located outside of the base path component (/Users/me/development/my_project/myapp/staticfiles).
I'm thinking this is a whitenoise issue, even though I set up my settings.py exactly like it is in their docs
Try adding hostnames in the allowed hosts section.
For Ex: ALLOWED_HOSTS = ['localhost', 'localhost_projectname', 'server_hostname']
You can find more details about how to add 404 and 500 pages in your site in the given blog post,
https://micropyramid.com/blog/handling-custom-error-pages-in-django/
I have got installed Django 1.9.2 and want to use a custom view to handle error 404. I am trying to do this:
# myapp/urls.py
from django.conf.urls import url, handler404
from django.views.generic.base import RedirectView
from django.core.urlresolvers import reverse_lazy
import views
urlpatterns = [
url(r'^not-found/$', views.NotFoundView.as_view(), name='not_found'),
]
#handler404 = RedirectView.as_view(url=reverse_lazy('not_found'))
handler404 = 'myapp.views.NotFoundView.not_found_handler'
# myapp/views/NotFoundView.py
from django.http import HttpResponse
class NotFoundView(object):
#classmethod
def as_view(cls):
return cls.handler
#classmethod
def handler(cls, request):
return HttpResponse(u"My error 404", status=404)
def not_found_handler(request, exception, template_name='404.html'):
return HttpResponse(u"New handler 404", status=404)
In other words, I overrode handler404 with RedirectView initialized by the URL to my custom view called NotFoundView. But unfortunately it didn't work, I got the standard Django's error 404 instead of my custom one. What am I doing wrong?
How can I redirect any kind of url patterns to a created page "404.html" page if it doesn't exist in the urls.py rather than being shown the error by django.
Make a view that'll render your created 404.html and set it as handler404 in urls.py.
handler404 = 'app.views.404_view'
Django will render debug view if debug is enabled. Else it'll render 404 page as specified in handler404 for all types of pages if it doesn't exist.
Django documentation on Customizing error views.
Check this answer for a complete example.
In your views.py, just add the following code (No need to change anything in urls.py).
from django.shortcuts import render_to_response
from django.template import RequestContext
def handler404(request):
response = render_to_response('404.html', {},
context_instance=RequestContext(request))
response.status_code = 404
return response
Put a custom 404.html in templates directory.
source : click here
There is no need to change anything in your view or url.
Just do these 2 steps, in your settings.py, do the following
DEBUG = False
ALLOWED_HOSTS = ["*"]
And in your app directory (myapp in this example), create myapp/templates/404.html where 404.html is your custom error page. That is it.
Go to your project settings.py and set DEBUG = True to DEBUG = False
Then Django redirects all NOT set patterns to not found.
In additional if you want to customize 404 template , in your project urls.py
set
handler404 = 'app.views.404_view'
then in your projects view.py
from django.shortcuts import render_to_response
from django.template import RequestContext
def handler404(request):
response = render_to_response('404.html', {},
context_instance=RequestContext(request))
response.status_code = 404
return response
and Finally, in your templates add 404.html and fill it with what you want to show end user.