5
5
50VAJJ2017-03-15 22:27:52
Django
50VAJJ, 2017-03-15 22:27:52

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?
cb7d083f6e524fc197fcd4eb2e32a737.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ruslan Gilfanov, 2017-03-18
@50VAJJ

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)

I thought to modify this crutch into a wheelchair, namely - so that the name of the model field does not matter. For example, when changing and deleting an object, loop through all fields of the model to apply checks and operations to all FileField and ImageField in the model.
In a good way, it's better to deal with the file fields of models and make your own custom. The task under consideration is of course a trifle, but experience can come in handy.

D
devalone, 2017-03-16
@devalone

Quite, ImageField for this purpose also is created.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question