使用Django Rest Framework上传照片

时间:2017-03-06 19:04:16

标签: android django django-rest-framework ion

我正在尝试使用Django Rest Framework和Android Studio上传照片,但是当我尝试检索此图像时,我总是变空。

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'),

结果:

  

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

的Android

上传图片我正在使用适用于Android的离子koush库。

    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 个答案:

答案 0 :(得分:1)

好吧,这很令人尴尬,但问题是在android上传,我需要在Ion Koush电话中将标签“foto”更改为“image”。