如何修改django ImageField以接受svg文件

n53p2ov0  于 2023-04-22  发布在  Go
关注(0)|答案(1)|浏览(137)

我使用django rest框架(版本3.12.2)作为后端,React/Next js作为前端。
我的目标很简单,我想上传图片到photo_main字段。
不幸的是,我收到一个错误消息时,试图上传svg图像(png,jpg和jpeg的工作刚刚好)

错误消息

{"photo_main":["Upload a valid image. The file you uploaded was either not an image or a corrupted image."]}

型号

class Recipe(models.Model):
    id = models.UUIDField( 
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
    )
    author = models.ForeignKey(get_user_model() , on_delete=models.CASCADE, null=True, related_name='author') 
    photo_main = models.ImageField(upload_to='media/', blank=True)
    title = models.CharField(max_length=150)
    description = models.TextField(blank=True)

先谢了

g2ieeal7

g2ieeal71#

所以在浏览论坛后,我遇到了解决方案:

validators.py

import os
from django.core.exceptions import ValidationError

def validate_file_extension(value):
    ext = os.path.splitext(value.name)[1]  # [0] returns path+filename
    valid_extensions = ['.jpg', '.jpeg', '.png', '.svg']
    if not ext.lower() in valid_extensions:
        raise ValidationError('Unsupported file extension.')

models.py

from app_name.valiators import validate_file_extension

image = models.ImageField('Image', upload_to=image_upload_path, validators=[validate_file_extension])

相关问题