Django表单插入记录而不是更新记录 [英] Django form insert record instead of update record
问题描述
我在Django中尝试更新一些记录时遇到一些问题:
当我尝试更新一些记录时,该应用程序会插入一个新的记录,我不知道为什么我有这个行为。
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.
模型
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'
查看:
@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))
形式:
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
我为其他模型使用相同的视图和表单定义来呈现编辑表单,而与其他模型的作品伟大,记录更新。
我不明白这是怎么回事
我重写表单,查看此模型的定义,我不知道是什么问题。
数据库是遗留数据库,表没有任何类型的关系或约束。
顺便说一句我使用Django脆皮表单
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
提前感谢
推荐答案
如果您使用相同的表单创建和更新视图,那么您需要在您的唯一字段上提供干净的方法,并在对象存在时引发ValidationError。
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.
但是在你的情况下,我假设你使用复合主键在字段:id_proveedor,num_archivos,你应该覆盖整个形式的清除方法:
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
这篇关于Django表单插入记录而不是更新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!