python - Django failed to consider image -


i'm trying make user upload image file , should automatically converted base64 string.

so input form looks like,

<form role="form" method="post" action="{% url 'guideform-edit' object.pk %}"               class="post-form form-horizontal">{% csrf_token %}             <!-- customizing form -->             {{ form|crispy }}             <!-- end of customization -->             <div style="position:relative;">                 <a class='btn btn-primary' href='javascript:;'>                     choose file...                     <input type="file"                            style='position:absolute;z-index:2;top:0;left:0;bottom:0;right:0;filter: alpha(opacity=0);-ms-filter:"progid:dximagetransform.microsoft.alpha(opacity=0)";opacity:0;background-color:transparent;color:transparent;'                            name="file_source" size="40" onchange='$("#upload-file-info").html($(this).val());'>                 </a>                 &nbsp;                 <span class='label label-info' id="upload-file-info"></span>             </div>             <button type="submit" class="save btn btn-default btn-primary center-block">update</button>          </form> 

corresponding view class like,

class guideformupdateview(updateview):     model = guide     fields = ['name', 'image', 'point_of_interest']     template_name_suffix = '_update_form'      def post(self, request, *args, **kwargs):         query_dict = request.post         img = image.open(stringio(query_dict['file_source']))         print img 

and error got is,

file "/home/avinash/django_projects/guide/src/guide/views.py" in post   166.         img = image.open(stringio(query_dict['file_source']))  file "/home/avinash/.virtualenvs/guide/local/lib/python2.7/site-packages/pil/image.py" in open   2295.                   % (filename if filename else fp))  exception type: ioerror @ /guides/edit/1 exception value: cannot identify image file <stringio.stringio instance @ 0x7f427ab4c6c8> 

i tried print query_dict variable,

print query_dict 

output got is,

{u'csrfmiddlewaretoken': u'xxxxxxxxxxx', u'name': u'pieza tower', u'file_source': u'20150706_104718.jpg'} 

so, seems gets uploaded image string , not actual image.

a couple of things here:

  1. you need specify enctype="multipart/form-data" form attribute upload files

  2. the file stored in request.files, not request.post

and finally, convert base64, can use module

encoded_img = base64.b64encode(filehandler.read()) 

where filehandler handler file in request.files

also, looks not have input type='file' loaded via django form. might better idea let django form handle validations dont run security issues, etc.. (you can restrict input file types, etc.. ),


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -