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.
Asked
Active
Viewed 1,242 times
0
-
Thank you for accepting my answer! Please let me know me if there is anything else I can help you with. – georgekrax Apr 21 '20 at 19:20
-
No thanks if worked there are some other issues i am facing but i think its part of the game :) so i am trying . – Muneeb Mughal Apr 23 '20 at 09:22
-
Great start for you! – georgekrax Apr 23 '20 at 11:21
1 Answers
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