[Django]-Django Return Two Separate __str__ for a Model Form

1👍

In the template, form.instance.entity is the instance’s related entity. If you want to display the type field, you can simply use:

{{ form.instance.entity.type }}

To answer the question in your title, each model can only have one __str__ method. You could define another method or property that returns a string, but there’s no need to do this if you just want to display the type field.

2👍

Models in Django are just classes. You could also create property for type in Task class.

class Task(models.Mode):
    ... your code ...

    @property
    def entity_type(self):
        return '{}'.format(self.entity.type)

Then you’d call {{ form.instance.entity_type }} in template.

It’s a bit of an overkill in this case, but it might be an option in more complex situations.

👤Borut

Leave a comment