你如何在Django中创建动态表单? [英] How would you make a dynamic formset in Django?

查看:1132
本文介绍了你如何在Django中创建动态表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我做的方式:

{{ formset.management_form }}
<table>
    {% for form in formset.forms %}
        {{ form }}
    {% endfor %}
</table>
<a href="javascript:void(0)" id="add_form">Add Form</a>   

这里是JS:

var form_count = {{formset.total_form_count}};
$('#add_form').click(function() {
    form_count++;
    var form = '{{formset.empty_form|escapejs}}'.replace(/__prefix__/g, form_count);
    $('#forms').append(form)
    $('#id_form-TOTAL_FORMS').val(form_count);
});

什么特别让我感到,我不得不写那个 escapejs 模板标签我自己。它只是剥离所有的换行符,并转义任何单引号,这样不会弄乱我的字符串。但是Django制造商在这种情况下希望我们做什么呢?为什么他们有这个 TOTAL_FORMS 隐藏字段,当他们可以使用像< input name =my_form_field [0]/ < / code>然后再计算其长度?

What specifically bothers me is that I had to write that escapejs template tag myself. It just strips all newlines and escapes any single quotes so that it doesn't mess up my string. But what exactly did the Django makers expect us to do in this situation? And why do they have this TOTAL_FORMS hidden field, when they could have just used an array like <input name="my_form_field[0]" /> and then counted its length instead?

推荐答案

Django中有几个地方 为什么是因为这是Django管理应用程序的实现方式,我相信这是其中之一。因此,答案是他们希望您实现自己的JavaScript。

There are a few places in Django where "the reason why" is because that's how it was implemented for the Django admin app, and I believe this is one of them. Thus the answer is they expect you to implement your own javascript.

看到这个SO问题动态地添加一个表单... 了解更多的javascript想法。

See this SO question Dynamically adding a form... for some more javascript ideas.

还有两个可插拔应用程序, django-dynamic-formset django-dinamyc-form ,直到刚才看到,我才看到第一个。

There are also two pluggable apps available, django-dynamic-formset and django-dinamyc-form which I hadn't seen until just now when looking up the first one.

这篇关于你如何在Django中创建动态表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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