开发者

Django Admin: Show duplicate file in Storage

开发者 https://www.devze.com 2023-04-12 06:48 出处:网络
I have a models.FileField on my Admin-Page in a Model and would like to show an error to the user when he tries to upload an already existing file.

I have a models.FileField on my Admin-Page in a Model and would like to show an error to the user when he tries to upload an already existing file. I already tried overriding get_available_开发者_StackOverflow中文版name() on FileSystemStorage, but if I throw a ValidationError, it doesn't get displayed nicely.

Is there any way to do this (easily)?


Provide a custom form to your 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号