class ProductImageForm(forms.ModelForm):
class Meta:
model = ProductImage
fields = ['product', 'original', 'caption']
# use ImageInput widget to create HTML displaying the
# actual uploaded image and providing the upload dialog
# when clicking on the actual image.
widgets = {
'original': ImageInput(),
}
def save(self, *args, **kwargs):
# We infer the display order of the image based on the order of the
# image fields within the formset.
kwargs['commit'] = False
obj = super(ProductImageForm, self).save(*args, **kwargs)
obj.display_order = self.get_display_order()
obj.save()
return obj
def get_display_order(self):
if self.prefix:
return self.prefix.split('-').pop()
else:
return 1
我正在使用django modelformset_factory将图像插入到数据库中并更新图像。现在的问题是在使用modelformset_factory时将图像插入数据库而不是更新。以下是我的代码。请帮我更新除了保存
ImageFormSet = modelformset_factory(ProductImage,
form=ProductImageForm, extra=0, can_delete=True)
formset = ImageFormSet(self.request.POST or None, self.request.FILES or None, data)
if formset.is_valid():
try:
instances = formset.save(commit=False)
for instance in instances:
instance.save()
except Exception as e:
pass
else:
err = formset.errors
raise error_message(err)