Many2ManyField不通过Modelforms保存

时间:2010-02-07 21:28:37

标签: python django

我有一个模型形式:

class POwner4NewModel(ModelForm):
    class Meta:
        model = ProductOwner
        exclude = ("o_owner","o_owner_desc","o_product_model","o_main_image","o_thumbnail","o_gallery_images","o_timestamp","o_status")

这是模型的架构:

class ProductOwner(models.Model):
    o_owner = models.ForeignKey(User, verbose_name="Owner")
    o_owner_desc = models.TextField(verbose_name="Seller Description")
    o_product_model = models.ForeignKey(ProductModel, verbose_name="Product")
    o_main_image = models.ImageField(upload_to=settings.CUSTOM_UPLOAD_DIR, verbose_name="Product Main Image", blank=True)
    o_thumbnail = models.ImageField(upload_to=settings.CUSTOM_UPLOAD_DIR, verbose_name="Product Thumbnail (100x100)px", blank=True)
    o_gallery_images = models.ManyToManyField(ProductImages, verbose_name="Product Gallery Images", related_name="product_images", blank=True)    
    o_status = models.CharField(max_length=100, choices=PRODUCT_STATUS, verbose_name="Product Status", default="approved")
    o_timestamp = models.DateTimeField(auto_now_add=True, verbose_name="Date Created")
    o_internationlisation = models.ManyToManyField(Countries, verbose_name="Available in", related_name="product_countries")

这是我的代码试图保存表单:

def save_m_owner(self, request):
    form = POwner4NewModel(request.POST, request.FILES)
    form = form.save(commit=False)
    form.o_owner = request.user
    form.o_owner_desc = self.product_model.p_description
    form.o_product_model = self.product_model
    form.o_status = "unapproved"
    form.o_main_image = self.product_model.p_main_image
    form.save()

我已经尝试添加form.save_m2m(),但它表示表单没有该属性。所以现在,在使用o_internationlisation的字段中,不保存m2m。我不确定我在这里做错了什么,可以使用一些帮助,谢谢!

1 个答案:

答案 0 :(得分:4)

表单没有save_m2m(),因为您在执行form

时用模型实例覆盖了form = form.save(commit=False)

尝试使用其他内容,例如instance = form.save(commit=False)等,然后您应该可以使用form.save_m2m()(当然在instance.save()之后)。