2017-08-03 87 views
0

我有一個模型表單集,但是當我嘗試保存多個表單集我得到的錯誤:保存表單集在Django

KeyError at /auditoria/auditoria_tab/ 'id_control'

我的觀點:

@staff_member_required 
def AuditoriaView(request): 
    class RequiredFormset(BaseFormSet): 
     def __init__(self,*args,**kwargs): 
     super(RequiredFormset,self).__init__(*args,**kwargs) 
     for form in self.forms: 
      form.empty_permitted = False 

    auditoriaFormset = formset_factory(AuditoriaForm,max_num=31,formset=RequiredFormset) 

    if request.method == 'POST': 
     usuario = request.user 
     accion = 'Registro nuevo Detalle de Auditoria' 
     formset = auditoriaFormset(request.POST) 
     for form in formset.forms: 
     if formset.is_valid(): 
      obj = form.save(commit=False) 
      #obj.id_control = control 
      obj.auditor = request.user 
      obj.save() 
    else: 
     formset = auditoriaFormset() 

    return render_to_response('audit_auditoria.html', 
           {'formset':formset}, 
           context_instance=RequestContext(request)) 

我的表格:

class AuditoriaForm(forms.ModelForm): 
    id_control = forms.ModelChoiceField(queryset=Control.objects.all().order_by('nombre'),\ 
             required=True,label='Control', widget=forms.Select(attrs={'class':'form-control'})) 
    id_analista = UserModelNameChoiceField(queryset=User.objects.filter(is_staff=False),\ 
              required = True, label='Analista', widget=forms.Select(attrs={'class':'form-control'})) 
    fecha = forms.DateField(widget=DateInputCustom()) 
    id_tipoerror = forms.ModelChoiceField(queryset=TipoError.objects.all(),required=True, label='Tipo Falla', widget=forms.Select(attrs={'class':'form-control'})) 
    id_sharepoint = forms.IntegerField(label='Sharepoint', widget=forms.NumberInput(attrs={'class':'form-control','style': 'width:80px'})) 
    id_estado = forms.ModelChoiceField(queryset=Estado.objects.all(),required=True, label='Estado', widget=forms.Select(attrs={'class':'form-control'})) 
    observaciones = forms.CharField(widget=forms.Textarea(attrs={'rows':5,'cols':30})) 

    class Meta: 
     model = DetalleAuditoria 
     exclude = ('auditor',) 

    def __init__(self,*args,**kwargs): 
     super(AuditoriaForm,self).__init__(*args,**kwargs) 
     self.helper = FormHelper(self) 

    def clean(self): 
     cleaned_data = super(AuditoriaForm,self).clean() 
     idc = cleaned_data['id_control'] 
     fechac = cleaned_data['fecha'] 

     try: 
     DetalleAuditoria.objects.get(id_control = idc,fecha = fechac) 
     raise forms.ValidationError('Esta Incidencia ya ha sido registrada') 
     except DetalleAuditoria.DoesNotExist: 
     pass 

     return cleaned_data 

模板:

<form id="form_audit" class="form" method="post" action="/auditoria/auditoria_tab/"> 
      <table class="table table-responsive table-condensed table-bordered"> 
       {{ formset.management_form }} 
       {% for form in formset.forms %} 
       <thead> 
       <th class="info"colspan="6"> 
        <label >{{ form.id_control.label|capfirst }} </label> 
        {{ form.id_control }} 
       </th> 
       </thead> 
       <thead> 
       <th>{{ form.id_analista.label|capfirst }}</th> 
       <th>{{ form.id_sharepoint.label|capfirst }}</th> 
       <th>{{ form.fecha.label|capfirst }}</th> 
       <th>{{ form.id_tipoerror.label|capfirst }}</th> 
       <th>{{ form.id_estado.label|capfirst }}</th> 
       <th>{{ form.observaciones.label|capfirst }}</th> 
       <thead> 
       <tbody> 
       <tr class="{% cycle row1,row2 %} formset_row"> 
       <td>{{ form.id_analista }}</td> 
       <td>{{ form.id_sharepoint }}</td> 
       <td>{{ form.fecha }}</td> 
       <td>{{ form.id_tipoerror }}</td> 
       <td>{{ form.id_estado }}</td> 
       <td>{{ form.observaciones }}</td> 
       </tr> 
       {% endfor %} 
       </tbody> 
      </table> 
       <input type="submit" class="btn btn-info" value="Registrar"> 
      </form> 

{% block extra_js %} 
<script src="{{STATIC_URL|default:"/static/"}}admin/js/jquery.formset.js"></script> 

<script type="text/javascript"> 

    function renewDatePickers() { 
    $('.datepicker').datepicker('destroy'); 
    $('.datepicker').datepicker({ 
     format: "yyyy-mm-dd", 
     startDate: "2014-01-01", 
     endDate: "2020-01-01", 
     autoclose: true 
    }); 
    } 

    $(renewDatePickers); 

    $('.formset_row').formset({ 
     addText: 'Agregar Detalle Auditoria', 
     deleteText: 'Eliminar', 
     prefix: '{{ formset.prefix }}', 
     added: renewDatePickers 
    }); 

</script> 

{% endblock extra_js %} 

當我想保存數據時,如何從其他表單集中的第一個formset中使用字段ID_CONTROL。

我不確定我是否以正確的方式使用了formset ?.

任何意見

由於提前

更新: 我得到的錯誤,在 「清潔」 功能。當視圖試圖挽救該行appeare第二表單集療法錯誤的:

idc = cleaned_data['id_control'] 

在錯誤頁面,我可以看到的帖子,我可以看到第一個表單集的ID_CONTROL值,但第二formset我看到除了id_control之外的所有字段。

+0

可以共享完整的錯誤消息? – Jayground

+0

@Jayground這是我得到的所有消息。這個錯誤顯示了我從表單中清除函數的異常,我認爲在第二個formset中沒有id_control的價值 – joselegit

+0

難以遵循,請嘗試構建一個最小可重現版本。 – slackmart

回答

0

在我看來,以這種方式將相同的控制ID放入下一個表格中是沒有意義的。 總之,要解決你問什麼,這應該是有效的(具有不同的「出生日期」值的形式):

id_control=None 
    if request.method == 'POST': 
     usuario = request.user 
     accion = 'Registro nuevo Detalle de Auditoria' 
     formset = auditoriaFormset(request.POST) 

     for counter, form in enumerate(formset.forms): 
     if formset.is_valid(): 
      obj = form.save(commit=False) 
      if counter>0: 
       obj.id_control = id_control 
      obj.auditor = request.user 
      obj.save() 
      if counter==0: 
       id_control=obj.id_control 
    else: 
     formset = auditoriaFormset()