动态添加字段到窗体 [英] dynamically add field to a form

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

问题描述

我的表单中有3个字段。
我有一个提交按钮和一个按钮来添加附加字段。
我明白我可以在表单类中使用 __ init __ 方法添加字段。



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



当我点击添加其他字段按钮时,添加附加字段?



表单是否必须再次呈现?



如何以及何时调用 __ init __ 或者我甚至要调用它?



如何将参数传递给 __ init __

解决方案

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



我将以 FormSet 的工作方式来看这个问题:有一个隐藏的字段包含活动的表单数,并且每个表单名称都以表格索引。实际上,您可以使一个字段 FormSet



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



这是一个从头开始的 - 它应该给你一些想法。它也回答了关于将参数传递给 __ 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('extra',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)] = \
forms.CharField()


def myview ):
如果request.method =='POST':
form = MyForm(request.POST,extra = request.POST.get('extra_field_count')
如果form.is_valid():
打印valid!
else:
form = MyForm()
return render(request,template,{'form':form})



HTML



  form_count = Number($([name = extra_field_count])val()); 
//获取额外的表单数,所以我们知道用于下一个项目的索引。
$(#add-another)。click(function(){
form_count ++;

element = $('< input type =text >');
element.attr('name','extra_field_'+ form_count);
$(#forms)。append(element);
//构建元素将它附加到我们的表单容器

$([name = extra_field_count])。val(form_count);
//增加表单数,所以我们的视图知道要填充
/ /许多验证字段
})

< form>
< div id =forms>
{{form.as_p}}
< / div>
< button id =add-another>添加另一个< / button>
< input type =submit/>
< / form>


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 has 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

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

Views

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_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 ++;

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

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

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

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