adding forms from formset on fly from server side

喜你入骨 提交于 2019-12-11 18:49:49

问题


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

here is what i have in 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})

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.


回答1:


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,})

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.



来源:https://stackoverflow.com/questions/5331489/adding-forms-from-formset-on-fly-from-server-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!