Answer the question
In order to leave comments, you need to log in
Why when I add a picture in django admin to ImageField, then django admin creates a new one and loads it?
Why when I add a picture in django admin to ImageField, then django admin creates a new one and loads it? It also gives it a strange name. This is fine?
Answer the question
In order to leave comments, you need to log in
According to the Django developers, it's ok.
If you want to change this behavior in a quick way:
from django.db import models
from django.db.models.signals import post_delete
def change_image(post_object):
# функция удаления изображений при их замене на новые
post_object = self
try:
pre_object = post_object.__class__.objects.get(id=post_object.id)
if pre_object.image != post_object.image:
pre_object.image.delete(save=False)
except:
pass
def delete_image(sender, **kwargs):
# функция удаления изображений при удалении объектов
try:
object_ = kwargs.get('instance')
storage, path = object_.image.storage, object_.image.path
storage.delete(path)
except:
pass
class MyModel(models.Model):
# наша модель с картинкой
image = models.ImageField(
upload_to='images/',
)
def save(self, *args, **kwargs):
# вызов change_image при сохранении объекта модели
change_image(post_object=self)
super(Category, self).save(*args, **kwargs)
# прикрепляем функцию delete_image к сигналу post_delete от модели MyModel
post_delete.connect(receiver=delete_image, sender=MyModel)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question