Search code examples
djangodjango-templatesdjango-shell

How to import a template tag in the interactive shell?


How can I import a custom template tag or filter in the interactive shell to see if the everything is working fine?

I have two machines behaving differently and I don't have a clue of how to do some debugging.

On the production machine I can't load a template filter, I get the error "Template library not found". On the local machine everything works fine.


Solution

  • If you're worried about typos, missing __init__.py problems or masked ImportErrors, you could just import the function. Assuming the following structure:

    foo
    ├── bar
    │   ├── __init__.py
    │   ├── models.py
    │   ├── static
    │   │   └── ..
    │   ├── templates
    │   │   └── ..
    │   ├── templatetags
    │   │   ├── __init__.py
    │   │   └── baz.py
    │   ├── views.py
    ├── manage.py
    └── foo
        ├── __init__.py
        ├── settings.py
        ├── urls.py
        └── wsgi.py
    

    and the following contents of baz.py:

    from django import template
    
    register = template.Library()
    
    @register.filter
    def capitalize(value):
        return value.capitalize()
    

    you would just run

    >>> from bar.templatetags import baz
    >>> print baz.capitalize('test')
    'test'