简体   繁体   English

使用Django动态将字段添加到模型表单

[英]Dynamically Add Field to Model Form Using Django

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? 我可以使用jquery向HTML添加字段,我的问题是这些多余的字段如何需要在模型中表示?

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>

And I included this javascript (in addition to jquery and jquery.formset) 而且我包括了这个javascript(除了jquery和jquery.formset之外)

<script type="text/javascript">
    $(function() {
        $('#myForm tbody tr').formset();
    })
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM