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.
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
I lately start Django and have same problem for upload image.
All steps that i done
1) Install Pillow for using ImageField
pip install Pillow
2) In Settings.py
add these lines
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
3) Use ImageField in model.py (create nameFile
function for create folder and name of file)
def nameFile(instance, filename):
return '/'.join(['images', str(instance.name), filename])
class UploadImageTest(models.Model):
name = models.CharField(max_length=100)
image = models.ImageField(upload_to=nameFile, max_length=254, blank=True, null=True)
4) serializer.py
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = UploadImageTest
fields = ('name', 'image')
5) views.py
class ImageViewSet(ListAPIView):
queryset = UploadImageTest.objects.all()
serializer_class = ImageSerializer
def post(self, request, *args, **kwargs):
file = request.data['file']
image = UploadImageTest.objects.create(image=file)
return HttpResponse(json.dumps({'message': "Uploaded"}), status=200)
6) urls.py: add this line
path('upload/', views.ImageViewSet.as_view(), name='upload'),
7) admin.py: add this line
admin.site.register(UploadImageTest)
8) in terminal
python manage.py makemigrations
python manage.py migrate
来源:https://stackoverflow.com/questions/45564130/django-rest-framework-image-upload