Risolto: come memorizzare gli svg nel campo immagine django con SVGAndImageFormField

Ultimo aggiornamento: 09/11/2023

Il problema principale è che gli svg non sono supportati dal campo immagine predefinito di Django. È necessario utilizzare una classe di campo personalizzata per archiviare gli 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>

Questo è un ImageField personalizzato che ti consente di caricare un'immagine o un SVG.
Il metodo to_python prende i dati dal form e li converte in un FileObject.
Se i dati sono già un FileObject, lo restituisce semplicemente.
Se il dato ha un attributo read (cioè se è un oggetto simile a un file), lo restituisce.
Se i dati sono vuoti (”), restituisce ” (questo perché i campi di caricamento file vuoti restituiscono Nessuno invece di ”, come altri campi).
Se i dati non sono vuoti, prova ad aprirli come file (usando la modalità 'rb'). Se ciò riesce, restituisce l'oggetto file. In caso contrario, restituisce solo i dati stessi (questo è così che i moduli che potrebbero aspettarsi questi dati in seguito non si interrompono).

Consenti il ​​caricamento dei file SVG su ImageField tramite l'amministratore di Django

Se vuoi consentire il caricamento dei file SVG in un ImageField in Django, puoi farlo aggiungendo la seguente riga al tuo file settings.py:

IMAGE_FIELD_MAX_FILE_SIZE = 1000000

Come archiviare Svgs nel campo immagine Django

Esistono diversi modi per archiviare gli svg in Django. Il modo più semplice è utilizzare la classe ImageField. Questa classe consente di specificare un URL o un percorso file come valore per il campo.

Un altro modo per archiviare gli svg in Django è usare la classe ImageGallery. Questa classe ti consente di specificare un URL o un percorso file come valore per il campo e genererà automaticamente una galleria di immagini basata su quel percorso.

Related posts: