Сообщение не отображается в панели администратора django - PullRequest
0 голосов
/ 04 февраля 2019

Моя цель - заблокировать загрузку изображения, которое уже есть в базе данных - форма для этого в админке.Для этого я использовал метод clean() в моделях, но не могу отобразить сообщение в панели администратора о том, что такая фотография уже загружена.

Я использую здесь метод очистки в моделях.ру.Предыдущий Я пытался с сообщениями, но безуспешно, потому что для этого мне нужно request.

В терминале эта команда выполняется print('Test'), но не эта raise ValidationError('This image already exists.')

модель из django-filer:

class BaseImage(File):
    SIDEBAR_IMAGE_WIDTH = 210
    DEFAULT_THUMBNAILS = {
        'admin_clipboard_icon': {'size': (32, 32), 'crop': True,
                                 'upscale': True},
        'admin_sidebar_preview': {'size': (SIDEBAR_IMAGE_WIDTH, 0), 'upscale': True},
        'admin_directory_listing_icon': {'size': (48, 48),
                                         'crop': True, 'upscale': True},
        'admin_tiny_icon': {'size': (32, 32), 'crop': True, 'upscale': True},
    }
    file_type = 'Image'
    _icon = "image"

    _height = models.IntegerField(null=True, blank=True)
    _width = models.IntegerField(null=True, blank=True)

    default_alt_text = models.CharField(_('default alt text'), max_length=255, blank=True, null=True)
    default_caption = models.CharField(_('default caption'), max_length=255, blank=True, null=True)

    subject_location = models.CharField(_('subject location'), max_length=64, blank=True,
                                        default='')
    file_ptr = models.OneToOneField(
        to='filer.File', parent_link=True,
        related_name='%(app_label)s_%(class)s_file',
        on_delete=models.CASCADE,
    )

    @classmethod
    def matches_file_type(cls, iname, ifile, request):
        # This was originally in admin/clipboardadmin.py  it was inside of a try
        # except, I have moved it here outside of a try except because I can't
        # figure out just what kind of exception this could generate... all it was
        # doing for me was obscuring errors...
        # --Dave Butler <croepha@gmail.com>
        iext = os.path.splitext(iname)[1].lower()
        return iext in ['.jpg', '.jpeg', '.png', '.gif']

    def file_data_changed(self, post_init=False):
        attrs_updated = super(BaseImage, self).file_data_changed(post_init=post_init)
        if attrs_updated:
            try:
                try:
                    imgfile = self.file.file
                except ValueError:
                    imgfile = self.file_ptr.file
                imgfile.seek(0)
                self._width, self._height = PILImage.open(imgfile).size
                imgfile.seek(0)
            except Exception:
                if post_init is False:
                    # in case `imgfile` could not be found, unset dimensions
                    # but only if not initialized by loading a fixture file
                    self._width, self._height = None, None
        return attrs_updated

    def save(self, *args, **kwargs):
        self.has_all_mandatory_data = self._check_validity()
        super(BaseImage, self).save(*args, **kwargs)

модель в моем приложении:

class ImageModel(BaseImage):
    text = models.TextField(null=True, blank=True)

    def clean(self):
        if ImageModel.objects.filter(original_filename=self.file).exists():
            print('Test')
            raise ValidationError('This image already exists.')
...