有多种方法可以做到这一点。
1)您可以将 help_text 添加到模型中的字段定义中,正如Bobort 在上面的评论中所说:
class GroupMessage(Message):
group = models.ForeignKey(Group, related_name='+', help_text='Some text')
如果您希望此 help_text 保持不变,无论您使用什么 ModelForm,这种方式都非常有用。例如,您可以为 GroupMessage 模型创建两个 ModelForm 表单,它们都将具有来自该模型的 help_text。
2)您可以像这样覆盖表单字段中的模型字段:
class GroupForm(ModelForm):
group = forms.ModelChoseField(label='Group', help_text='Some text')
class Meta:
model = GroupMessage
当您不仅需要更改 help_text 还需要更改标签或查询集或字段类型时,这种方式很有用。
3) 你可以像上面的laffuste 那样做:
class GroupForm(ModelForm):
class Meta:
model = GroupMessage
help_texts = {
'group': 'Group to which this message belongs to',
}
如果您只想更改一个或多个字段的 help_text,这种方法很有用。
4) 另一种方法就像你做的那样:
class GroupForm(ModelForm):
class Meta:
model = GroupMessage
def __init__(self, *args, **kwargs):
super(GroupForm, self).__init__(*args, **kwargs)
self.fields['employees'].help_text = 'Some text'
但是这个解决方案需要一点说明。如果您将在这样的模板中使用此表单:
{% for field in form %}
{{ field }}
{{ field.help_text }}
{% endfor %}
没关系。但例如以防万一:
{% for field in form.visible_fields %}
{{ field }}
{{ field.help_text }}
{% endfor %}
help_text 将为空,因为 BoundField 中的 help_text 在您自己设置之前已填充。因此解决方案是将self['employees'].help_text = 'Some text' 添加到__init__ 或在模板中使用{{ field.field.help_text }}。
当您想通过某些条件设置 help_text 时,此解决方案很有用,例如,如果将特定参数传递给表单初始化或其他内容。
希望对某人有所帮助。