如何通过formset修改现有对象

[英]how to modify existing object by formset


I have a Product Model like this:

我有这样的产品型号:

class Product(models.Model):
   title = models.TextField(max_length=200)

and a Image Model like this:

和像这样的图像模型:

class Image(models.Model):
    product = models.ForeignKey(Product)
    image = models.ImageField(upload_to=....)

Now, I can add a product with multiple image by formset, but what should I do to modify existing product. In server-side code, I need to know which image be modified, which image is new added, which image be deleted. Of course, I can to do it by normal way, just like if I delete a image, I will change it's name to "delete-img_id" through javascript, if I modify a image, I can change it's name to "modify-img_id", then check it in django server-side and handle them with correctly operate, like this:

现在,我可以通过formset添加具有多个图像的产品,但是我应该怎么做才能修改现有产品。在服务器端代码中,我需要知道要修改哪个图像,新添加哪个图像,删除哪个图像。当然,我可以通过正常的方式来做,就像我删除图像一样,我会通过javascript将其名称更改为“delete-img_id”,如果我修改图像,我可以将其名称更改为“modify-img_id” “,然后在django服务器端检查它并正确操作处理它们,如下所示:

def check_img(name):
   operate = name.split("-")[0]
   img_id = name.slipt("-")[1]
   if operate == "modify": modify_img(img_id)

1 个解决方案

#1


0  

you can override save_formset method of ModelAdmin

您可以覆盖ModelAdmin的save_formset方法

def save_formset(self, request, form, formset, change):
    if formset and formset.has_changed():
        quiz_obj = formset.save(commit=False)[0].product
        # todo 
    return super(ProductAdmin, self).save_formset(request, form, formset, change)

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2016/04/18/affeac868001d3ae203a58c23fa04dd6.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号