【问题标题】:How to display many-to-many field as a list of text input fields?如何将多对多字段显示为文本输入字段列表?
【发布时间】:2010-09-02 17:45:26
【问题描述】:

当我显示 ToolBoxEditForm 时,它使用了一个多选字段。但我想要的是一个表单,让用户可以将工具箱中的每个工具作为文本字段进行编辑。我不知道如何使用多对多字段来做到这一点。

class Tool(models.Model):
    tool_name = models.CharField(unique=True, max_length=200)
......

class ToolBox(models.Model):
    tools = models.ManyToManyField(Tool,max_length=300)

class ToolBoxEditForm (ModelForm):
    tools = ???
    class Meta:
      model = ToolBox
      exclude  = ('user', 'popularity',)

【问题讨论】:

    标签: django django-forms django-models


    【解决方案1】:

    我正在做一些猜测工作,因为我已经为不同目的使用了 ManytoManyField 和表单。我在构造函数中添加了自定义字段操作。

    我想可以使用类似的技巧来创建文本字段。此示例应创建三个额外的文本字段,您可以稍后对其进行验证。

    class ToolBoxEditForm(forms.Form):
    
        def __init__(self, *args, **kwargs):
            super(ToolBoxEditForm , self).__init__(*args, **kwargs)
            for i in range(3):
                self.fields['many_to_many_field_%d' % i] = CharField()
    

    【讨论】:

      猜你喜欢
      • 2013-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      相关资源
      最近更新 更多