[Django]-Form object has no attribute 'save_m2m' django

4👍

Try it like this

form.save(commit=False)
form.save_m2m()
👤Malik

0👍

Try editing your view like this,

def form_valid(self, form, **kwargs):
    product = form.save(commit=False)
    product.slug = slugify(form.instance.title)
    product.shop = Shop.objects.get(slug=self.kwargs['slug'])
    product.save()
    if form.cleaned_data['uploaded_images']:
        if ',' in form.cleaned_data['uploaded_images']:
            for item in form.cleaned_data['uploaded_images'].split(','):
                try:
                    media = Media.objects.get(id=int(item))
                    product.images.add(media)
                except ObjectDoesNotExist:
                    pass
        else:
            try:
                media = Media.objects.get(id=int(form.cleaned_data['uploaded_images']))
                product.images.add(media)
            except ObjectDoesNotExist:
    # **Edited here**..
    product.save_m2m()
    if form.cleaned_data['removed_images']:
        for item in form.cleaned_data['removed_images'].split(','):
            try:
                media = Media.objects.get(id=int(item))
                image_path = MEDIA_ROOT + '/' + media.image.name
                os.remove(image_path)
                media.delete()
            except ObjectDoesNotExist:
                pass

    return super(ProductCreateView, self).form_valid(form)

0👍

I’ve rewrote my model with adding new variable to Media. And in view I’ve changed from

product.images.add(media)

to

product.media_set.add(media)

and My model

class Media(models.Model):
class Meta:
    verbose_name = "Изображение"
    verbose_name_plural = "Изображения"

image = models.ImageField(upload_to='images')
products = models.ManyToManyField(Product)

def __str__(self):
    return self.image.url

in class Product I deleted var images

Leave a comment