Save image in Django from Android app

417 views Asked by At

I was having problem while saving picture in Django from Android app. I searched and finally solved the problem. I am sharing this so that it might help. Please see the answer below.

1

There are 1 answers

0
Zohab Ali On BEST ANSWER

You will have to implement things according to your own specifications. I am just showing you as a generic example

I have used okHttp in my android app to send data on network (including pic)

Android AsyncTask Code (doInBackground Method)

  RequestBody formBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("filename","filename",RequestBody.create(MediaType.parse("multipart/form-data"), new File(file.getPath())))
                    //.addFormDataPart("other_field", "other_field_value")
                    .build();
            Request request = new Request.Builder()
                    .header("Authorization", "Token " + myToken)
                    .url(myUrl).post(formBody).build();
            Response response = new OkHttpClient().newCall(request).execute();
            return response.body().string();

My view.py Code

def rechargeapplication(request):
    user=#get your own object
    uploadpic = request.FILES['filename']
    user.picture.save("image.jpg",uploadpic)
    user.save()
    return JsonResponse({'result':'Success'})

How I created imageField in models.py

picture=models.ImageField(upload_to="photos" , null=True, blank=True)

if you are using ImageField then you will have to install "Pillow" Also make sure that you specify MEDIA_ROOT & MEDIA_URL in settings.py....I am showing you how I did it

MEDIA_ROOT=os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'

and at the end of urls.py add this(as I was in debug mode that is why my implementation...)

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)