我在模型中的Admin-Page上有一个models.FileField,并希望在用户尝试上传现有文件时向用户显示错误。 我已经尝试在FileSystemStorage上覆盖get_available_name(),但是如果我抛出ValidationError,它就不能很好地显示出来。
有没有办法(轻松)这样做?
答案 0 :(得分:1)
为您的ModelAdmin提供自定义表单:
class FileModel(models.Model):
name = models.CharField(max_length=100)
filefield = models.FileField()
class CustomAdminForm(forms.ModelForm):
# Custom validation: clean_<fieldname>()
def clean_filefield(self):
file = self.cleaned_data.get('filefield', None):
if file:
# Prepare the path where the file will be uploaded. Depends on your project.
# In example:
file_path = os.path.join( upload_directory, file.name )
# Check if the file exists
if os.path.isfile(file_path):
raise ValidationError("File already exists")
return super(CustomAdminForm, self).clean_filefield()
# Set the ModelAdmin to use the custom form
class FileModelAdmin(admin.ModelAdmin):
form = CustomAdminForm