Avinash Raj
Avinash Raj

Reputation: 174706

Django failed to consider image

I'm trying to make user to upload an image file and then it should automatically converted into a base64 string.

So my 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 is 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 the error I 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 at /guides/edit/1
Exception Value: cannot identify image file <StringIO.StringIO instance at 0x7f427ab4c6c8>

I also tried to print the query_dict variable,

print query_dict

Output I got is,

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

So, it seems like it gets the uploaded image as string and not as an actual image.

Upvotes: 2

Views: 61

Answers (1)

karthikr
karthikr

Reputation: 99620

A couple of things here:

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

  2. The file is stored in request.FILES, not request.POST

And finally, to actually convert to base64, you can use the module

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

where filehandler is the handler to the file in request.FILES

Also, it looks like you do not have the input type='file' loaded via django form. It might be a better idea to let django form handle the validations so you dont run into security issues, etc.. (you can restrict the input file types, etc.. ),

Upvotes: 3

Related Questions