Good day. I have an image of a signature, im using signature: ^5.0.1 for Flutter. I need to save it in to the ImageField. I haven't been able to save it in Django.

this is my code inside flutter

signaturePic(String imgName, SignatureController controller)async{
  String completeUrl = '$rootApi/reports/signature_pic/';
  var uri = Uri.parse(completeUrl);
  var request = http.MultipartRequest("POST", uri);
  Uint8List? signatureFile = await controller.toPngBytes();    
  if (signatureFile != null){
    final multipartFile = http.MultipartFile.fromBytes(imgName, signatureFile);
    request.files.add(multipartFile);
    request.headers["authorization"]='TOKEN ${temp.apiKey}';
  }
}

in Django 4.0 im using djangorestframework==3.13.1

class SignaturePicView(APIView):
    def post(self, request):
        try:
            for title, value in request.data.items():
                items = title.split('__')
                is_return = True if items[5] == 'True' else False

                SignaturePic.objects.update_or_create(
                    user=User.objects.get(id=request.user.id),
                    unique_identifier=title,
                    is_return=is_return,
                    defaults={
                        'image': value,
                    }
                )
            return Response(status=status.HTTP_201_CREATED)

        except ValueError as e:
            print(e)
            return Response(status=status.HTTP_400_BAD_REQUEST, data=e)

this is the model in django

class SignaturePic(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date_created = models.DateTimeField(auto_now_add=True)
    date = models.DateField(auto_now_add=True)
    unique_identifier = models.CharField(max_length=220, null=True, blank=True)
    image = models.ImageField(upload_to='signatures/', null=True, blank=True)
    is_return = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.unique_identifier} -> {self.date}"

when it saves this is what I get.

: �PNG  IHDR�_>���sRGB���sBIT|d�IDATx��y|T�ـ���Lf&��KH�dGd�E(�@+�'"R-����+X~Z�¯h� |,� ���;(a��d�Lf2���1i��,!�I&�}��s����ߓ;�s�9�VKʃ�#Һ[email protected] �)��� ��؏���ٛ����p��� ��� �����>|[email protected]�&s w��98s��:���=Hb��ۊ �������jDRI�W!KN�i���ױgeb;��H,�}����T�A�� ���h�T�~��:��0�X*���p�܊+�\����\? ��Uo�}&�J�*m } ނ3-}W޷�S�1���HRFh�4<�9���)Μ��!������������D�A,Eޤ���D�aH����`ٹ�ҵ�@��nЋ�; Gٶ/"��'�7.�l�;(Zt'~�"�q-~t� N�[t��Ll�� �( ��3ǽ�X���u�K��u�;��E?��[�'����[�0���cx�O����^��ts�k����!d�i$<�u�a�=W�Q��},�pZ�7����h{��Q��v-����!�m�8�--{��|A�z���9��{+�_��- 8-����8f>��Ի�8�-�9��kH��U�q�%����XD�U���וǥ�����&V)���)L���F��6$�̬�4 �S���8�e�BlY��R����2=��"�k^�X^�E��M%�s�lӇ�g�#5V�zA�z���e�Q�ͧ��b���~Xb�����V��M�[xe�I��"�=�ĉb��&,�a��A�1݀���@jhZ��E˧�vE�^$�����A���l��8���un?�>��{YrZ��,|��,��H���\U�8�8Q���̛��[xU�@��h٣ƱM�>�+�[ͻ7y1Rc�j�ĉ�gva��!��;P��~�ԝ�ql׹����G��E��c��'ͻ�(� N�<�����E�.F��~�k�L�y�`���W���YrI/f�l�@�C���M�uv7�C�t^�0fb��ǒ�L0��%O���~�o0<�F��V �S��X�}�u�'H�F\!�ID�1��!�I[��K���ف4���V��>6<�+ĩ�Ґ0�>�[email protected]����9F�6��'�`^;��q-H��YJzXs� NıY�u�2\yP��n��hz�ko�y,�R~��(Zt#y�ʈH�8�$�U�{��ၸ��J�<��[(Y� ���d+����}%�y~� Np�ڊy�;�/�8�-b��\� oR��=d��h�ۃțv�H�"�F�n;���q�+��țt"n�"����=���,��Ǚ���C?⵰��8aºo)e�߮l���A���A, {.g�vL+^@���,�5q�j�H��� A�b����V�|U��F�A�N�[������6��i+���T�������\=���)dI��G�A�k|�r���;,�7#��n�T��U/c?������ӣ$�\�|�_/Dz�C����1}��X�� �s\唬�����D���(���6��:�m}ۡ����hz?)�7�l�?"��A�*�<����xM��U�<4�� �H.������7��!oօ��/���TD�UA�*P��%��@�6����"v�qdo�xu��|�#��3���^Dr�A��`^?����5G��)O�>b�J��5�}��vS��E5�lIq�y�|ʶ�@����:"y�>�O��l�F�E�ح_��qn�y�|ʶ��0 �.G�kBD�x��0}��+ǐh�0��G��NqnA�Ǔ���DV��=�>}� E�n$<�YR��� 7�8? �scZ9G���G7dVĤ)?���U/��:��g�!�)#�+�T๞�i�<�O"VŢ9i�_-�lKh����/a�vD�DA��՛Xv,&�s�hՋ��?B��������W9�"n�����<�A��l˻�myej?�q-I��׈��;�k_'�u KN�8z�.�G$WmШ�1�����*T��4�O3^�%���b?�u��Џx E��a�U�4Jq\����M\"�)I��1��?{��X�-$��"V�0�]@L�gÞ�.ht�x�/Q��,$j#���O�E�a��/7Q��l|���^����8v����K�8^�% �<����v�I���.1�9ٛ*ƚ �h�4��w#h4�8s�Q�����P� if&"Y�Vj����O�������p�&.�ڱ���(�q_���3�&�F�O!i暰u�y�cݿ���ːƷ�0�u��OX�G+ ^G���^^7�I��qX� 8�>������%���s�>��Ǐv�8%���uOh����&��%a��|��]�P쇦����7���+���Z�{>BѲ'�v�mb����>�� ��~$N�,bo4D3 R��-� T��2jnX�~�������/�'�9,q�# N��c-���/�M��8�7�l���cE;�N4(q���(��E�r��� �dr���m Ŋ0=b����%�e�{H M�����̲��M��L��F��t��8s�!KhM���q���K���+����1 B���W�T�7y1]R��ُ��t���/��<M��4��z/���Z,{��L���`Ti��g�A闿�qf7A�ej?���Q>nߍz-N��e�myE�.��]�X���0�{��ۆ�m_4ݞ@7hf�Jmp�[q�������H*C�cƟ-�VO��P��bpR�},Ʊ�i'��H����Y�-�;?F�s�V���S�]�D��q��>0)�e6X�8�O� Ilr�zo��wb�0���([�A���q����Oc�މ��?���F�q�� ��$6����mŘ�ϧ�@�%o�m�g����H��`�w��ZV^�~�CfU�:���Xv�yP��-64�8%k^�[��$&�yU��qre���}�{�m��h���y[8��P���_�[����D�j����ȡl��ؿ_�vN�Ċ捕z#N�iő� ஏޥ�z۷+�ۊ�TF�!vXFm��h�7�7�~�T��퐂�t1�Fߙ�(Z�B�m4��sj<!�S�8�ck��[�2�/�.�ny���/)Y�A�U���È�PuV˕6�^��-Xv}��eOt����s�ٽXw}��rW9��O?q��'a�_��M�/e�h�����mB��,ŕ�-��CQwZoW�oD�8A�[�?H��_8�0�x�%���Hb���<�p�0'pW�Z�����d-z KI�}������EjlJ�S���|�6\�Q-����e�h{>���L+��{Q��#a��H��v]��V��'�4�Ķ��ױ�^B0�#�)�W�l �Q)N�m'�"����-�C�q��Ed�#�{'*�1�{�r�X����2��*�U��f�Wg`?�O�#)�6 �D!Q#��ԶЎ)��I}n4]F �D)Q!�y�[����������W�����JJ�R���� (��[email protected]�k��c0��=��vQ������q��b��/�~�+<׳��S���u�����(��w��A�W޷x��g)���Q�$��uu]Z��Uq�w�<�����H�����k劜"�U� ��u���'?g�><����'���p_9bq��s"*N�m�uv/�ܽ8��E$��q u������w�@_�Ud�i�,-"�m%x�ec����ϑ�$�"�k�2m ��� �� �H"&�eׇ����?F�6��Tt�#oz�-��%��/G��a?�����H,Ɠ� lj�@,!�t;��(�<�,%�㿫��O��q��l�{�[email protected]޴3��O�L��M���y�x�s���C$N�Yb�p�Yeܗ����Wr[V&"�o�y$�x ��V����ƈ���0��Sg5��VKʃ� fپ{�f�#Kl�a�<4���sׅ�}�D 5�����e�����{�\%�s�+��y�<�?ޛ���dI�H�͐�$ �)I�HbPw��I���M�E���L���=)(�>HJ�V���yz'�#kp�� �ڀ��`$�tW���?��8s�a?��-+Y\<g*?���C�����m� (�=�����c��!���8s��/[email protected]��?y1��c�V���*�_/�})��I�bA�j���(S�"��%���@��B$U A����Id�;��"��3��@$��3_��k��$�Cf��1�T���P�gq�Ep���qj+{)���B[+��[��x�)�z9���o���_ɕʶ��ig<�O�L��p��:ԞKq��e�q]8�,)o�y-{Vn8��8E��hz�G��>"�74�,���2��⹑�+���5����Z�6p��q�[email protected]���W|Il "�g)@�K����F�"V� 8ː�$ KNG��Yb�Z���sGq���u��KY�b���І]C3k��F�@�D `�����Qwbie7���*��;ɔh{<�n��ͺ�i�u��s����<�ib��H�,�5��� yE�u]�@!*��T��Zd�-q��A�1�e}Q���Ġ�I�g�IEND�B`�

Any help its highly appreciated. best,


Solution 1: LiquidDeath

You need to send it as a file from frontend. And in backend you can create a form to handle the sent file and do any validation if you wish. Below is a working backend code. Frontend i'm unaware of flutter. so adding react js snippet which you can use as a reference.

Backend :

forms.py

from django import forms

def validate_img_format(input_file):
    # Just an example. here you can add any validation if you have 
    # Or remove validate_img_format from ImageForm and just keep label
    if not input_file.name.endswith(".png"):
        raise forms.ValidationError("Only PNG file is accepted")

class ImageForm(forms.Form):
    imgfile = forms.FileField(label='signature image', validate_img_format)

Views.py

import ImageForm from './forms.py'

class SignaturePicView(APIView):
    def post(self, request):
        try:
            form = ImageForm(request.POST, request.FILES)
            if form.is_valid():
                # All your conditional checks
                sig_instance = SignaturePic(docfile = request.FILES['imgfile'])
                sig_instance.unique_identifier=title
                ...
                sig_instance.save()
            return Response(status=status.HTTP_201_CREATED)

        except ValueError as e:
            print(e)
            return Response(status=status.HTTP_400_BAD_REQUEST, data=e)

Frontend :

const async function FileUpload(e) {

const formData = new FormData();
formData.append("title", 'user entered title');
formData.append("imgfile", e.target.files[0]);
// all other fields
...

await axios({
    method: "post",
    headers: 'headers',
    url: 'url',
    data: formData,
  }).then().catch()

}