Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework image upload

I have model Product:

def productFile(instance, filename):     return '/'.join( ['products', str(instance.id), filename] )  class Product(models.Model):     ...      image = models.ImageField(         upload_to=productFile,         max_length=254, blank=True, null=True     )     ... 

Then I have serializer:

class ProductSerializer(serializers.ModelSerializer):     class Meta:         model = Product         fields = (             ...             'image',             ...         ) 

And then I have views:

class ProductViewSet(BaseViewSet, viewsets.ModelViewSet):     queryset = Product.objects.all()     serializer_class = ProductSerializer 

How I can upload image with Postman? What is the best practices to upload image to model? Thank you.

like image 399
Danila Kulakov Avatar asked Aug 08 '17 09:08

Danila Kulakov


People also ask

How do I upload to Django REST framework?

So you have two choices: let ModelViewSet and ModelSerializer handle the job and send the request using content-type=multipart/form-data; set the field in ModelSerializer as Base64ImageField (or) Base64FileField and tell your client to encode the file to Base64 and set the content-type=application/json.

What is HyperlinkedModelSerializer in Django?

HyperlinkedModelSerializer is a layer of abstraction over the default serializer that allows to quickly create a serializer for a model in Django. Django REST Framework is a wrapper over default Django Framework, basically used to create APIs of various kinds.


1 Answers

you can create separate endpoint for uploading images, it would be like that:

class ProductViewSet(BaseViewSet, viewsets.ModelViewSet):     queryset = Product.objects.all()     serializer_class = ProductSerializer      @detail_route(methods=['post'])     def upload_docs(request):         try:             file = request.data['file']         except KeyError:             raise ParseError('Request has no resource file attached')         product = Product.objects.create(image=file, ....) 

you can go around that solution

-- update: this's how to upload from postman enter image description here

like image 188
Shehab ElDin Avatar answered Sep 18 '22 14:09

Shehab ElDin