![](/img/trans.png)
[英]Django Rest Framework+React JS ,unable to implement form parser (error: The submitted data was not a file. Check the encoding type on the form.)
[英]Facing ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid') -Django Rest + React
我有一个编辑个人资料页面,用户可以在其中编辑以前输入的信息。 该表单还包含一个图像字段。 我从后端获取数据并用现有数据预填充字段。 现在,图像的数据基本上是图像上传后存储的媒体文件夹的路径。 现在假设用户不想更改之前输入的图像并提交表单我收到以下错误
{'profile_photo': [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]}
如果在 request.data 中未收到图像文件,请向我建议如何控制此错误
下面是代码
视图.py
api_view(['PUT'])
@permission_classes([IsAuthenticated])
@parser_classes([MultiPartParser, FormParser])
def edit_teacher_detail(request):
data = request.data
if data is not None:
id = data.get('id')
queryset = TeacherDetail.objects.get(id = id)
serializer = TeacherDetailSerializer(instance=queryset, data = data)
try:
if serializer.is_valid():
serializer.save()
return Response(status=status.HTTP_200_OK)
else:
print(f'\nThis is the error in the serialization {serializer._errors}\n')
return Response({'message': serializer._errors}, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
print(e)
return Response(status=500)
reactjs API发送数据
export const editTeacherDetail = async (detailsData, photo) => {
let formData = new FormData();
formData.append("id", detailsData.id);
formData.append("is_verified", true);
formData.append("name", detailsData.name.toUpperCase());
formData.append("adhaar_number", detailsData.adhaar_number);
formData.append("phone", detailsData.phone);
formData.append("location", detailsData.location.toUpperCase());
formData.append("full_address", detailsData.full_address.toUpperCase());
formData.append("age", detailsData.age);
formData.append("gender", detailsData.gender.toUpperCase());
formData.append("name_of_school", detailsData.name_of_school.toUpperCase());
formData.append("experience", detailsData.experience);
formData.append("teach_for_no_days", detailsData.teach_for_no_days);
formData.append("subject", detailsData.subject.toUpperCase());
formData.append("teach_class", detailsData.teach_class);
formData.append("home_tuition", detailsData.home_tuition);
formData.append("fees", detailsData.fees);
formData.append("home_tuition_fees", detailsData.home_tuition_fees);
formData.append("shift", detailsData.shift.toUpperCase());
formData.append("board", detailsData.board.toUpperCase());
formData.append("profile_photo", photo.image); // this is the image field
try {
let response = await axiosInstance.put(`/teacher/edit-detail/`, formData);
return response;
} catch (error) {
if (error.response) {
ToastNotification(
"We are facing some problems. Please try again later",
"error"
);
return error.response;
} else {
return error.request;
}
}
};
如果用户没有上传图片,这就是formData.append("profile_photo", photo.image);
/media/photos/2022/05/12/jgs.jpeg
TeacherDetail 模型(更新)
class TeacherDetail(models.Model):
id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
is_verified = models.BooleanField(default=False)
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, blank=True)
name= models.CharField(max_length=100, null=True, blank=True)
profile_photo = models.ImageField(upload_to = 'photos/%Y/%m/%d', null=True, blank=True)
adhaar_number = models.CharField(max_length=200, null=True, blank=True)
phone = models.CharField(max_length=11, null=True, blank=True)
location = models.CharField(max_length=50, null=True, blank=True)
full_address = models.CharField(max_length=500, null=True, blank=True)
age = models.IntegerField( null=True, blank=True)
name_of_school = models.CharField(max_length=200, null=True, blank=True)
experience = models.IntegerField( null=True, blank=True)
teach_for_no_days = models.IntegerField( null=True, blank=True)
shift = models.CharField(max_length=20 ,null=True, blank=True)
subject = models.CharField(max_length=300, null=True, blank=True)
teach_class = models.CharField(max_length=100 ,null=True, blank=True)
board = models.CharField(max_length=25,null=True, blank=True)
gender = models.CharField(max_length=8 ,null=True, blank=True)
fees = models.IntegerField( null=True, blank=True)
fac = models.IntegerField(null=True, blank=True)
home_tuition = models.BooleanField(default=False)
home_tuition_fees = models.IntegerField(null=True, blank=True)
hfac = models.IntegerField(null=True, blank=True)
date_created = models.DateTimeField(default=timezone.now, editable= False)
您可以直接填写表格:
def edit_teacher_detail(request):
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = YourForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
PD:我认为您可以使用 PUT 传递表单
我想出了一种控制发送的方法
formData.append("profile_photo", photo.image);
从前端本身。
我在反应中所做的是检查typeof photo.image是否为字符串。 如果它是一个字符串,这意味着没有文件被上传并且它包含 url 路径,因此,我不会将它附加到 formData 中,否则我会附加它。 下面是我的代码
反应部分
if (typeof photo.image === "string") {
} else {
formData.append("profile_photo", photo.image);
}
我不知道这是否是一种有效的方法。 但目前这对我有用。 请建议是否有人有更好的方法在后端处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.