As you guessed, there is a much more easier way built-in to django:
{% now "Y" %}
Edit
As you mentioned in the comments that you want to share a bunch of template tags among all of your apps, you can override libraries
dictionary and add your custom template tags there.
Read more about that in the docs
and for your templates:
{% load your_template_tags_file_name %}
{% cd_year %}
Edit 2
This is how the TEMPLATES
part of your settings.py
should look like:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'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',
],
'libraries': { # <-----------
'global_tags': 'template_tags.global_tags',
'admin.urls': 'django.contrib.admin.templatetags.admin_urls',
},
},
},
]
and your directory structure should be like:
<your_project_dir>
├── __init__.py
├── settings.py
├── template_tags
│ ├── global_tags.py
│ ├── __init__.py
...
the global_tags.py
file should contain your template tag definition and registration, as:
from datetime import datetime
from django import template
register = template.Library()
@register.simple_tag
def current_time(format_string):
return datetime.now().strftime(format_string)
@register.simple_tag
def cd_year():
return datetime.now().year
@register.simple_tag
def cd_email():
return 'pp@pp.com'
and for each template that's going to use those custom template tags:
{% load global_tags %}
{% cd_year %}