Как успешно загрузить BLOB-изображения в поле ImageField в django
Я использую django rest framework (версия 3.12.2) для моего backend, и React/Next js в моем front end.
Моя цель довольно проста, я хочу загружать BLOB изображения через POST запрос в django.
но, к сожалению, я получаю это сообщение об ошибке
{"photo_main":["The submitted data was not a file. Check the encoding type on the form."]}
сталкивался ли кто-нибудь с этой проблемой и смог ли ее решить?
модель
class Recipe(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False,
)
author = models.ForeignKey(get_user_model() , on_delete=models.CASCADE, null=True, related_name='author')
photo_main = models.ImageField(upload_to='media/', blank=True)
title = models.CharField(max_length=150)
description = models.TextField(blank=True)
вид
class RecipeCreate(CreateAPIView):
permission_classes = (permissions.IsAuthenticated, )
queryset = Recipe.objects.all()
serializer_class = RecipeCreateSerializer
def perform_create(self, serializer):
'''save the the current logged in user as the author of the recipe'''
serializer.save(author=self.request.user)
действие создания рецепта
export const recipeCreateAction =
({ photoMain, title, description }) =>
async (dispatch) => {
try {
const config = {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Token ${localStorage.getItem('auth_token')}`,
},
};
const body = JSON.stringify({
photo_main: photoMain,
title,
description,
});
await axios.post(endpointRoute().recipes.create, body, config);
dispatch({ type: CREATE_RECIPE_SUCCESS });
} catch {
dispatch({ type: CREATE_RECIPE_FAIL });
}
};
Буду благодарен за любую помощь, которую смогу получить, заранее спасибо
После просмотра форума я наткнулся на решение:
validators.py
import os
from django.core.exceptions import ValidationError
def validate_file_extension(value):
ext = os.path.splitext(value.name)[1] # [0] returns path+filename
valid_extensions = ['.jpg', '.jpeg', '.png', '.svg']
if not ext.lower() in valid_extensions:
raise ValidationError('Unsupported file extension.')
models.py
from django.core.validators import validate_image_file_extension
image = models.ImageField('Image', upload_to=image_upload_path, validators=[validate_file_extension])