[Answered ]-Django ImageField upload_to value from M2M relation

2👍

You must save the instance, which is an instance of Image(), and M2M relations w/ albums, at first, before access instance.albums.all().

Check Django admin file upload with current model id for the point of saving Model before using it’s pk in upload_to(). Since M2M get in the way here, instead of post_save() method mentioned in the post, use m2m_changed signal to inform the ready of instance.albums.all(), something like:

@receiver(m2m_changed, sender=Image.albums.through)
def save_file_on_m2m(sender, instance, action, **kwargs):
    if action == 'post_add' and hasattr(instance, _UNSAVED_FILEFIELD):
        instance.image = getattr(instance, _UNSAVED_FILEFIELD)
        instance.save()        
        instance.__dict__.pop(_UNSAVED_FILEFIELD)

This depends on the m2m values for Image.albums, if there is not any, image would be lost. Thus I would suggest using some other key which is more solid then this.

Also you may work on modelform directly to save image field manually, after save the Image() itself and M2M relations.

👤okm

Leave a comment