在循环

时间:2018-04-18 10:10:35

标签: django django-crispy-forms

我有一个表单,我使用GET请求中的值来显示可以在表单中使用的值。我正在尝试使用crispy form来显示每个值的下拉菜单,但我不知道如何定义crispyform布局:

class ReportSample(forms.Form):

    def __init__(self, *args, **kwargs):
        super(ReportSample, self).__init__(*args, **kwargs)

        sr_id = self.data.getlist('id')
        current_sr_id = sr_id[0]

        vasr_obj = VariantAnnotationSampleRun.objects.filter(
                        sample_run_id=SampleRun.objects.get(id=current_sr_id)
                    )

        for o in vasr_obj:

            self.fields[str(o.id)] = forms.ChoiceField(
                    choices=(
                        ('dont_report', '-',),
                        ('report', 'Report',),
                        ('to_confirm', 'To confirm',),
                    )
                )

        self.helper = FormHelper()

        self.helper.layout = Layout(
                Submit('submit', 'Submit', css_class='upload-btn'),
            )
        self.helper.form_method = 'POST'

如果我在HTML中没有使用脆弱的表单来渲染它:

{{form}} 

然后我得到vasr_obj中每个值的下拉列表。如何通过在布局中定义字段(分配给str(o.id)变量)来完成此操作:

我尝试过这方面的变体:

        self.helper = FormHelper()


        for o in vasr_obj:

            id_field = forms.ChoiceField(
                    choices=(
                        ('dont_report', '-',),
                        ('report', 'Report',),
                        ('to_confirm', 'To confirm',),
                    )
                )

            self.helper.layout = Layout(
                    Field(id_field, css_class='search-sample'),
                    Submit('submit', 'Submit', css_class='upload-btn'),
                   )

        self.helper.form_method = 'POST'

但它给出了错误:

WARNING:root:Could not resolve form field '<django.forms.fields.ChoiceField object at 0x7fb1b32d26d8>'.

1 个答案:

答案 0 :(得分:1)

尝试生成Field个对象列表并将其传递给Layout

def __init__(self, *args, **kwargs):
    super(ReportSample, self).__init__(*args, **kwargs)

    sr_id = self.data.getlist('id')
    current_sr_id = sr_id[0]

    vasr_obj = VariantAnnotationSampleRun.objects.filter(
        sample_run_id=SampleRun.objects.get(id=current_sr_id)
    )

    fields = []
    for o in vasr_obj:
        str_id = str(o.id)
        fields.append(Field(str_id, css_class='search-sample'))
        self.fields[str_id] = forms.ChoiceField(
            choices=(
                ('dont_report', '-',),
                ('report', 'Report',),
                ('to_confirm', 'To confirm',),
            )
        )

    self.helper = FormHelper()
    self.helper.layout = Layout(
        *fields,
        Submit('submit', 'Submit', css_class='upload-btn'),
    )

    self.helper.form_method = 'POST'