Generate HTML using Django-Polymorphic models

245 Views Asked by At

Can I generate HTML dynamically based on DJANGO-POLYMORPHIC Models? I'd like to read all of the rows from a table and generate divs based on the class type. Or is this bad practice?

{% if content %}
{% for c in content %}
<ul>
    {%  if c.instance_of(Text) %}
        <li>TEXT</li>
    {% endif %}
    {%  if c.instance_of(Image) %}
        <li>IMAGE</li>
    {% endif %}
</ul>
{% endfor %}
{% else %}
<p>No content available.</p>
{% endif %}
1

There are 1 best solutions below

2
On BEST ANSWER

I'd be reluctant to code it like that.

First, you'll need to pass Text and Image in your context, and regardless you can't call a function in a template with parameters.

I'd be inclined to either write a template tag or filter, or better, just add a property to the class that returns the type of "thing" it is, which you could put directly into the <li></li>

class Foo(PolymorphicModel):
    def description(self):
        return self.__class__.__name__

And...

<ul>
{% for c in content %}
        <li>c.description</li>
{% endfor %}
</ul>