해결됨: SVGAndImageFormField를 사용하여 django 이미지 필드에 svgs를 저장하는 방법

주요 문제는 svgs가 기본 Django 이미지 필드에서 지원되지 않는다는 것입니다. svgs를 저장하려면 사용자 정의 필드 클래스를 사용해야 합니다.

?

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' 모드 사용). 성공하면 파일 객체를 반환합니다. 그렇지 않은 경우 데이터 자체를 반환합니다(이는 나중에 이 데이터를 예상할 수 있는 양식이 중단되지 않도록 하기 위한 것입니다).

SVG 파일이 Django 관리자를 통해 ImageField에 업로드되도록 허용

Django의 ImageField에 SVG 파일을 업로드하려면 settings.py 파일에 다음 행을 추가하면 됩니다.

IMAGE_FIELD_MAX_FILE_SIZE = 1000000

Django 이미지 필드에 SVG를 저장하는 방법

Django에 svgs를 저장하는 몇 가지 방법이 있습니다. 가장 간단한 방법은 ImageField 클래스를 사용하는 것입니다. 이 클래스를 사용하면 URL 또는 파일 경로를 필드 값으로 지정할 수 있습니다.

Django에 svgs를 저장하는 또 다른 방법은 ImageGallery 클래스를 사용하는 것입니다. 이 클래스를 사용하면 URL 또는 파일 경로를 필드 값으로 지정할 수 있으며 해당 경로를 기반으로 이미지 갤러리를 자동으로 생성합니다.

관련 게시물:

코멘트 남김