How can I pass data to any template from any view in Django?

后端 未结 2 640
天命终不由人
天命终不由人 2020-12-20 02:20

Like a good little coder, all of my Django templates inherit from a base.html. Now I would like to add some functionality to the base to always show some interesting things.

2条回答
  •  死守一世寂寞
    2020-12-20 02:25

    For this I use context processors. For example, if I want get variable MEDIA_URL for each view, I define context_processors.py like this:

    def media_url(request):
        from django.conf import settings
        return {'MEDIA_URL': settings.MEDIA_URL}
    

    in settings.py you must have

    TEMPLATE_CONTEXT_PROCESSORS = (
        ....
        'django.core.context_processors.request',
        'myaplication.context_processors.menuitems',
    )
    

    in view you must have render_to_response and context_instance=RequestContext(request) For example:

    def my_view(request):
    return render_to_response('base.html',{},
                                  context_instance=RequestContext(request))
    

提交回复
热议问题