解決済み: SVGAndImageFormField を使用して django 画像フィールドに svgs を保存する方法

主な問題は、デフォルトの Django 画像フィールドで svgs がサポートされていないことです。 svg を保存するには、カスタム フィールド クラスを使用する必要があります。

?

I am trying to store svgs in django image field  with SVGAndImageFormField. I have tried this:
<code>class SVGAndImageFormField(forms.ImageField):

    def to_python(self, data):
        f = super().to_python(data)
        if isinstance(f, FileObject):
            return f

        if hasattr(data, 'read'):
            return data

        if not data: # empty file upload field returns None instead of '' like the rest of the fields. get around it.
            return ''

        try: # handle when it's just a path instead of a file object. (IE when you are updating the form and not uploading anything new)
            return open(data, 'rb')  # do something with the path here. probably save it off.
        except FileNotFoundError: # catch missing files and just return them as is so we don't break forms that might be expecting them later on down the line somewhere. (like when you are updating the form and not uploading anything new)  This will cause validation errors if they are invalid paths though so be aware of that!   You could also handle this by subclassing ImageField and overriding from_db_value() but I'm not sure what you would want to do there so I'll leave that as an exercise for the reader! 😉   https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.fields.files._ImageFieldFile  https://docs.djangoproject.com/en/2.0/ref/models/fields/#field-types  https://docs-archive-old-1x1x1x1x1x4x3xx11111l1111111111111l22222222d11111111l3ooooooooxxxxxxxxxxxxxxxxxxxxxxxxxxxxdddddddddddddxxxxxxxeeeeeeeeeeeeeeexxxxxxxxxxxxxxxxfoooooooooooooooxxxxxxxxxxxxxxxgpppppppppppppppqrrrrrrrrrrrrrrrsssssssssssssstttttttttuuuuuuuuvvvvvvvvwwwwwwwwyyyyyyzzzzzzz{{{{{{|}}}}}}}~€€€€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’"•–—˜™š›œžŸ ¡¢£¤¥¦©«®°²¶·»½ÀÂÄÇÉÊËÎÏÔ×Ûßàâäçéêëîïôûüˆˇˉ–––––—―™š›œ–—˜™š›œ"•–—˜™š•–—˜™š•–—˜™š•–—˜™š•–—˜™š• – — – — – — – — – — – — – — – — – — ¢£¤ ¥ ¦ © « ® ° ² ¶ · » ½ À â Ä ç é êëîïôûüˆˇˉ––––––—" • - - - - - " • - - - " • -- -- -- -- " • -- -- " • --- --- --- --- " • --- --- " • ---- ---- ---- ---- ---- ---- ---- ---- ----- ------ -------- --------- ---------- ------------------- ------------------------------------------------------------ ----------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------------------------</code>

これは、画像または SVG をアップロードできるカスタム ImageField です。
to_python メソッドはフォームからデータを取得し、それを FileObject に変換します。
データが既に FileObject である場合は、それを返すだけです。
データに読み取り属性がある場合 (つまり、ファイルのようなオブジェクトの場合)、それを返します。
データが空 (") の場合、" が返されます (これは、他のフィールドと同様に、空のファイル アップロード フィールドが " ではなく None を返すためです)。
データが空でない場合は、('rb' モードを使用して) ファイルとして開こうとします。 これが成功すると、ファイル オブジェクトが返されます。 そうでない場合は、データ自体を返すだけです (これは、後でこのデータを予期するフォームが壊れないようにするためです)。

Django admin 経由で SVG ファイルを ImageField にアップロードできるようにする

SVG ファイルを Django の ImageField にアップロードできるようにするには、settings.py ファイルに次の行を追加します。

IMAGE_FIELD_MAX_FILE_SIZE = 1000000

Django 画像フィールドに Svg を保存する方法

Django に svg を保存する方法はいくつかあります。 最も簡単な方法は、ImageField クラスを使用することです。 このクラスを使用すると、フィールドの値として URL またはファイルパスを指定できます。

Django に svg を保存する別の方法は、ImageGallery クラスを使用することです。 このクラスを使用すると、フィールドの値として URL またはファイルパスを指定でき、そのパスに基づいて画像のギャラリーが自動的に生成されます。

関連記事:

コメント