Search code examples
djangodjango-admindjango-uploads

Validate uploaded file format and show error if it's not intact in Django admin page


I have my own text data file format to my Django application.

After uploading one file to Django through admin page, how can I show error to admin uploader if file contents is not in proper format?

Is there common way to handle this situation?


Solution

  • You can use simple form validation, as everywhere in Django.

    Pseudocode below

    admin.py

    class YourModelAdminForm(forms.ModelForm):
        def clean_your_field(self):
            if format_is_not_valid:
                raise forms.ValidationError('Format is not valid')
    
    
    class YourModelAdmin(admin.ModelAdmin):
        form = YourModelAdminForm
    
    
    admin.site.register(YourModel, YourModelAdmin)
    

    or you can create your custom validator and use it on model field

    models.py

    class YourModel(models.Model):
        your_field = models.FileField(validators=[your_validator])