【问题标题】:Iterate over Django custom Form迭代 Django 自定义表单
【发布时间】:2017-09-02 08:24:49
【问题描述】:

我正在尝试创建一个动态表单,其中包含不同数量的 CharField。我希望能够以我的形式在半任意的地方随意显示它们。我的方法是创建一个可迭代的函数来处理正确的 self.fields[INDEX]。但是,当我这样做时,我确实看到了:

<django.forms.fields.CharField object at 0x80bae6be0>
<django.forms.fields.CharField object at 0x80bae6f98>
<django.forms.fields.CharField object at 0x80bae6da0>

如何按预期进行 CharField() 渲染?

我的代码如下:

class ImplementationForm(forms.ModelForm):
    """
    Specifies the implementation of a given control.
    """
    class Meta:
        model = Implementation
        fields = ['implemented', 'scope', 'separate']

    def __init__(self, *args, **kwargs):

        control = kwargs.pop('control')

        super(ImplementationForm, self).__init__(*args, **kwargs)
        self.fields['separate'].widget.attrs.update({'class': 'separate'})
        self.fields['scope'].widget.attrs.update({'class': 'scope'})

        for substatement in control.substatement.all():
            self.fields['statement_%s'%substatement.pk] = forms.CharField()

    def subfield(self):
        print("Comes herE")
        for index in self.fields:
            if index[:10] == 'statement_':
                yield self.fields[index]

模板基本上是这样做的:

{% for x in myform.subfield %} {{ x }} {% endfor %}

【问题讨论】:

  • 我建议使用FormSet。它们提供您要求的开箱即用功能。

标签: python django


【解决方案1】:

您正在寻找的是表单的 BoundFields。例如{{ 表格. 电子邮件 }} 您正在迭代 Field 实例(不是包装 Field 实例的表单的 BoundField 实例),例如{{ form.field.email }}。 这就是为什么你得到 ​​p>

&lt;django.forms.fields.CharField object at 0x80bae6da0&gt;

来自您的模板。见:https://stackoverflow.com/a/671305/3035260

另见 django 的文档:https://docs.djangoproject.com/en/1.10/ref/forms/api/#django.forms.BoundField

尝试这种肮脏的方式(请参阅下面的编辑以获得更好的解决方案):

{# Iterate over your list of field instances #}
{% for x in myform.subfield %}
  {# Find the matching BoundField instance #} 
  {% for field in myform %}
    {% if field.field == x %}
      {# Matching BoudField instance found, display it. #}
      {{ field }}
    {% endif %}
  {% endfor %}
{% endfor %}

编辑: 刚刚遇到了一个更好(不那么脏)的方法: 一个字段有一个

get_bound_field(self, form, field_name)

根据文档的方法:https://docs.djangoproject.com/en/1.10/_modules/django/forms/fields/#Field.get_bound_field

所以,在最后一行('yield' 行)的子字段方法中,试试这个:

yield self.fields[index].get_bound_field(self, index)

然后,您的模板将保持不变:

{% for x in myform.subfield %} {{ x }} {% endfor %}

一切都应该按您的预期工作。

【讨论】:

    猜你喜欢
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 2016-09-12
    • 2018-02-06
    • 1970-01-01
    相关资源
    最近更新 更多