Alex V
Alex V

Reputation: 63

Django: passing variable to simple_tag other than id fails

Situation is simple: I want to show a specific object (model Block) in a template like this: {% block_by_name editorial as b %} {{ b.title }} or, preferably with a filter like this {{ block.title|get_by_name:editorial }}.

I succeeded with a simple_tag.

Getting items by id works fine:

# in templatetags
@register.simple_tag
def block_by_id(id=1):
    b = Block.objects.get(id=id)
    return b


# in html template it get block with id 3 and shows it OK
{% block_by_id 3 as b %} {{ b.title }}

However, when I want to get blocks by names or tags like below,

Getting items by name fails

#
@register.simple_tag
def block_by_name(n="default_name"):
    b = Block.objects.get(name=n)
    return b

# in html template it fails to get block with name "editorial"
{% block_by_name editorial as b %} {{ b.title }}

Django shows the error Block matching query does not exist Because it assumes that variable n is empty string, though I passed it: "editorial"

The traceback:

        b = Block.objects.get(name=n)

     ...

▼ Local vars
Variable    Value
n   

''

Not sure why this happens. How can I pass the variable so as it does not disappear?

Upvotes: 0

Views: 601

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599788

But you didn't pass "editorial", you passed editorial. That's a variable, which does not exist. Use the string.

Upvotes: 1

Related Questions