7👍
write a template context processor:
#my_context_processors.py
def include_groups(request):
#perform your logic to create your list of groups
groups = []
return {'groups':groups}
then add it in your settings file:
#settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"path.to.my_context_processors.include_groups",
)
now a variable groups
will be available to you in all your templates
1👍
If you need data added to more than one template contexts you should look into achieving that via your own template context processor.
- [Django]-Why can't Fabric fabfile see Django settings?
- [Django]-How to read a text file from within Django view function?
- [Django]-Uwsgi: RuntimeError: cannot release un-acquired lock
1👍
You need to create template context processor to pass an object to each request. Here is some example
- [Django]-Import modules that are above project root
- [Django]-How to install mod_wsgi on Windows+XAMPP in 2017
- [Django]-Is it okay to use os.sep instead of "/" in url
- [Django]-Monitoring django postgres connections
- [Django]-Deleting periodic task for celery scheduler in `settings.py` will not delete the actual task
0👍
#tu_context_processor.py
from setting.models import Business
def include_business(request):
business = Business.objects.all().last()
return {'business': business}
in your settings file:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'core.tu_context_processor.include_business',
],
},
},
]
now a variable business will be available to you in all your templates
tested in Django 4
- [Django]-Append extra data to request.POST in Django
- [Django]-How to pull information saved from IP address call with GeoIP2() django models to display in my html
Source:stackexchange.com