learner
learner

Reputation: 4808

Upload an image to twitter via tweepy from django form

I want to upload an image to twitter taken by a django form:

<div class="panel panel-danger">
                <div class="panel-heading">
                    <h3 class="panel-title">Panel title</h3>
                </div>
                <div class="panel-body">
                    <form action="" method="POST" role="form" enctype="multipart/form-data">
                        {% csrf_token %}
                        <legend>Upload a file: </legend>

                        <div class="form-group">
                            <input type="file" name="file" class="form-control" id="">
                        </div>



                        <button type="submit" class="btn btn-primary">Submit</button>
                    </form>
                </div>
            </div>

The image I got is:

if fileForm.is_valid():
            print "file is uploaded."
            paramFile = open(request.FILES['file'],'rb')
            # paramFile = request.FILES['file'].read()
            api.update_with_media(paramFile,status="Hello first image")

The error I got is:

coercing to Unicode: need string or buffer, InMemoryUploadedFile found

How can I upload this to twitter?

Upvotes: 1

Views: 318

Answers (2)

neverwalkaloner
neverwalkaloner

Reputation: 47354

Method update_with_media() has only one positional argument which takes filename. So you can specify filename something like this:

api.update_with_media(request.FILES['file'].name,
                      status="Hello first image")

Also you should pass file using keyword argument 'file':

api.update_with_media(request.FILES['file'].name,
                      file=request.FILES['file'], 
                      status="Hello first image")

Upvotes: 1

valignatev
valignatev

Reputation: 6316

As per docs, you have to pass both file parameter which will be opened internally and filename parameter which is needed to determine MIME type and will be used to as form field in post data. So just pass them explicitly as keyword arguments and you should be fine.

Upvotes: 1

Related Questions