[Django]-Django โ€“ How to update a field inside a model save() method?

1๐Ÿ‘

Move the super save to the end of save() so it updates the model after you make your changes.

def save(self, *args, **kwargs):
    if not self.id:
        BicycleAdItemKind.tree.insert_node(self, self.parent)

    pdb.set_trace()
    # I will move the file from "Temp" folder to the folder with the "Id" number
    from django.core.files.move import file_move_safe
    src = settings.MEDIA_ROOT + "/" + self.image_file_temp_fullpath 
    dst = settings.MEDIA_ROOT + "/" + "MultimediaData/HelpAdImages/ItemKind/%s/%s" % (self.id, self.image_file_temp_filename)
    new_directory = settings.MEDIA_ROOT + "/MultimediaData/HelpAdImages/ItemKind/%s" % (self.id)
    if not os.path.exists(new_directory):
        os.makedirs(new_directory)

        if file_move_safe(src, dst):
            # I will update the field image
            BicycleAdItemKind.objects.filter(pk=self.id).update(image=dst)
            # Delete the Temp file

    super(BicycleAdItemKind, self).save(*args, **kwargs)
๐Ÿ‘คravishi

0๐Ÿ‘

Have you tried checking to see what dst is when you run the update? Why not do it like this?

self.image=dst
๐Ÿ‘คgirasquid

Leave a comment