Is there a way to access the context from everywhere in Django?

前端 未结 3 1882
执笔经年
执笔经年 2020-12-10 05:49

I\'m looking for a way to have a global variable that is accessible by any module within my django request without having to pass it around as parameter. Traditionally in ot

3条回答
  •  一整个雨季
    2020-12-10 05:52

    You have to write your own ContextProcessor, like explained here.


    EDIT:

    After you've created a Context Processor, e.g.,

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

    you can get the variables you need by initializing a RequestContext, like this:

    from django.template import RequestContext
    
    def myview(request):
      rc = RequestContext(request)
      rc.get('ip_address')
    

    However, please note that if you don't put your Context Processor inside the TEMPLATE_CONTEXT_PROCESSORS tuple, you have to pass the processor to RequestContext as an argument, e.g.:

    from django.template import RequestContext
    
    def ip_address_processor(request):
      return {'ip_address': request.META['REMOTE_ADDR']}
    
    def myview(request):
      rc = RequestContext(request, processors=[ip_address_processor])
      rc.get('ip_address')
    

    Some useful links:

    • Django Template API documentation
    • Settings TEMPLATE_CONTEXT_PROCESSORS
    • Django Book: Advanced Templates

提交回复
热议问题