Gaurav Wadhwani
Gaurav Wadhwani

Reputation: 1352

Django TemplateTags not compiling

I am trying to create custom django templatetags for my project. I followed the guides available and created the tags. But the tags are not being picked up. They aren't even being compiled (as the .pyc file isn't generated).

The structure is my_dir>app>templatetags>markup_tags.py. The folders app and templatetags have the required __init__.py file.

My markup_tags.py file is

from django import template
from random import randint

register = template.Library()

@register.assignment_tag()
def random_number(length=3):
    """
    Create a random integer with given length.
    For a length of 3 it will be between 100 and 999.
    For a length of 4 it will be between 1000 and 9999.
    """
    return randint(10**(length-1), (10**(length)-1))

When I check the tag using python manage.py shell command:

from my_dir.app.templatetags import markup_tags

I get the error:

Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named templatetags

Whats wrong here? Thanks.

Edit: The folder structure is Folder-Structure

Upvotes: 4

Views: 598

Answers (2)

anjaneyulubatta505
anjaneyulubatta505

Reputation: 11695

I had the same problem before I solved it by adding code below
In settings.py

TEMPLATE_LOADERS = ('django.template.loaders.app_directories.load_template_source',
)

Add your app in

INSTALLED_APPS = ('myapp',)
And be sure to have an
__init__.py
in the "myapp" folder as well as in templatetags.

Upvotes: 0

Gaurav Wadhwani
Gaurav Wadhwani

Reputation: 1352

So I don't know what went wrong but the templatetags folder I was copying into the app directory wasn't being picked up by python. I deleted that and using my IDE (PyCharm), I created a new Python Package in my app, which automatically generates a new __init__.py file.

I restarted my server then and it seems to work now. Weird though!

Upvotes: 1

Related Questions