2011-10-12 79 views
2

我在模型的管理頁面中有一個models.FileField,並且想要在用戶嘗試上載已存在的文件時向用戶顯示錯誤。 我已經嘗試覆蓋FileSystemStorage上的get_available_name(),但如果我拋出一個ValidationError,它不會很好地顯示。Django管理員:在存儲器中顯示重複文件

有沒有辦法做到這一點(輕鬆)?

回答

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