【发布时间】:2016-05-10 04:58:40
【问题描述】:
我有一些表格 modelformset_factory,模型包含 ForeignKey,但我需要像 CharField 一样显示这个 ForeignKey(ModelChoiceField)。
我是这样用的:
class SingleNeedFormWithDescription(ModelForm):
helper = StandardFormHelper()
helper.template = 'template.html'
need = CharField()
class Meta:
model = NeedMembershipOrganization
fields = ['need', 'description']
我的模板中有需要的 ID,但我需要 need.title 或 need.__str__()。
我的模特:
class NeedMembershipOrganization(Model):
need = ForeignKey('needs.Need')
organization = ForeignKey(Organization)
description = TextField(blank=True, null=True, verbose_name='description')
谢谢!
【问题讨论】:
-
那你打算怎么用呢?外键将作为下拉列表呈现为对象列表,但如果你用 charfield 覆盖它,你在文本框中输入什么?
-
您可以使用
autocomplete-light获取具有自动完成功能的文本输入表单域。当相关模型有大量条目可供选择时非常有用。 github.com/yourlabs/django-autocomplete-light -
请参阅this answer,了解如何覆盖默认模型表单字段。