[Answered ]-Django model clean function validation error problem

1👍

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

👤Ben

Leave a comment