Django form insert record instead of update record

2019-08-07 05:37发布

问题:

I am having some issues trying to update some records in Django: When i try to update some record, the app insert a new one, I don't know why i have this behavior.

Model

class DetalleRecepcion(models.Model):
    id_proveedor = models.ForeignKey(Proveedor,db_column='id_proveedor',primary_key=True, verbose_name='Proveedor')
    anio = models.IntegerField( null=False)
    mes = models.IntegerField(verbose_name='Mes')
    fecha_recepcion = models.DateField(verbose_name='Fecha Recepcion')
    usuario = models.CharField(max_length=15, blank=True)
    num_archivos = models.IntegerField(primary_key=True, verbose_name='No de archivos')
    class Meta:
        managed = False
        db_table = 'mpc_detalle_recepcion'

view:

@login_required(login_url='/login/')
def DetRecView(request):
    idp = request.GET.get('i')
    anio = request.GET.get('a')
    mes = request.GET.get('m')
    if request.method == 'POST':
       r = DetalleRecepcion.objects.get(id_proveedor=idp,anio=anio,mes=mes)
       form = DetRecForm(request.POST or None, instance =r)
       if form.is_valid():
          form.save()
          return HttpResponse('<script type="text/javascript">window.close()</script>')
    else:
       r = DetalleRecepcion.objects.get(id_proveedor=idp,anio=anio,mes=mes)
       r.usuario = request.user
       form = DetRecForm(instance=r)

    return render_to_response('detrec.html',
                              {'form':form},
                              context_instance=RequestContext(request))

Form:

class DetRecForm(forms.ModelForm):
      fecha_recepcion = forms.DateField(widget=DateInput(),)
      def __init__(self,*args,**kwargs):
          super(DetRecForm,self).__init__(*args,**kwargs)
          self.helper = FormHelper(self)
          self.helper.layout = Layout(
           Field('id_proveedor',
                 'anio',
                 'mes',
                 'usuario',
                 readonly = True
                 ),
           Fieldset('',
                    'fecha_recepcion',
                    'num_archivos',
                    Submit('save','Grabar'),
                    HTML('<a class="btn btn-danger" id="cerrar">Cancelar</a>')
                    )
          )
      class Meta:
          model = DetalleRecepcion

I use the same view and form definition for others models to render edit forms and with this other models works great and the records are updated. I don't understand what it's happen. I rewrite the form, view definition for this model and I don't know what it is the problem. The database is a legacy database and the tables doesn't have any kind of relationship or constraint. By the way I am using Django crispy form

Thanks in advance

回答1:

If you using same form for create and update views, then you need provide clean method on your unique field and raise ValidationError when object exists.

But in your case, I assuming you using Composite Primary Key on fields: id_proveedor, num_archivos, you should override clean method of the whole form:

class DetRecForm(forms.ModelForm):
    fecha_recepcion = forms.DateField(widget=DateInput())

    def __init__(self, *args, **kwargs):
        super(DetRecForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.layout = Layout(
            Field('id_proveedor',
                  'anio',
                  'mes',
                  'usuario',
                  readonly=True
            ),
            Fieldset('',
                     'fecha_recepcion',
                     'num_archivos',
                     Submit('save', 'Grabar'),
                     HTML('<a class="btn btn-danger" id="cerrar">Cancelar</a>')
            )
        )

    def clean(self):
        cleaned_data = super(DetRecForm, self).clean()

        id_proveedor = self.cleaned_data['id_proveedor']
        num_archivos = self.cleaned_data['num_archivos']

        qs = self.Meta.model.objects.filter(id_proveedor=id_proveedor, num_archivos=num_archivos)
        if self.instance:
            qs = qs.exclude(pk=self.instance.id)
        if qs.count() > 0:
            raise forms.ValidationError(u'Such object exists!')

        return cleaned_data

    class Meta:
        model = DetalleRecepcion


回答2:

Try to get object by pk for instance

DetalleRecepcion.objects.get(pk=kwargs['pk'])