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?
Django Upload Validator is one option for handling that: https://pypi.org/project/django-upload-validator/
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
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. :)