Accessing global variable in view using context processor in Django

前端 未结 3 1541
忘了有多久
忘了有多久 2021-01-13 03:17

Assuming I have a context processor:

def title(request):
   return {\'titles\': \'mytitle\'}

I can access this variable in template as

3条回答
  •  没有蜡笔的小新
    2021-01-13 04:14

    If you need the data in your views, it's cleaner to use Middleware in conjunction with a Context Processor:

    1. Create a trivial custom middleware to store some data on the request object, say at request.x (example). Now you can access this in your views directly.
    2. Enable django.core.context_processors.request in your TEMPLATE_CONTEXT_PROCESSORS to have request.x accessible from your templates.

    See my related question: Django: How to provide context to all views (not templates)?

提交回复
热议问题