Many2ManyField不能通过Modelforms来保存

2024-04-19 01:15:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模型:

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

我试着添加表格保存\u m2m()但它说表单没有这个属性。所以现在,在使用oèu internationalisation的领域,m2m没有被保存。我不知道我做错了什么,需要帮助,谢谢!你知道吗


Tags: nameimageselfformtrueverbosemodelmain
1条回答
网友
1楼 · 发布于 2024-04-19 01:15:33

窗体没有save_m2m(),因为在执行form = form.save(commit=False)操作时使用模型实例重写了form

尝试使用instance = form.save(commit=False)等其他语言,然后你就可以使用form.save_m2m()(当然是在instance.save()之后)。你知道吗

相关问题 更多 >