我的目标是阻止上传数据库中已经存在的图像-表单位于admin中。为此,我在模型中使用了clean()
方法,但无法在管理面板中显示有关已上传此类照片的消息。
我在models.py中使用此处的干净方法。上一个,我尝试使用消息,但没有成功,因为我需要request
才能做到。
在终端中,此命令print('Test')
被执行,但不是raise ValidationError('This image already exists.')
这个命令
模型:
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.')