Django rest framework unsupported media type with image upload

this is my first time trying to upload image to django rest framework, i am using svelte for my front end and using the fetch api for requests.

i am have an error that i cannot solve. all requests containing images return an unsupported media type error.

Back End

i have added these line to my settings.py

# Actual directory user files go to
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'mediafiles')

# URL used to access the media
MEDIA_URL = '/media/'

my simplified views.py

@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
@parser_classes([FormParser, MultiPartParser])
def products(request):
if request.method == 'POST' and isPermitted(request.user, 'allow_edit_inventory'):
        serializer = ProductSerializer(data=request.data)
        serializer.initial_data['user'] = request.user.pk
        if serializer.is_valid():
            serializer.save()
            return Response({'message': "product added"}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

my urls.py

from django.contrib import admin
from django.urls import path, include
from rest_framework.authtoken import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include("API.urls"))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

and finally my models.py

def product_images_upload_to(instance, filename):
    return 'images/{filename}'.format(filename=filename)
class Product(models.Model):
    name = models.CharField(max_length=200)
    image_url = models.ImageField(upload_to=product_images_upload_to, blank=True, null=True)

Front End

my file upload component in svelte, the exported image variable is what get used in the request in the following code.

  export let avatar, fileinput, image;

    const onFileSelected = (e) => {
        image = e.target.files[0];
        let reader = new FileReader();
        reader.readAsDataURL(image);
        reader.onload = (e) => {
            avatar = e.target.result;
        };
    };

request

export const addProduct = async (product) => {
    const fd = new FormData();
    fd.append("name", product.name);
    fd.append("image_url", product.image_url);

    const response = await fetch(`${URL}/products`, {
        method: "POST",
        headers: {
            "Content-Type": `multipart/form-data boundary=${fd._boundary}`,
            Authorization: `token ${localStorage.getItem("auth")}`
        },
        body: JSON.stringify(product),
    })
    return response
}

was missing a semicolon in the frontend

new front end code:

export const addProduct = async (product) => {
    const fd = new FormData();
    fd.append("name", product.name);
    fd.append("image_url", product.image_url);

    const response = await fetch(`${URL}/products`, {
        method: "POST",
        headers: {
            "Content-Type": `multipart/form-data; boundary=${fd._boundary}`,
            Authorization: `token ${localStorage.getItem("auth")}`
        },
        body: JSON.stringify(product),
    })
    return response
}
Back to Top