I thought I had this figured out, but just discovered something weird.
In urls I have
url('^page_1/$', handle_page_1),
url('^page_2/$', handle_page_2),
url('^.*/$', handle_page_not_found),
handle_page_not_found()
redirect the user appropriately if the url is not recognized.
That works fine, but I discovered something weird.
If a function returns
return HttpResponse("ok")
then "ok" is returned and everything seems to work fine. BUT, I just saw that handle_page_not_found()
is also called (I tested with a print statement). It's still "ok" that is returned, but it's first executing the code in handle_page_not_found()
.
So, how can I have a function that is called for unrecognized urls, but that is not called by a HttpResponse
object?
EDIT: Based on answer, saw that my code is actually fine except in special test situation. It's all good so long as the HttpResponse is returned to an ajax call (which is when I normally use it).
avoid the matter with this, it works with me.
urls.py:
urlpatterns = patterns('',
url('^page_1/$', handle_page_1),
url('^page_2/$', handle_page_2),
)
handler404='views.handle_page_not_found_404'
views.py :
def handle_page_not_found_404(request):
page_title='Page Not Found'
return render_to_response('404.html',locals(),context_instance=RequestContext(request))
For more details see: Django documentation: customizing-error-views
class Redirect404Middleware(object):
def process_response(self, request, response):
if response == Http404:
return HttpResponsePermanentRedirect('/')
return response
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With