TEMPLATE_CONTEXT_PROCESSORS
时间: 2023-08-29 12:10:48 浏览: 99
TEMPLATE_CONTEXT_PROCESSORS is a setting in Django that specifies a list of callables that are used to populate the context variable for all templates. These callables take the request object as an argument and return a dictionary of values that will be added to the context.
By default, Django includes some context processors in this list, such as the auth context processor, which adds information about the currently logged-in user to the context. However, you can also add your own context processors to this list.
To add a context processor, you need to define a callable that takes the request object as an argument and returns a dictionary. For example, you could define a context processor that adds the current date to the context:
```python
from datetime import datetime
def current_datetime(request):
now = datetime.now()
return {'current_datetime': now}
```
Then, you can add this context processor to the TEMPLATE_CONTEXT_PROCESSORS setting in your Django settings file:
```python
TEMPLATE_CONTEXT_PROCESSORS = [
# Default context processors
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
# Custom context processor
'myapp.context_processors.current_datetime',
]
```
Now, the `current_datetime` context processor will be called for every template and the `current_datetime` variable will be available in the template context.
阅读全文