1

I'm trying to upload a photo using Django Rest Framework and Android Studio, but I'm getting always null when I try to retrieve this image.

Models.py:

class FotoCliente(models.Model):
    image = models.ImageField(upload_to='userpic/%Y/%m/%d/', null = true, max_length = 255)

Serializer.py

class FotoClienteSerializer(serializers.HyperlinkedModelSerializer):
    #id_cliente_cliente = ClienteSerializer()
    class Meta:
        model = FotoCliente
        fields = ('id','image','url')

Views.py

class PhotoList(APIView):

    def get(self, request, format = None):
        photo = FotoCliente.objects.all()
        serializer = FotoClienteSerializer(photo, many = True)
        return Response(data= serializer.data, status = status.HTTP_200_OK)

    def post(self, request, format = None):
        serializer = FotoClienteSerializer(data=request.data, context={'request':request})
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status = status.HTTP_201_CREATED)
        return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)


class PhotoDetail(APIView):

    def get_object(self, pk):
        try:
            return FotoCliente.objects.get(pk=pk)
        except:
            return Http404

    def get(self, request, pk,format=None):
        photo = self.get_object(pk)
        serializer = FotoClienteSerializer(photo,context={'request':request})
        return Response(data=serializer.data, status = status.HTTP_200_OK)

    def post(self, request, format = None):
        serializer = FotoClienteSerializer(data=request.data, files = request.FILES)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status = status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format= None):
        photo = self.get_object(pk)
        photo.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

    def put (self, request, pk, format= None):
        photo = self.get_object(pk)
        serializer = FotoClienteSerializer(photo, data= request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status = status.status.HTTP_400_BAD_REQUEST)

Urls.py

   url(r'^api/fotos/$', views.PhotoList.as_view(), name ='fotocliente-list'),
url(r'api/fotos/(?P<pk>[0-9]+)/$', views.PhotoDetail.as_view(), name = 'fotocliente-detail'),

Result:

{ "id": 7, "image": null, "url": "http://127.0.0.1:8080/api/fotos/7/" }

Android

For uploading the picture I'm using ion koush library for Android.

    Ion.with(editClientActivity.this)
        .load("POST", url) //url de query
        .setHeader("Cache-Control", "No-Cache")//desabilitando cache denovo porque essa parada é bug
        .setHeader("Authorization", getIntent().getExtras().getString("token"))//token de acesso
        .noCache()//desabilitando cache
        //.setLogging("LOG",Log.VERBOSE)//para debug
        .setMultipartParameter("application/json",dadosFoto.toString())
        .setMultipartFile("foto","multipart/form-data",file)
        .asJsonObject() //array recebida
        .setCallback(new FutureCallback<JsonObject>() {
            @Override
            public void onCompleted(Exception e, JsonObject result) {
                // do stuff with the result or error
                Log.v("R Foto: ", "" + result);
                if (e != null) {
                    Toast.makeText(editClientActivity.this, "Erro na Query: " + e, Toast.LENGTH_LONG).show(); //cria balao de texto na view indicada
                    Log.v("Query Error: ", "" + e.getMessage()); //DEBUG
                }
                Toast.makeText(editClientActivity.this, "Cliente de cara nova ;) !", Toast.LENGTH_LONG).show();

                intent = new Intent(getApplicationContext(), clientSummaryActivity.class); // cria nova intent
                intent.putExtra("cpfCliente",date.toDbCpf(cpfCliente.getText().toString()));
                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);
            }
        });

1 Answer 1

1

Ok, this is embarrassing but the problem was at the upload at the android, I needed to change the tag "foto" to "image" at the Ion Koush call.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.