REA_ANDREW
REA_ANDREW

Reputation: 10774

How to create a custom django filter tag

I am having trouble in getting my site to recognise custom template tags. I have the following dir structure:

Then I have added this to the INSTALLED_APPS:

INSTALLED_APPS = (
#    'django.contrib.auth',
    'django.contrib.contenttypes',
#    'django.contrib.sessions',
    'django.contrib.sites',
    'project_name'
)

I then reference this inside the template like this:

{% load getattribute %}
{%  for header in headers %}
    <td>{{ obj|getattribute:header }}</td>
{% endfor %}

The error which I get is as follows:

Could not import controllers.EventController. Error was: No module named project_name

Any help would be appreciated for this:

TIA

Andrew

UPDATE:

The site works but I cannot get the template tags to work. If I remove the project_name from the installed_apps I get the following error:

Exception Value: 'getattribute' is not a valid tag library: Could not load template library from django.templatetags.getattribute, No module named getattribute

Upvotes: 1

Views: 1310

Answers (3)

diegueus9
diegueus9

Reputation: 31582

The error is becaus you have wrong your folder's structure, i think you must read the docs, this tutorial (part1) explains the right structure:

You have a project that isn't same thing that app:

  • project_name
    • app_name
      • templatetags
        • getattribute.py
      • models.py
      • views.py
  • settings.py
  • manage.py

And in your INSTALLED_APPS:

INSTALLED_APPS = (
#    'django.contrib.auth',
     'django.contrib.contenttypes',
#    'django.contrib.sessions',
     'django.contrib.sites',
     'project_name.app_name',
)

That is all

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599956

Your project structure is, not to put too fine a point on it, a mess. Some of the many things you need to do:

  • don't use the same name for the containing directory (project) and the inner one (which should be an app name).
  • manage.py and settings.py should be in the outer level, not inside an application.
  • I don't know what the second views is - is it actually views.py? In which case it will never be used.
  • The empty files inside templatetags and views should be __init__.py, ie two underscores either side.
  • Probably the actual cause of your problem: you need a models.py inside an application, even if it's empty, for Django to load it at all - templatetags won't work without it.

Upvotes: 1

Andy Hume
Andy Hume

Reputation: 41674

Ae you sure this is specifically to do with the template tag?

It sounds like the project_name directory is not on your python path. The output on the error page should show your current python path, so you can check if it is as expected.

Read this to learn how to fix it: http://djangotricks.blogspot.com/2008/09/note-on-python-paths.html

Upvotes: 1

Related Questions