开发者

Many2ManyField is not saving via Modelforms

开发者 https://www.devze.com 2022-12-19 05:29 出处:网络
I have a Modelform: class POwner4NewModel(ModelForm): class Meta: model = ProductOwner exclude = (\"o_owner\",\"o_owner_desc\",\"o_product_model\",\"o_main_image\",\"o_thumbnail\",\"o_gallery_images\

I have a Modelform:

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")

This is the model's schema:

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")

This is my code trying to save the form:

def save_m_owner(self, request):
    form = POwner4NewModel(re开发者_高级运维quest.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()

I've tried adding form.save_m2m() but it says form does not have that attribute. So now, in the field using o_internationlisation, the m2m is not saved. I'm not sure what I'm doing wrong here, could use some help, thanks!


form doesn't have save_m2m() because you overwrote form with a model instance when you did form = form.save(commit=False)

try using something else like instance = form.save(commit=False) etc. then you should be able to use form.save_m2m() (of course after the instance.save()).

0

精彩评论

暂无评论...
验证码 换一张
取 消