pythondjangodjango-admindjango-file-upload

Django model clean function validation error problem


I have a Django model with custom clean function as below:

class License(models.Model):
    # fields of the model
    def clean(self):
        if condition1:
            raise ValidationError('Please correct the error!')

The problem is that, my admin user uploads some file as needed by FileField of License Model, but when I raise the ValidationError file fields are emptied and user is forced to upload the files again. Is it possible to raise the error, but keep the files?

This doesn't happen for other fields such as CharField.


Solution

  • You can't pre-populate a FileField in a form (<input type="file">), as it's a huge security risk and is automatically blocked by browsers.

    Alternatively, You could save every uploaded file before validating the form and raising other fields' ValidationErrors. When you re-render the form with errors, let the user know you've already received the file, such as in a form field add_error (https://docs.djangoproject.com/en/4.2/ref/forms/validation/)

    For example:

    class LicenseAdmin(admin.ModelAdmin):
        form = LicenseAdminForm
    
    
    class LicenseAdminForm(forms.ModelForm):
    
        def clean(self):
            cleaned_data = super().clean()
            if self.errors:
                uploaded_file = cleaned_data["upload_file"]
                save_license_upload(uploaded_file)  # Save the file
    
                self.add_error(
                    "upload_file", f"Uploaded file:{uploaded_file} already saved!"
                )  # Let the user know you already have the file
    
    

    See also: https://docs.djangoproject.com/en/4.2/ref/contrib/admin/#admin-custom-validation