FileExtensionValidator – Validate File Extensions in Django
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.
How to use FileExtensionValidator in Django ?
To demonstrate use of FileExtensionValidator, we will create a file uploader application that will validate ‘pdf’ files at backend.
First create new project.
django-admin startproject fileuploader
Then create new app inside the project
python manage.py startapp main
Then add the app name inside your INSTALLED_APPS inside the settings.py
FileExtensionValidator(allowed_extensions, message, code)
Raises a ValidationError with a code of ‘invalid_extension’ if the extension of value.name (value is a File) isn’t found in allowed_extensions. The extension is compared case-insensitively with allowed_extensions.
User can only upload pdf files in this filefield. Otherwise it will throw exception. Moreover, it is always recommended to add client-side validation for such requirements. This article illustrates how can you validate file uploads at server end.