El principal problema es que los svgs no son compatibles con el campo de imagen predeterminado de Django. Debe usar una clase de campo personalizada para almacenar 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>
Este es un ImageField personalizado que le permite cargar una imagen o un SVG.
El método to_python toma los datos del formulario y los convierte en un FileObject.
Si los datos ya son un FileObject, simplemente los devuelve.
Si los datos tienen un atributo de lectura (es decir, si es un objeto similar a un archivo), lo devuelve.
Si los datos están vacíos (”), devuelve ” (esto se debe a que los campos de carga de archivos vacíos devuelven Ninguno en lugar de ”, como otros campos).
Si los datos no están vacíos, intenta abrirlos como un archivo (usando el modo 'rb'). Si esto tiene éxito, devuelve el objeto de archivo. Si no, simplemente devuelve los datos en sí (esto es para que los formularios que podrían estar esperando estos datos más adelante no se rompan).
Permitir que los archivos SVG se carguen en ImageField a través del administrador de Django
Si desea permitir que los archivos SVG se carguen en un ImageField en Django, puede hacerlo agregando la siguiente línea a su archivo settings.py:
IMAGE_FIELD_MAX_FILE_SIZE = 1000000
Cómo almacenar svgs en el campo de imagen de Django
Hay algunas formas diferentes de almacenar svgs en Django. La forma más sencilla es utilizar la clase ImageField. Esta clase le permite especificar una URL o ruta de archivo como valor para el campo.
Otra forma de almacenar svgs en Django es usar la clase ImageGallery. Esta clase le permite especificar una URL o ruta de archivo como valor para el campo y generará automáticamente una galería de imágenes basada en esa ruta.