M
M
mkone1122020-12-16 14:05:06
Django
mkone112, 2020-12-16 14:05:06

How to use static file in ImageField by default?

If you specify a default file in the field, then when creating new instances of the model - instead of using all instances of one file - many copies of this file are created at the root. How can this be avoided?
...
app/
└── static/
│ └── img.png # instead of using this file

└── models.py

...
class ModelWithDefaultStaticImage(models.Model):
    image_file = models.ImageField(default='img.png')


img_iGJ3tYB.png # a copy is created for each instance of the model
...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Melnikov, 2020-12-16
@mkone112

Doing on the advice of Dr. Bacon Set
the model to Null

class officeUsers(models.Model):
    ....
    photo = models.ImageField(verbose_name='Фотография',
                              upload_to='photos/%Y/%m/%d',
                              blank=True)
    ....

Checking in the template
<div class="user_img">
      <img src="{% if user.photo %}{{ user.photo.url }}{% else %}{% static 'sysadmins/img/avatar.jpg' %}{% endif %}" alt="">
</div>

D
Dr. Bacon, 2020-12-16
@bacon

Make null, and when output, check and slip the desired one

D
dooMoob, 2020-12-16
@dooMoob

Did something like this. Implemented something like this:
When creating a user, he is randomly assigned one and a static image, then this image is created with the same name in the / media / folder, if it was not there. Next, just slip the correct path of this picture in / media / into the model

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question