0

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

Anny
  • 163
  • 1
  • 9

1 Answers1

0

Simple error, Your list should be like this:

valid_extensions = ['.jpg', '.png', '.mp3'] 

and when you use:

import os
text = "/path/to/file/file.jpg"

name = os.path.splitext(text)

then

if name[1].lower() in valid_extensions:
  pass
Rajat Jog
  • 197
  • 1
  • 10
  • ```os.path.splitext(text)``` gives ```('file-path', '.extensions')``` – Rajat Jog Mar 14 '22 at 04:24
  • do I have to mention the folder path ? – Anny Mar 14 '22 at 04:58
  • No it's just file path – Rajat Jog Mar 14 '22 at 05:03
  • thanks but 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.') – Anny Mar 14 '22 at 05:04
  • after adding . bfr the the extensions still not working – Anny Mar 14 '22 at 05:05