Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango - for-loop with variable field name
    primarykey
    data
    text
    <p>Recently I started experimenting with Python and Django. I like it, learned already a lot, but still a long way to go...</p> <p>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:</p> <ol> <li>upload new images</li> <li>delete the 'old' images from the database</li> </ol> <p>I wrote the code below that does the job for 1 image: </p> <pre><code>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() </code></pre> <p>But I am struggling with following problems:</p> <ol> <li><p>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:</p> <pre><code>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() </code></pre></li> <li><p>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...</p></li> </ol> <p>Hopefully someone can give some feedback and point me again in the right direction.</p> <p>Many thanks!</p> <p>Kind Regards</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload