Django 基于下拉列表动态创建表单 select

Django dynamic create form based on dropdown select

我正在使用 Django,问题和方法,有什么方法可以根据下拉列表 selection 生成动态表单吗? 我的表单非常简单,用户需要更新设备信息。 我不想一次提交一个表单,而是想提供带有下拉 select 设备数量的选项,比如说 10,应该有 10 个新表单条目。

1个Form中有4个栏位需要填写。 我开始了一些事情,但停留在通过 html

查看和显示

型号

class Devices(DeviceINFO, models.Model):
    name = models.ForeignKey(DeviceTYPE, on_delete=models.SET_NULL, null=True)
    item1_link1 = models.CharField(max_length=5, blank=True, default='')
    item1_link2 = models.CharField(max_length=5, blank=True, default='')
...

表格:

class Devices_form(forms.ModelForm):
    class Meta:
        model = Devices
        fields = '__all__'

    def __init__(self, n, *args, **kwargs):
        super(Devices_form, self).__init__(*args, **kwargs)
        for i in range(0, n):
            self.fields["item%d_link1" % i] = forms.CharField(max_length=20, blank=True, default='')
            self.fields["item%d_link2" % i] = forms.CharField(max_length=20, blank=True, default='')
... 

查看:

def DevicesView(request, *args, **kwargs):
    template_name = 'DeviceView.html'
    seq = [2, 4, 6, 8, 10]
    form = Devices_form(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            print(form.cleaned_data['seq'])
            context = { 'num': form.cleaned_data['seq'] }

    return render(request, template_name, {'seq': seq})

这样对吗?如何在html中显示?提前感谢您的帮助。

您可以根据请求的数量创建一个空表单列表,然后通过遍历该列表在模板中呈现它们。

def DevicesView(request, *args, **kwargs):
    template_name = 'DeviceView.html'
    seq = [2, 4, 6, 8, 10]
    form = Devices_form(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            print(form.cleaned_data['seq'])
            no_of_forms = form.cleaned_data['seq']
            list_of_forms = [device_form() for i in range(no_of_forms)]
            args = {'forms':list_of_forms}
            return render(request, template_name, args)

    return render(request, template_name, {'seq': seq})

然后在 HTML 中,类似于:

{% for form in forms %}
    {{ form.as_p }}
{% endfor %}