0

In my Django template, I call this frequently:

{% for name, address in directory.addressbook.items %}
  {% for street in address.list %}
    {{street.number}}

How do I create this as a filter? I've tried this, but it doesn't work.

In the template, I call:

{{directory.addressbook.items|all_numbers}}

And in my filter definition I have:

def all_numbers(data):
  number_list=[]
  if isinstance(data, dict):
    for name, address in data:
      for street in data.list():
        number_list.append(street)
    return number_list

But all I get returned is "[ ]". What am I doing wrong?

4
  • Not sure if this is part of the problem, but it looks like your outer loop (for name, address in data:) is not getting used at all (you don't use name or address). Commented Jun 6, 2013 at 0:45
  • Also, I don't think that dict has a list attribute. This should raise a syntax error. since you aren't seeing that it makes me thing that part of the code isn't being executed. Is data empty? If so, then returning [] is correct. Commented Jun 6, 2013 at 0:47
  • ah typo, that was meant to be for street in address.list(). But I don't get an exception there either - whats the right way to do this? (sorry, i'm new to python) Commented Jun 6, 2013 at 1:46
  • Well, street might be an object with a list method, so that might be OK Commented Jun 6, 2013 at 5:04

1 Answer 1

1

You need to register your function as a template filter. Also, this code will need to be in a module and then imported into your template as such...

# custom_filters.py
from django import template

register = template.Library()


@register.filter
def all_numbers(data):
  number_list=[]
  if isinstance(data, dict):
    for name, address in data:
      for street in data.list():  # this will raise an exception
        number_list.append(street)
    return number_list

# your-template.html
{% load custom_filters %}

{{ directory.addressbook.items|all_numbers }}
Sign up to request clarification or add additional context in comments.

1 Comment

The function is already registered as a filter, else it would raise an exception when I try to call it. I have plenty of other filters that I'm using. Why would "for street in data.list()" raise an exception?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.