Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Return Two Separate __str__ for a Model Form

I have a Task model that includes tasks and a foreign key to entities:

class Task(models.Model):
    task = models.CharField(max_length=500)
    entity = models.ForeignKey(Entity)

I have a model that is related to one foreign key in Task:

class Entity(models.Model):
    entity = models.CharField(max_length=50)
    type = models.CharField(max_length=50)
    def __str__(self):
        return self.entity

Task is placed into a Model Form:

class TaskForm(ModelForm):
    class Meta:
        model = Task
        fields = [
            'task',
            'entity'
        ]

The Model Form is displayed in the template like this:

{{ form.task }}
{{ form.instance.entity }}

How would I include the equivalent of {{ form.instance.type }}? This would involve somehow including two __str__ representations in the same model form. I have seen label_from_instance used in overriding the model form, but this looks like it's only possible with ModelChoiceFields. In addition, it would render the field as a widget rather than text (like form.instance).

like image 460
OverflowingTheGlass Avatar asked Sep 14 '26 22:09

OverflowingTheGlass


1 Answers

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.

like image 126
Borut Avatar answered Sep 17 '26 11:09

Borut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!