learner learner - 9 days ago 7
Python Question

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?

Answer

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")
Comments