Solucionat: com emmagatzemar svgs al camp d'imatge de Django amb SVGAndImageFormField

El problema principal és que els svgs no són compatibles amb el camp d'imatge de Django predeterminat. Heu d'utilitzar una classe de camp personalitzada per emmagatzemar 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>

Aquest és un ImageField personalitzat que us permet pujar una imatge o un SVG.
El mètode to_python pren les dades del formulari i les converteix en un FileObject.
Si les dades ja són un FileObject, només les retorna.
Si les dades tenen un atribut de lectura (és a dir, si és un objecte semblant a un fitxer), el retorna.
Si les dades estan buides (""), es retorna " (això és perquè els camps de càrrega de fitxers buits retornen Cap en lloc de "", com altres camps).
Si les dades no estan buides, prova d'obrir-les com a fitxer (utilitzant el mode 'rb'). Si això té èxit, retorna l'objecte fitxer. Si no, només retorna les dades en si (això és perquè els formularis que podrien estar esperant aquestes dades més endavant no es trenquin).

Permet que es carreguin fitxers SVG a ImageField mitjançant l'administrador de Django

Si voleu permetre que els fitxers SVG es pengin a un ImageField a Django, podeu fer-ho afegint la línia següent al vostre fitxer settings.py:

IMAGE_FIELD_MAX_FILE_SIZE = 1000000

Com emmagatzemar Svgs al camp d'imatge de Django

Hi ha algunes maneres diferents d'emmagatzemar svgs a Django. La manera més senzilla és utilitzar la classe ImageField. Aquesta classe us permet especificar un URL o una ruta de fitxer com a valor per al camp.

Una altra manera d'emmagatzemar svgs a Django és utilitzar la classe ImageGallery. Aquesta classe us permet especificar un URL o un camí de fitxer com a valor per al camp, i generarà automàticament una galeria d'imatges en funció d'aquest camí.

Articles Relacionats:

Deixa el teu comentari