Search code examples
pythondjangodjango-templatesdjango-viewsdjango-custom-tags

Trouble using a custom tag correctly with Django


Summary

I've been trying to get a custom tag working in Django, but seemingly it wont register correctly.

The index file looks to load correctly, it just complains about the tag not being registered correctly.

What I've done right now is just to put the .py file where I register the tag inside an app that is in the django installed apps part.

Should I be doing something else to ensure the tag registers properly?


Further info

The error I get:

Invalid block tag on line 1: 'show_loans'. Did you forget to register or load this tag?

The view where I call the tag

index.html

{% show_loans %}

The python file where i try to register the tag

loansTable.py

from .models import Loan
from datetime import datetime
from django import template

register = template.Library()

@register.simple_tag('loansTable.html')
def show_loans():
    l1 = Loan()
    l2 = Loan()
    l1.loanedDate_date = datetime.now
    l2.handinDate_date = datetime.now
    l2.loanedDate_date = datetime.now
    l2.handinDate_date = datetime.now
    loans2 =    { l1, l2 }
    return {'loans': loans2}

loansTable.html

<ul>
    {% for loan in loans %}
        <li> {{ loan }} </li>
    {% endfor %}
</ul>

Folder structure:

-app
--templates
---customTemplates
----index.html
----loansTable.html
--loansTable.py

Thanks for your help.


Solution

  • You don't need to register your tag to a template. You just need to load it from there. Which you are already doing.

    Therefore just replace:

    @register.simple_tag('loansTable.html')
    

    With this:

    @register.simple_tag
    

    You also need to put your custom tags in a templatetags directory. From the docs:

    In your index.html you must load template tags by file name where you have registered your template tags. i.e. if you registered tag inside custom_tags.py file

    {% load custom_tags %}
    

    The app should contain a templatetags directory, at the same level as models.py, views.py, etc. If this doesn’t already exist, create it - don’t forget the init.py file to ensure the directory is treated as a Python package.