0

I only want .xlsm files to be uploadable to the form.

This my field in models.py

...
pdf = models.FileField( upload_to=customer_directory_path, null=True, blank=True)
...

How can I do that?

edche
  • 636
  • 6
  • 33

3 Answers3

0

Django Upload Validator is one option for handling that: https://pypi.org/project/django-upload-validator/

Ed Kohler
  • 534
  • 3
  • 9
  • I think you don't need an external python package for this, since you could just take the file extension and then validate it is an xlsm file. Although maybe I am wrong. – John Doe Aug 09 '21 at 14:32
  • 1
    There is indeed more than one way to solve this problem. We don't need to scold people for providing different answers or for asking questions. – Ed Kohler Aug 09 '21 at 14:36
0

You can use regular expressions to check the extension of the file before saving the model using the clean() method like this:

from django.core.exceptions import ValidationError # for returnig errors
from django.db import models
from django.utils.translation import gettext_lazy as _
import re # import regex python module

class PdfModel(models.Model):
    pdf = models.FileField( upload_to=customer_directory_path, null=True, blank=True)

    def clean(self):
        pattern = re.compile('.*\.xlsm$')
        
        if not pattern.search(self.pdf):
            raise ValidationError(_('Only .xlsm files are accepted'))

more information about clean() method here

Fady's Cube
  • 158
  • 1
  • 7
0

According to the Django docs, you just have to do this:

from django.core.validators import FileExtensionValidator
    
class YourModel(models.Model):
    pdf = models.FileField(upload_to=customer_directory_path, null=True, blank=True, validators=[FileExtensionValidator(allowed_extensions=['xlsm'])])

This just checks the file ending and validates it ends in .xlsm, and if it doesn't it raises a ValidationError.

There are many ways of doing this, here are some resources I found on stack overflow:

Next time, try searching for answers to your question before going on stackoverflow. :)

John Doe
  • 512
  • 1
  • 5
  • 17