向表单动态添加字段 [英] dynamically add field to a form

查看:51
本文介绍了向表单动态添加字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我是 Python 和 Django 的新手,并且被一个初学者问题困住了;我的问题是:

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

表单是否需要重新渲染?

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

如何将参数传递给 __init__?

解决方案

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

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

事实上,你可以制作一个字段FormSet

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

如果您不想使用 FormSet,您可以随时自行创建此行为.

这是一个从头开始制作的 - 它应该会给你一些想法.它还回答了您关于将参数传递给 __init__ 的问题 - 您只需将参数传递给对象构造函数: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('额外', 0)super(MyForm, self).__init__(*args, **kwargs)self.fields['extra_field_count'].initial = extra_fields对于范围内的索引(int(extra_fields)):# 在通过 extra_fields 指定的数量中生成额外的字段self.fields['extra_field_{index}'.format(index=index)] = 表单.CharField()

查看

def myview(request):如果 request.method == 'POST':form = MyForm(request.POST, extra=request.POST.get('extra_field_count'))如果 form.is_valid():打印有效!"别的:表单 = MyForm()返回渲染(请求,模板",{'表单':表单})

HTML

<div id="表单">{{ form.as_p }}

<button id="add-another">添加另一个</button><输入类型=提交"/></表单>

JS

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.

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?

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

How do I pass arguments to __init__?

解决方案

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.

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.

In fact, you could make a one field FormSet

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

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

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')

Forms

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()

View

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>

这篇关于向表单动态添加字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆