开发者

Extra variables on a custom 404 template

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 h开发者_开发技巧ttp
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.


I had a similar problem.

handler404 should be set in the urls.py file, but you also have to import it, and that's not in the docs.

  1. add handler404 to your imports

    from django.conf.urls.defaults import patterns, include, url, handler404
    
  2. set handler404="string.of.the.view.to.load"

    handler404="myApp.views.pagenotfound"
    
  3. define your 404 view in view.py as a usual view.


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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜