允许通过 Django admin 将 SVG 文件上传到 ImageField [英] Allow SVG files to be uploaded to ImageField via Django admin

查看:21
本文介绍了允许通过 Django admin 将 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,我 将模型的 ImageField 更改为 FileField 指定了如下覆盖:

So to accept SVGs in the Django Admin I changed the model's ImageField to a FileField and 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 属性仍然适用于光栅图像类型,并将设置为 None 用于 SVG.

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 admin 将 SVG 文件上传到 ImageField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆