Reputation: 67
If i give wrong url then i want to redirect to 404.html page. in my view.py, i have following function-
from django.shortcuts import render_to_response
from django.template import RequestContext, loader
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from misc.models import *
from meta.views import Meta
from login.helper import *
from django.contrib import messages
def my_custom_404_view(request):
return render(request, "404.html", {
"areas": Area.objects.all(),
"jobs": Jobs.objects.filter(active=True),
})
i have 404 html page in my template and in my url file i have following
handler404 = 'pages.views.my_custom_404_view'
but when i enter any wrong url it does not work. it gives me- Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ko What i m doing wrong? please suggest.
Upvotes: 1
Views: 2555
Reputation: 313
Its not necessary to specify the url for 404 in reg expression fashion as we always do, just follow what's given below. First of all you need to have a template for 404 message inside the templates folder(specified template directory in settings.py). 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' 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 don't forget to change Debug=False in settings.py when testing in staging.
Upvotes: 1
Reputation: 2233
That's because you are in DEBUG
mode. Set DEBUG
to False
in your settings and see if it works.
EDIT: According to this link, you have to take a few more steps:
Step1: Create a 404.html
file having your error message.
Step 2: Place 404.html
in directory pointed by TEMPLATE_DIRS
Step 3: In urls.py
set handler404 = 'app.views.custom_404'
. This will be a you custom view which will return the 404.html
page when Http 404 error occurs.
Step 4: Create you custom view in views.py:
def custom_404(request):
return render_to_response('404.html')
Step 5: in settings.py
, ALLOWED_HOSTS = ['hostname']
, this will be a IP address from which you are running the django project (it can belocalhost
).
Step 6: very important , in settings.py
, make DEBUG=False
, only then you will able to see the custom error page.
Upvotes: 1