views:

473

answers:

1

Hi all,

I want to be able to use extra variables on a custom 404 template.

#404.html
{{ extra_var }}

I have already tried:

#urls.py
from myproject.myapp import views
handler404 = views.handler404

#views.py
from django.template import RequestContext, loader
from django import http
def handler404(request):
    extra_var = 'my_extra_var'
    t = loader.get_template('404.html')
    return http.HttpResponseNotFound(t.render(RequestContext(request, 
      {'request_path': request.path, 'extra_var': extra_var, })))

However, it doesn't seem to work: I can only access to request_path.

Any suggestion?


Update:

I've just founded an elegant and working solution to do this.

According to the Django Documentation:

The 404 view is passed a RequestContext and will have access to variables supplied by your TEMPLATE_CONTEXT_PROCESSORS setting (e.g., MEDIA_URL).

So you just need to write your own Template Context Processor:

def extra_var(request):
    return {'my_extra_var': 'my_extra_var'}

and add it to the TEMPLATE_CONTEXT_PROCESSORS tuple

+1  A: 

The fact that you can access request_path but not extra_var suggests to me your view is not being called properly, since request_path is passed automatically to the 404.html template, per the documentation:

If you don't define your own 404 view -- and simply use the default, which is recommended -- you still have one obligation: you must create a 404.html template in the root of your template directory. The default 404 view will use that template for all 404 errors. The default 404 view will pass one variable to the template: request_path, which is the URL that resulted in the 404.

I think you need to give handler404 a string, rather than a module, like this:

handler404 = 'myproject.myapp.views.handler404'
Dominic Rodger