dynamically add field to a form(动态添加字段到表单)
问题描述
我的表单中有 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 FormSet
s 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>
这篇关于动态添加字段到表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:动态添加字段到表单
基础教程推荐
- 如何在Python中绘制多元函数? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01