本文介绍了允许通过Django管理员将SVG文件上传到ImageField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在切换到SVG图片,以代表我的电子商务平台上的类别.我以前在Category模型中使用models.ImageField来存储图像,但是forms.ImageField验证不能处理基于矢量的图像(因此拒绝它).

I'm switching to SVG images to represent categories on my e-commerce platform. I was using models.ImageField in the Category model to store the images before, but the forms.ImageField validation is not capable of handling a vector-based image (and therefore rejects it).

我不需要对有害文件进行全面验证,因为所有上传都将通过Django Admin完成.看来我必须在模型中切换到models.FileField,但是我确实要警告不要上传无效的图像.

I don't require thorough validation against harmful files, since all uploads will be done via the Django Admin. It looks like I'll have to switch to a models.FileField in my model, but I do want warnings against uploading invalid images.

尼克·赫列斯托夫(Nick Khlestov)写了 SVGAndImageFormField (在本文中找到源,我没有足够的声誉来发布更多链接),通过 django-rest-framework的ImageField .如何在Django的ImageField(而不是DRF)上使用此解决方案?

Nick Khlestov wrote a SVGAndImageFormField (find source within the article, I don't have enough reputation to post more links) over django-rest-framework's ImageField. How do I use this solution over Django's ImageField (and not the DRF one)?

推荐答案

事实证明, SVGAndImageFormField 与DRF的ImageField没有依赖关系,它仅添加了由django.forms.ImageField完成的验证.

It turns out that SVGAndImageFormField has no dependencies on DRF's ImageField, it only adds to the validation done by django.forms.ImageField.

因此,为了在Django Admin中接受SVG,我如下指定了替代:

So to accept SVGs in the Django Admin I specified an override as follows:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        exclude = []
        field_classes = {
            'image_field': SVGAndImageFormField,
        }

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm

admin.site.register(MyModel, MyModelAdmin)

现在它可以接受所有以前的图像格式以及SVG.

It now accepts all previous image formats along with SVG.

刚刚发现,即使不从models.ImageField切换到models.FileField,此方法也有效. models.ImageFieldheightwidth属性仍然适用于光栅图像类型,对于SVG它将设置为None.

Just found out that this works even if you don't switch from models.ImageField to models.FileField. The height and width attributes of models.ImageField will still work for raster image types, and will be set to None for SVG.

这篇关于允许通过Django管理员将SVG文件上传到ImageField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 18:11