Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, redirect user for unrecognized url (not just 404 template)

Tags:

django

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).

like image 741
user984003 Avatar asked Oct 03 '22 08:10

user984003


2 Answers

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

like image 91
drabo2005 Avatar answered Oct 10 '22 12:10

drabo2005


 class Redirect404Middleware(object):
     def process_response(self, request, response):
         if response == Http404:
             return HttpResponsePermanentRedirect('/')

         return response
like image 37
eugene Avatar answered Oct 10 '22 12:10

eugene