Search code examples
pythondjangoimagedjango-modelsimagefield

Django do not update ImageField


Why Django update() do not update image file in media folder, but update everything else in update process.. Old image is in media folder, but there is no new image in folder.. When creating (using save()) everything is fine.. Any help, thanks in advance...

Here is the model class:

class Company(models.Model):
    name = models.CharField(max_length=100)
    companyAddress = models.CharField(max_length=70)
    companyPhoneNumber = models.CharField(max_length=30)
    companyDescription = models.CharField(max_length=150)
    companyProfileImage = models.ImageField(upload_to='images/', default = "images/defaultCompany.jpg", null = True)

Here is the code that I use when update:

newName = request.data['name']
newAddress = request.data['address']
newPhoneNumber = request.data['phoneNumber']
newDescription = request.data['description']
newCompanyProfileImage = request.data['image']

Company.objects.filter(id = companyId).update(name = newName, companyAddress = newAddress,
                companyPhoneNumber = newPhoneNumber, companyDescription = newDescription, companyProfileImage = newCompanyProfileImage)
        


Solution

  • The .update method bypasses the model's save method.

    As noted in the docs:

    The file is saved as part of saving the model in the database, so the actual file name used on disk cannot be relied on until after the model has been saved.

    Because you are using .update, you are bypassing the save method and therefore the image is not saved to disk.

    You must either (1) use .save to update the image OR (2) access the field storage class to 'manually' place the image in the correct location according to the configured storage backend (tricky, potentially unreliable so should be done in a transaction).

    Since you're just updating one object, just using the .save method is probably the most straightforward solution:

    obj = Company.objects.filter(id=companyId)
    obj.name = newName
    obj.companyAddress = newAddress
    # ... etc
    obj.companyProfileImage = newCompanyProfileImage
    obj.save()