pythondjangodjango-modelsdjango-templatesdjango-filter

django add filters in template is not working expectedly


I am a Django and Python beginner, and I encountered a problem while using Django. I hope to use a filter in the template to get the string I need, but the result below is not what I expected.

# filter definition

@register.filter
def to_class_name(obj):
    return obj.__class__.__name__
# HTML template for UpdateView (This template will be used by multiple models.)
# object = Order()

{{ object|to_class_name }} #reulst: Order

{{ 'wms'|add:object|to_class_name }} #result: str, expect: object

I roughly understand that the issue lies with the order, but it seems I can't add parentheses to modify it.

{{ 'wms'|add:(object|to_class_name) }} #cause SyntaxError

Is there any way to solve this problem? Or is there a better way to determine the page data I need to output based on the model class when multiple models share one template? Thank you all.


Solution

  • I roughly understand that the issue lies with the order, but it seems I can't add parentheses to modify it.

    You can use variables. link

    One way is to use with tag.

    it caches a complex variable under a simpler name. The variable is available until the {% endwith %} tag appears.

    eg.

    {% with firstname="Tobias" %}
    <h1>Hello {{ firstname }}, how are you?</h1>
    {% endwith %}
    

    In your case, something like this

    {% with class_name=object|to_class_name %}
       {{ 'wms'|add:class_name }}
    {% endwith %}
    

    Another approach is to use firstof tag. link

    {% firstof object|to_class_name as class_name %}
    {{ 'wms'|add:class_name }}