How to Use Custom Template Tag in Django: Simple Guide
To use a
custom template tag in Django, create a templatetags folder inside your app, add a Python module with your tag code, then load it in your template with {% load your_tag_module %}. Use your tag in the template by calling its name inside {% %} or {{ }} depending on the tag type.Syntax
Custom template tags in Django are defined inside a Python module within a templatetags package in your app. You register tags using the Library instance and decorate functions or classes to create simple or inclusion tags.
In your template, you load the tag module with {% load module_name %} and then use the tag by its name.
python
from django import template register = template.Library() @register.simple_tag def my_tag(arg1, arg2): return f"Arguments received: {arg1} and {arg2}"
Example
This example shows how to create a simple custom tag that concatenates two strings and use it in a Django template.
python + django template
# In your Django app folder, create a folder named 'templatetags' with an __init__.py file. # Then create a file 'custom_tags.py' with this content: from django import template register = template.Library() @register.simple_tag def concat_strings(str1, str2): return str1 + str2 # In your template file (e.g., example.html): """ {% load custom_tags %} <p>Concatenated: {% concat_strings "Hello, " "World!" %}</p> """
Output
<p>Concatenated: Hello, World!</p>
Common Pitfalls
- Not creating an
__init__.pyfile inside thetemplatetagsfolder, so Django won't recognize it as a package. - Forgetting to load the tag module in the template with
{% load module_name %}. - Using incorrect tag names or syntax in the template.
- Placing the
templatetagsfolder outside the app directory.
django template
# Wrong: No __init__.py in templatetags folder
# Django will not find your tags.
# Wrong template usage:
# {% concat_strings "Hello, " "World!" %} # Missing comma or quotes can cause errors
# Correct usage:
# {% load custom_tags %}
# {% concat_strings "Hello, " "World!" %}Quick Reference
| Step | Description |
|---|---|
| Create templatetags folder | Inside your app, add a folder named 'templatetags' with __init__.py |
| Define tag module | Create a Python file and register tags using @register.simple_tag or @register.inclusion_tag |
| Load tags in template | Use {% load module_name %} at the top of your template |
| Use the tag | Call your tag inside {% %} or {{ }} depending on tag type |
| Restart server | Restart Django server to load new tags |
Key Takeaways
Always place your custom tags inside a templatetags package within your app.
Register your tags with the template.Library() instance using decorators.
Load your custom tag module in templates before using the tags.
Ensure __init__.py exists in templatetags folder for Django to detect it.
Restart the Django server after adding new template tags.