How to edit/update/change the image in Django

In Django whenever we change the value for Image Field, a path is created for that image. Here I will be using Django form to edit/change the image. The reason for using the Django forms is that it will automatically set the path for image which really reduce the extra work for setting the path manually for image.

let’s take an example of models.py having image field in class product and stored in static folder, it can be any folder, it’s up to you where you want to store it.

example class product with image field

Now for the Image field in class Product i will create Django form.

Now I have Edit function in Views.py file where i have written code for updating the image field.

views.py file

On line 60 I am filtering out the that object for which i will update the image. On line 61 I am taking the new updated data and updated image for that particular object i filtered out on line 60 which is stored in variable name ”old_image” .

On line 63 the word image is actually the variable name to store the image field in models (image = models.CharField(upload_to=’static/’)

Here you can see the word “instance” , this will collect the data for filtered object which i want to update. From line 63 to 65 the old image path will be removed if it exists. Line 66 will both save the image and set the image path automatically.

Python Programmer, Django Developer