Вирішено: як зберігати svgs у полі зображення django за допомогою SVGAndImageFormField

Основна проблема полягає в тому, що 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>

Це спеціальне ImageField, яке дозволяє завантажувати зображення або SVG.
Метод to_python бере дані з форми та перетворює їх у FileObject.
Якщо дані вже є FileObject, він просто повертає їх.
Якщо дані мають атрибут читання (тобто якщо це файлоподібний об’єкт), він повертає його.
Якщо дані порожні (”), повертається ” (це тому, що порожні поля завантаження файлу повертають None замість ”, як і інші поля).
Якщо дані не порожні, він намагається відкрити їх як файл (за допомогою режиму «rb»). Якщо це вдається, він повертає об’єкт файлу. Якщо ні, він просто повертає дані самі (це для того, щоб форми, які можуть очікувати ці дані пізніше, не зламалися).

Дозволити завантаження файлів SVG в ImageField через адміністратор Django

Якщо ви хочете дозволити завантажувати файли SVG у ImageField у Django, ви можете зробити це, додавши такий рядок у свій файл settings.py:

IMAGE_FIELD_MAX_FILE_SIZE = 1000000

Як зберігати Svgs у полі зображення Django

Є кілька різних способів зберігати svgs у Django. Найпростішим способом є використання класу ImageField. Цей клас дозволяє вказати URL-адресу або шлях до файлу як значення поля.

Ще один спосіб зберігати svgs у Django — використовувати клас ImageGallery. Цей клас дозволяє вказати URL-адресу або шлях до файлу як значення для поля, і він автоматично створить галерею зображень на основі цього шляху.

Схожі повідомлення:

Залишити коментар