Recently I started experimenting with Python and Django. I like it, learned already a lot, but still a long way to go...
I made a model containing 5 image fields. Next to the model I also made a form to enter data and save it. So far so good. Now I want to write another form to 'edit' the uploaded images, meaning:
- upload new images
- delete the 'old' images from the database
I wrote the code below that does the job for 1 image:
if form.is_valid():
form_image = form.cleaned_data['image_1']
try:
details = Model.objects.get(pk=pk)
if details.image_1 != form_image:
details.image_1.delete(save=False)
except: pass # when new photo then we do nothing, normal case
form.save()
But I am struggling with following problems:
How can this code be rewritten to update 5 image fields? Because in worst case one can edit all 5 image fields. I tried with a 'for loop' but never succeed. For example:
image_list = [image_1, image_2, image_3, image_4, image_5] if form.is_valid(): for image in image_list: form_image = form.cleaned_data[image] try: details = Model.objects.get(pk=pk) if details.image != form_image: details.image.delete(save=False) except: pass # when new photo then we do nothing, normal case form.save()
Are there more intelligent ways to write this piece of logic. A problem that I have with this code is that it checks on the name of the image. And probably this goes wrong when I have multiple images with the same name...
Hopefully someone can give some feedback and point me again in the right direction.
Many thanks!
Kind Regards