0

In my project I encountered the following error. enter image description here

In my view I copies files from one model to another. However, it seems that some files do not have a counterpart and verification shows that they path exist FileNotFoundError at /home/. It seems the path exists but the file on the server does not. How to check if file exists before saving to a new model.

My code:

if product.img_1:
    obj_apartment.basic_img = product.img_1

I need something like this:

if product.img_1.open():
    obj_apartment.basic_img = product.img_1
Maddie Graham
  • 2,019
  • 4
  • 25
  • 51
  • 1
    Since your original `if product.img_1:` is correct, and from your other question `{% if obj.profile_pictures %}` is correct, the error is elsewhere. Perhaps your settings.py `MEDIA_ROOT` or `MEDIA_URL`, or your product class' `ImageField(upload_to=...` value is where the error lies. Are you sure it is the file that does not exist and not the directory, `/home/app/app/app/category-pictures/` with 3 `app`'s? – raphael Nov 01 '22 at 18:02
  • File does not exist. The directory exists. Media root and media url works fine. Functions in my question work fine. The error occurred with about 50 products per 5 thousand. I mean use Celery to transfers from one model to another model. I wanted to generate an error locally, so I added an object and deleted the entire media folder. I see the same error. Maybe someone deleted files on the server ... is there any way to prevent django from picking up a fatal error but displaying the template without for example image or with an alternative image whean meet `[Errno 2] No such file or directory`. – Maddie Graham Nov 01 '22 at 18:16
  • 1
    And storage.exists() doesn't help? As given here https://stackoverflow.com/q/50606068/10951070? Sorry, don't know what else to try. – raphael Nov 01 '22 at 18:49
  • In the view works fine. But, if we render queryset in a template, is there an alternative? – Maddie Graham Nov 01 '22 at 18:54
  • If it works in the view, then create a custom filter (https://docs.djangoproject.com/en/4.1/howto/custom-template-tags/) lilke https://stackoverflow.com/q/18364547/10951070 and that should work in the template – raphael Nov 01 '22 at 19:20

0 Answers0