Skip to content

Instantly share code, notes, and snippets.

@hnaoto
Last active October 9, 2021 02:57
Show Gist options
  • Save hnaoto/d2868221682d0c62af77 to your computer and use it in GitHub Desktop.
Save hnaoto/d2868221682d0c62af77 to your computer and use it in GitHub Desktop.
Write your own context processors ("global variable" in Django templates)
#Reference: https://docs.djangoproject.com/en/1.9/ref/templates/api/#writing-your-own-context-processors
#This file is in yourapp/ directory
+from .models import Foo
+
+def foo(request):
# you might need this line for unit tests
if request.user.is_authenticated and request.user.is_active:
+ count = len(Foo.objects.filter(user = request.user))
+ return {"foo_count" :count}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
'django.core.context_processors.media',
#add this line
'yourapp.context_processors.foo'
],
},
},
]
<!DOCTYPE html>
<head></head>
<body>
<p>The number of Foo is {{foo_count}}</p>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment