添加内联行而不添加javascript而不添加行

时间:2013-08-30 05:31:49

标签: django django-forms

我正在尝试添加没有javascript的内联行,类似于此SO帖子:Django: Adding inline formset rows without javascript

但是,当我按下add时,表单会重新初始化并且不会添加额外的行。我做错了什么?

forms.py

IndicatorFormSet2 = inlineformset_factory(Disease, Indicator)

views.py

  disease = get_object_or_404(Disease, pk=disease_id)  

  if request.method == "POST": 
      if 'add' in request.POST:
        cp = request.POST.copy()
        cp['form-TOTAL_FORMS'] = int(cp['form-TOTAL_FORMS'])+1
        indicatorInlineFormSet = IndicatorFormSet2(request.POST, cp, prefix='form')
        return HttpResponseRedirect(reverse('drui', kwargs={'disease_id':disease_id}))

  if indicatorInlineFormSet.is_valid():
      indicatorInlineFormSet.save()
      return HttpResponseRedirect(reverse('valdrui', kwargs={'disease_id':disease_id}))

  else:
      indicatorInlineFormSet = IndicatorFormSet2(instance=disease, prefix='form')

2 个答案:

答案 0 :(得分:0)

我认为您需要更新formsets factory以获得更多表单,例如:

disease = get_object_or_404(Disease, pk=disease_id)  

  if request.method == "POST": 
      if 'add' in request.POST:
        cp = request.POST.copy()
        total = int(cp['form-TOTAL_FORMS'])

        #add max_num and extra params to formset factory
        IndicatorFormSet2 = inlineformset_factory(Disease, Indicator, 
                            max_num=total+1, extra=1)

        indicatorInlineFormSet = IndicatorFormSet2(request.POST, cp, prefix='form')
        return HttpResponseRedirect(reverse('drui', kwargs={'disease_id':disease_id}))

答案 1 :(得分:0)

我实际上能够解决这个问题。

views.py

 if indicatorInlineFormSet.is_valid() and 'add' in request.POST:
     indicatorInlineFormSet.save()
     return HttpResponseRedirect(reverse('drui', kwargs={'disease_id':disease_id}))

 elif indicatorInlineFormSet.is_valid():
     indicatorInlineFormSet.save()
     return HttpResponseRedirect(reverse('next_page', kwargs={'disease_id':disease_id}))

forms.py

 IndicatorFormSet2 = inlineformset_factory(Disease, Indicator, extra=1)

表格将通过额外的内联来验证和反转。