How to pass common dictionary data to every page in django

感情迁移 提交于 2019-11-30 00:17:32
    17

    It blows me away how common this is. You want to use context processors my friend!

    Very easy to create, like so:

    def messagenumber_processor(request):
       return {'messagenumber': 5}
    

    Since messagenumber is a dynamic variable based on the User, you could pull data from the database by fetching from request.user as you have full access to request within each context processor.

    Then, add that to your TEMPLATE_CONTEXT_PROCESSORS within settings.py and you're all set :-) You can do any form of database operation or other logic within the context processor as well, try it out!

    • 2
      Two notes: 1) You'll need to have django.contrib.auth.middleware.AuthenticationMiddleware in your MIDDLEWARE_CLASSES setting in order for request.user to work. 2) Only templates rendered with django.template.RequestContext instances as context will have context processors applied. – Joseph Spiros Jul 11 '10 at 2:27
    • thanks, a couple of more questions. *)I can put this method in any where (in any my view files)? *)Adding this processor like 'myproject.myapp.myview.messagenumber_processor'? and *) How to call this data in template ? request.messagenumber_processor? – icn Jul 11 '10 at 2:33
    • @Joseph Valid points, which are stated in the links I posted, but thanks! @xlione You technically can put it anwyhere within your project, but it's recommended to place it in a context_processors.py for the application that these context processors will deal with. To call the data in your template, reference the dict you return in the context processor. E.g in my example if I put {{ messagenumber }} in my template, it would output 5 assuming I linked up my context processor all correctly. – Bartek Jul 11 '10 at 2:36
    • thanks again! it works like a charm! – icn Jul 11 '10 at 3:06
    17

    Just to save someone's time if new to django

    settings.py

    TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.contrib.messages.context_processors.messages",
    "home.context_processor.remote_ip")
    

    in home application, create a python file called context_processor.py

    in the context_processor.py add a function like this:

    def remote_ip(request):
      return {'remote_ip': request.META['REMOTE_ADDR']}
    

    use it in the templates like {{ remote_ip }}

    标签
    易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!