Django返回两个单独的__str__以获取模型表单 [英] Django Return Two Separate __str__ for a Model Form
问题描述
我有一个 Task
模型,其中包含任务和实体的外键:
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)
我有一个与 Task
:
class Entity(models.Model):
entity = models.CharField(max_length=50)
type = models.CharField(max_length=50)
def __str__(self):
return self.entity
任务
放入模型表单:
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 }}
我应如何包括 {{form.instance.type}}
的等价内容?这将涉及以某种方式包含相同模型形式的两个 __ str __
表示形式。我已经看到 label_from_instance
用于覆盖模型表单,但这似乎只能通过ModelChoiceFields来实现。另外,它将字段显示为小部件而不是文本(例如 form.instance
)。
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
).
推荐答案
在模板中, form.instance.entity
是实例的相关的实体
。如果要显示 type
字段,则可以简单地使用:
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 }}
要回答标题中的问题,每个模型只能有一个 __ str __
方法。您可以定义另一个返回字符串的方法或属性,但是如果您只想显示 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.
这篇关于Django返回两个单独的__str__以获取模型表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!