Subject, in the admin Django.

class FooModel(models.Model): image = models.FileField( upload_to="foo/path/images", validators=[здесь_попытка_в_валидатор] ) 

I wanted to use something like os.path.exists in the custom validator, but, firstly, I didn’t find how to distinguish the freshly stored file from the one already saved in the model, and secondly, I didn’t find the way to which the file ( .path in the validator it ignores the registered upload_to and gives to the crazy about MEDIA_ROOT).

    1 answer 1

    With validators fail. In the validator you cannot get the old value of the object field.
    You need to redefine the form, and in it already, in the method clean_image do checks. I think the old value can be obtained through self.instance.image .
    Something like this:

     class FooAdminForm(forms.models.ModelForm): def clean_image(self): old_fullname = os.path.join(settings.MEDIA_ROOT, self.instance.image.name) if os.path.exists(old_fullname): raise ValidationError(u'...') return self.cleaned_data.get("image", False) class FooOptions(admin.ModelAdmin): # ... form = FooAdminForm