Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I upload svg file to a django app?

I tried to upload an .svg by the admin site to SQLite (django's default db) and I got the following error:

Upload a valid image. The file you uploaded was either not an image or a corrupted image.

I can upload .jpg files and it works properly.

class News(models.Model):
    news_id         = models.AutoField(primary_key=True, editable=False)
    news_title      = models.CharField(max_length=150)
    news_date       = models.DateTimeField(auto_now_add=True, editable=False)
    news_body       = models.TextField(max_length=1500)
    news_img        = models.ImageField(upload_to="pictures/%Y/%m/")
    news_author     = models.ManyToManyField(Author)

    class Meta:
        ordering: ['news_id']

    def __str__(self):
        return '%s %s %s'%(self.news_id, self.news_title, self.news_date)
like image 549
VicenteC Avatar asked Sep 18 '19 15:09

VicenteC


People also ask

Does Django support SVG?

django-filer This means that SVG images can be uploaded just like PNGs or JPEGs and used by existing templatetags such as thumbnail .

What program works with SVG files?

Google Chrome, Firefox, IE, Opera, and every popular browser has the capacity to render SVG images. SVG files are also supported in basic text editors and high-end Graphics editors like CorelDRAW.


1 Answers

You sould change your Django ImageField to FileField and add .svg extension to field validators.

File Extension Validator

The result model file field is something like this:

from django.core.validators import FileExtensionValidator

news_img = models.FileField(upload_to="pictures/%Y/%m/", validators=[FileExtensionValidator(['pdf', 'doc', 'svg'])])
like image 124
Alberto Sanmartin Martinez Avatar answered Oct 17 '22 01:10

Alberto Sanmartin Martinez