Last active
October 9, 2021 02:57
-
-
Save hnaoto/d2868221682d0c62af77 to your computer and use it in GitHub Desktop.
Write your own context processors ("global variable" in Django templates)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' | |
], | |
}, | |
}, | |
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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