[Django]-Instance.__dict__ in django templating language

4👍

There are two ways you can do this.

1) Model method:

class Something(models.Model):
    field1 = models.CharField()

    def to_dict(self):
        return self.__dict__

    def __str__(self):
        return self.field1

and then you can call {{ instance.to_dict }} in your template.

2) Template filter

@register.filter
def to_dict(instance):
    return instance.__dict__

and then you can call {{ instance|to_dict }}

Note: You must activate the template filters and create them by following these instructions

👤Hybrid

0👍

Use the pprint filter:

{{ my_object|pprint }}

Leave a comment