6

I am getting ready to deploy my first Django application and am hitting a bit of a roadblock. My base template relies on me passing in the session object so that it can read out the currently logged in user's name. This isn't a problem when I control the code that is calling a template.

However, as part of getting this app ready to be deployed, I need to create a 404.html page. I extended my base template just like I've done with my other pages, but I don't see a way to pass in the session object so that I can utilize it. Is there a way to have Django call a custom method to render your 404 rather than just rendering your 404.html for you?

2 Answers 2

13

You need to override the default view handler for the 404 error. Here is the documentation on how to create your own custom 404 view function:

http://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views

Sign up to request clarification or add additional context in comments.

4 Comments

Just a note for other people: You need to define handler404 in the urls.py in the root of your project, not in one of your apps.
It must be in the file settings.ROOT_URLCONF points to (which normally is in the root of your project, but doesn't have to be...)
I found this answer because that tutorial didn't make sense to me. Does the handler404 line go in the urls.py urlpatterns list? How does the syntax of it make any sense?
Answered myself - yes it does go in urls.py, and outside of the urlpaterns. And yes, it is a string that holds the name in the format that you would otherwise use in an import statement. I found these details surprising, but it works.
4

Define your own 404 handler. See Django URLs, specifically the part about handler404.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.