0

I want to upload the svg images from admin models, how I can enable it? or allowed specific extensions like other .webp ,.docx and pdf etc.

1 Answers1

1

Well, whenever you want your users to upload an image, then you should use the models.ImageField() in the corresponding model. For other types of media, you can use the models.FileField(), and you can create a custom validator to check if you want a .docx or .pdf, etc.

Create a validators.py file inside your app folder, and add the function:

from django.core.exceptions import ValidationError
import os

def validate_file_extension(value):
    ext = os.path.splitext(value.name)[1]  # [0] returns path & filename
    valid_extensions = ['.pdf', '.doc', '.docx', '.jpg', '.png', '.xlsx', '.xls'] # populate with the extensions that you allow / want
    if not ext.lower() in valid_extensions:
        raise ValidationError('Unsupported file extension.')

Then in your models.py:

from .validators import validate_file_extension

And finally, use the validator for your model field:

class Document(models.Model):
    file = models.FileField(upload_to="documents/", validators=[validate_file_extension])

See also:

georgekrax
  • 1,065
  • 1
  • 11
  • 22