使用Django动态将字段添加到模型表单 [英] Dynamically Add Field to Model Form Using Django
问题描述
我有一个模型,其中包含地址的字段,例如街道,城市,州,邮编.我创建了一个表格,允许用户为每个表格输入值.我现在想做的是让它可以让用户按下按钮,说添加地址",然后每个字段都会重复一次.我可以使用jquery向HTML添加字段,我的问题是这些多余的字段如何需要在模型中表示?
I have a model that has fields for an address such as Street, City, State, Zip. I have created a form that allows the user to input values for each of these. What I would like to do now is make it where the user can press a button, say "add address" and then each field would be repeated. I could use jquery to add fields to the HTML, My issue is how would these extra fields need to be represented in the model?
最终,我想获取其他地址并将其用于搜索中,在该搜索中,我将检索具有用户输入的任何地址的任何内容.任何帮助或建议,表示赞赏.
Ultimately, I'd like to take the additional addresses and use them in a search where I retrieve anything that has any of the addresses the user has input. Any help or suggestions is appreciated.
推荐答案
感谢维杰!我无法将您的答案标记为答案(不确定原因),但是您的链接帮助了我.
Thanks Vijay! I couldn't mark yours as the answer (not sure why) but your link helped me.
由于我只想重复一些字段,因此我只将这些字段放在表中.
Since I only wanted some fields to repeat, I put only those fields in the table.
<form id="myForm" method="post" action="">
{% for form in formset.forms %}
<p> {{ form.nonDuplicatingField }}
<p> {{ fomr.anotherNonDuplicatingField }}
<table border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td>{{ form.duplicatingField }}</td>
<td>{{ form.duplicatingFieldTwo }}</td>
<td>{{ form.duplicatingFieldThree }}</td>
</tr>
</tbody>
</table>
{% endfor %}
{{ formset.management_form }}
</form>
我包括了这个javascript(除了jquery和jquery.formset之外)
And I included this javascript (in addition to jquery and jquery.formset)
<script type="text/javascript">
$(function() {
$('#myForm tbody tr').formset();
})
</script>
这篇关于使用Django动态将字段添加到模型表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!