从服务器端动态添加来自formset的表单

从服务器端动态添加来自formset的表单

本文介绍了从服务器端动态添加来自formset的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{% for form in formset.forms %}
    <div class="elements">
           {{form.as_ul}}
     </div>
     <input type="image" value="ADD" id="add_more">
{% endfor %}

这是我在js中拥有的

$('#add_more').click(function(){
      if($('.app-form').valid()){
      cloneMore('div.ul:last','prefix');
    }
});

,其余与参考

and the rest is same as the reference this reference I'm trying to display forms when user goes for "ADD".when add is pressed it goes to the view as well as print one more form using jquery.in views.

  def start(request):
        qd = request.POST
        ffact = formset_factory(ModelForm,extra=int(qd['prefix-TOTAL_FORMS']))
        fset = ffact(qd,prefix='prefix')
        if fset.is_valid():
           return render_to_response('test.html',{'formset':fset})
        else:
           return render_to_response('test.html',{'formset':fset})

但是,即使提交的表单无效,jquery也会生成其他表单,而视图会导致所有无效表单域的错误消息.如何让点击动作等待或以某种方式与views.py验证结果通信然后才显示多余的表格?欣赏它.

But jquery is resulting in additional form even if the submitted form is not valid,while view is resulting in the error messages for all the form-fields that are not valid.How can i make click action wait or somehow communicate with the views.py validation result and only then display extra form? Appreciate it.

推荐答案

这可以通过两种方式完成:从用户端还是从后端,但是到我的问题NO. jquery/django为此.我正在尝试在服务器端执行整个操作:在views.py中:

this could be done in two ways :either from user end or from backend but to my question NO.there is no way[i dint find one] to tie jquery/django for this purpose.I'm trying to do the entire thing at server end:in views.py:

query_dict = request.POST
tot = int(querydict['prefix-TOTAL_FORMS'])
   ffact = formset_factory(ModelForm,extra=tot)
   fset = ffact(query_dict,prefix='prefix')
   if fset.is_valid():
      ffact = formset_factory(ModelForm,extra=1)
      fset = ffact(initial=fset.cleaned_data,prefix='prefix')
      return render_to_response('test.html',{'formset':fset,})

在test.html中:

in test.html:

{% for form in fset.forms%}
    {{form.as_ul}} or anything that works for you
{% endfor %}

这对我有用,可能有更有效的方法.我很乐意了解它.

this worked for me,there might be more efficient way. I'm more than happy to learn about it.

这篇关于从服务器端动态添加来自formset的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!