动态添加字段到表单

2022-01-31 00:00:00 python django django-forms

问题描述

我的表单中有 3 个字段.我有一个提交按钮和一个添加附加字段"按钮.我知道我可以在表单类中使用 __init__ 方法添加字段.

I have 3 fields in my form. I have a submit button and a button to "Add additional Field". I understand I can add fields using __init__ method in the form class.

我是 Python 和 Django 的新手,遇到一个初学者问题;我的问题是:

I am new to Python and Django and am stuck with a beginner question; my question is:

当我点击添加附加字段"按钮时,添加附加字段的过程是什么?

When I click the "Add additional field" button, what is the process to add the additional field?

表单是否必须再次呈现?

Does the form have to be rendered again?

如何以及何时调用 __init__ 或者我什至必须调用它?

How and when do I call __init__ or do I even have to call it?

如何将参数传递给 __init__?


解决方案

您的表单必须基于从您的 POST 传递给它的一些变量来构建(或盲目检查属性).每次重新加载视图时都会构建表单本身,无论是否出错,因此 HTML 需要包含有关有多少字段的信息,以构建正确数量的字段进行验证.

Your form would have to be constructed based on some variables passed to it from your POST (or blindly check for attributes). The form itself is constructed every time the view is reloaded, errors or not, so the HTML needs to contain information about how many fields there are to construct the correct amount of fields for validation.

我会以 FormSet 的工作方式来看待这个问题:有一个隐藏字段包含活动表单的数量,并且每个表单名称前面都带有表单索引.

I'd look at this problem the way FormSets work: there is a hidden field that contains the number of forms active, and each form name is prepended with the form index.

其实你可以做一个单字段FormSet

In fact, you could make a one field FormSet

https://docs.djangoproject.com/en/dev/topics/forms/formsets/#formsets

如果您不想使用 FormSet,您始终可以自己创建此行为.

If you don't want to use a FormSet you can always create this behavior yourself.

这是一个从头开始制作的 - 它应该会给你一些想法.它还回答了您关于将参数传递给 __init__ 的问题 - 您只需将参数传递给对象构造函数:MyForm('arg1', 'arg2', kwarg1='keyword arg')

Here's one made from scratch - it should give you some ideas. It also answers your questions about passing arguments to __init__ - you just pass arguments to an objects constructor: MyForm('arg1', 'arg2', kwarg1='keyword arg')

class MyForm(forms.Form):
    original_field = forms.CharField()
    extra_field_count = forms.CharField(widget=forms.HiddenInput())

    def __init__(self, *args, **kwargs):
        extra_fields = kwargs.pop('extra', 0)

        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['extra_field_count'].initial = extra_fields

        for index in range(int(extra_fields)):
            # generate extra fields in the number specified via extra_fields
            self.fields['extra_field_{index}'.format(index=index)] = 
                forms.CharField()

查看

def myview(request):
    if request.method == 'POST':
        form = MyForm(request.POST, extra=request.POST.get('extra_field_count'))
        if form.is_valid():
            print "valid!"
    else:
        form = MyForm()
    return render(request, "template", { 'form': form })

HTML

<form>
    <div id="forms">
        {{ form.as_p }}
    </div>
    <button id="add-another">add another</button>
    <input type="submit" />
</form>

JS

<script>
let form_count = Number($("[name=extra_field_count]").val());
// get extra form count so we know what index to use for the next item.

$("#add-another").click(function() {
    form_count ++;

    let element = $('<input type="text"/>');
    element.attr('name', 'extra_field_' + form_count);
    $("#forms").append(element);
    // build element and append it to our forms container

    $("[name=extra_field_count]").val(form_count);
    // increment form count so our view knows to populate 
    // that many fields for validation
})
</script>

相关文章