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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With