To only accept a certain file type in FileField with Python Django, we can add a validator function to check the file extension.
For instance, we write
def validate_file_extension(value):
import os
from django.core.exceptions import ValidationError
ext = os.path.splitext(value.name)[1] # [0] returns path+filename
valid_extensions = ['.pdf', '.doc', '.docx', '.jpg', '.png', '.xlsx', '.xls']
if not ext.lower() in valid_extensions:
raise ValidationError('Unsupported file extension.')
class Document(models.Model):
file = models.FileField(upload_to="documents/%Y/%m/%d", validators=[validate_file_extension])
to define the validate_file_extension function to check the file extension of the selected file’s path.
We get the extension from the path with os.path.splitext(value.name)[1].
And then we check if the ext extension is in valid_extensions.
If it’s not, then we raise a ValidationError.
Next, in our Document model, we add a FileField with the validators arguments set to an array with the validate_file_extension as the value.
Then validate_file_extension when a file is uploaded.
One reply on “How to only accept a certain file type in FileField with Python Django?”
Hi I love this example but the example was slightly wrong for me.
I seemed to get it working with the follwing code:
def validate_agreement(value):
ext = os.path.splitext(value.name)
valid_extensions = [‘.pdf’, ‘.PDF’]
if not ext[1].lower() in valid_extensions:
raise ValidationError(‘Unsupported file extension.’)