1
votes

I have made a simple django application for creating my custom 404 page using django 1.10. I have created 404.html and 500.html in my page,According to Django Documentation.Then I tried two methods to render the 404 Error message.

1)I made simple 404.html and 500.html page and did nothing then. I was successful in getting the 500 page. Correct url to the page was:localhost:8000/book And I supplied localhost:8000/book/fgfg And there was no entry according to the input.But it was sending me to the 500 page but not to the 404 page as I expected. This is Internal App's Urls.py:

from django.conf.urls import url
from django.conf.urls import (
handler400, handler403, handler404, handler500
 )
from bookform import views
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),]

And this is External Project's urls.py:

 from django.conf.urls import url,include,handler404,handler500
 from django.contrib import admin


 urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^book/', include('bookform.urls')),
]
# handler404='bookform.views.handler404'
# handler500='bookform.views.handler500'

I have commented the handler404 and 500 here which I uncommented in 2nd method. In first method I did nothing except adding the 404 and 500 html files and Django tried to find out the url and resulted in 500 error but I was expecting it to be 404 error. It showed this error when setting Debug into true: Using the URLconf defined in formdj.urls, Django tried these URL patterns, in this order: ^admin/ ^book/ ^$ [name='index'] The current URL, book/dfsdfsd, didn't match any of these.

And If I set DEBUG=FALSE It resulted into 500 error.

2)Now in method 2: I updated the views.py file and Uncommented the handler404 and handler505 line from urls.py.

This is views.py:

  from django.shortcuts import render,render_to_response
  from django.shortcuts import HttpResponse
  from django.forms import modelformset_factory
  from forms import BookForm
  from bookform.models import Book
  from django.template import RequestContext
  def index(request):

     BookFormSet=modelformset_factory(Book,fields= ('name','authors'),extra=10,can_delete=True)
    formset=BookFormSet()
    return render(request,'bookform/index.html',{'formset':formset})

  def handler404(request):
    response = render(request,'bookform/404.html', {'status':400},
                            )
    response.status_code = 404
    print('I am getting called')
    return response
 def handler500(request):
    response = render(request,'bookform/500.html', {'status':400},
                              )
    print('I am getting called 500')
    response.status_code = 500
    return response

Again I was getting the 500 Page.I tried to delete the 500 and Debug=False then It resulted into 500.Then I turned debug on,It was saying the error was a 404 error. So whatever I did,I got a 500.html page called. Now I am confused how to load 404.html page correctly.

2

2 Answers

2
votes

In the urls.py of project folder add this where the accounts (it can be any app) is an app of the same project:

project/urls.py

handler404 = 'accounts.views.page_not_found'

In accounts's view add this:

accounts/views.py

def page_not_found(request):
    """Page not found Error 404"""

     response = render_to_response('404.html',context_instance=RequestContext(request))
     response.status_code = 404
     return response

Don't forget to make necessary imports, also better add handler404 contents above urls pattern. also don't forget to change Debug=False in settings.py when testing in staging.

0
votes

Try the view like that:

from django.views.generic.base import TemplateView

class Error404View(TemplateView):
    template_name = '404.html'

    def get(self, request, *args, **kwargs):
        response = super(Error404View, self).get(request, *args, **kwargs)
        response.status_code = 404
        return response

    @classmethod
    def as_error_view(cls):
        v = cls.as_view()
        def view(request):
            r = v(request)
            r.render()
            return r
        return view

Than, in urls.py:

handler404 = Error404View.as_error_view()