【问题标题】:I need display ModelChoiceField like CharField我需要像 CharField 一样显示 ModelChoiceField
【发布时间】: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.titleneed.__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,了解如何覆盖默认模型表单字段。

标签: python django


【解决方案1】:

您可以将ModelChoiceField 小部件更改为TextInput,但您可能必须想办法验证和解析输入。

class SingleNeedFormWithDescription(ModelForm):

    need = forms.ModelChoiceField(
        queryset=Need.objects.all(), 
        widget=forms.TextInput)

【讨论】:

    猜你喜欢
    • 2015-07-24
    • 2021-10-06
    • 2019-07-21
    • 1970-01-01
    • 2011-02-07
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    相关资源
    最近更新 更多