55
I don’t know if this is the right way to do it, but in my Django apps, I always place common template tags in a lib
“app”, like so:
proj/
__init__.py
lib/
__init__.py
templatetags/
__init__.py
common_tags.py
Just make sure to add the lib
app to your list of INSTALLED_APPS
in settings.py
.
35
Since Django 1.9, it is no longer necessary to create additional common
app as others mentioned. All you need to do is to add a path to your project templatetags
directory to the settings.py
‘s OPTION['libraries']
dict.
After that, these tags will be accessible throughout your whole project. The templatetags
folder can be placed wherever you need and can also have different name.
Customized example from the Django docs:
OPTIONS={
'libraries': {
'myapp_tags': 'path.to.myapp.tags',
'project_tags': 'project.templatetags.common_extras',
'admin.urls': 'django.contrib.admin.templatetags.admin_urls',
},
}
- [Django]-Django filter JSONField list of dicts
- [Django]-How can I handle Exceptions raised by dango-social-auth?
- [Django]-Location of Django logs and errors
7
Django registers templatetags globally for each app in INSTALLED_APPS
(and that’s why your solution does not work: project is not an application as understood by Django) — they are available in all templates (providing they was properly registered).
I usually have an app that handles miscellaneous functionality (like site’s start page) and put templatetags not related to any particular app there, but this is purely cosmetic.
- [Django]-__init__() got an unexpected keyword argument 'mimetype'
- [Django]-How can I set a default value for a field in a Django model?
- [Django]-Query for top x elements in Django
6
This is the place where you place it in settings.py.
The first key(‘custom_tags’ in this case) in ‘libraries’ should be what you want to load name in template.
PROJECT STRUCTURE
mysite
- myapp
- mysite
- manage.py
- templatetags
- custom_tags.py
SETTINGS.PY
TEMPLATES = [
{
'BACKEND': '....',
'OPTIONS': {
'context_processors': [
...
],
'libraries': {
'custom_tags': 'mysite.templatetags.custom_tags',
}
},
},
]
- [Django]-Django rest framework, use different serializers in the same ModelViewSet
- [Django]-How do I execute raw SQL in a django migration
- [Django]-How to save a model without sending a signal?
-2
Django works by App. They are refer in the INSTALLED_APPS setting.
I suggest to you to split everything related to a different app. For your templatetags problem, you could create an app called ‘common_tags’. Then setup the INSTALLED_APPS settings to use it, and you’ll be able to load your common tags from any templates like so:
{% load XXXX %}
- [Django]-Missing Table When Running Django Unittest with Sqlite3
- [Django]-Success_url in UpdateView, based on passed value
- [Django]-Alternate Row Coloring in Django Template with More Than One Set of Rows