I am trying to add a file extension validator in the Filefield of my model. But when I am adding a different extension file through my serializer it's adding the extensions I didn't put in my validators.py
Here is the code so far
# validators.py
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 = ["png", "jpg", "jpeg", # for images
"pdf", "doc", "docx", "txt", # for documents
"mp3", "aac", "m4a", "mp4", "ogg"] # for audios
if not ext.lower() in valid_extensions:
raise ValidationError('Unsupported file extension.')
#models.py
class QuestionFile(models.Model):
question = models.ForeignKey(
Question, on_delete=models.CASCADE, related_name='files', null=True, blank=True)
FILE_TYPE = (
('NONE', 'NONE'),
('IMAGE', 'IMAGE'),
('DOCUMENT', 'DOCUMENT'),
('AUDIO', 'AUDIO'),
)
file_type = models.CharField(
choices=FILE_TYPE, max_length=50, null=True, blank=True)
file = models.FileField(
'files', upload_to=path_and_rename, max_length=500, null=True, blank=True, validators=[validate_file_extension])
def __str__(self):
return str(self.question)
and here is the output in my serializer for this model
"id": ..,
"file": "<filepath>/c-f479b7453519484b827dbc0051bd9a64.html",
"file_type": ..,
"question": ..
As it's visible, though .html extension is not added in the validators.py still it's uploading. Did I make any mistakes in my code? I am unable to figure out that. If any other information is needed let me know, please.
Thanks