[英]Facing ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid') -Django Rest + React
I have an Edit Profile page where a user can edit the previously entered information.我有一个编辑个人资料页面,用户可以在其中编辑以前输入的信息。 The form also contains an image field.
该表单还包含一个图像字段。 I fetch the data from the backend and prefill the fields with the existing data.
我从后端获取数据并用现有数据预填充字段。 Now the data that comes for the image is basically the path to the media folder where the image gets stored once uploaded.
现在,图像的数据基本上是图像上传后存储的媒体文件夹的路径。 Now suppose the user does not want to change the previously entered image and submits the form I get the below error
现在假设用户不想更改之前输入的图像并提交表单我收到以下错误
{'profile_photo': [ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid')]}
Please suggest to me what should I do to control this error if an image file is not received in the request.data如果在 request.data 中未收到图像文件,请向我建议如何控制此错误
Below are the codes下面是代码
views.py视图.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 sending the data 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;
}
}
};
if no image is uploaded the by the user this is what is passed in formData.append("profile_photo", photo.image);如果用户没有上传图片,这就是formData.append("profile_photo", photo.image);
/media/photos/2022/05/12/jgs.jpeg
TeacherDetail Model (Update) 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)
You can take the form directly:您可以直接填写表格:
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: I think you can pass a form using PUT PD:我认为您可以使用 PUT 传递表单
I figured out a way to control sending of我想出了一种控制发送的方法
formData.append("profile_photo", photo.image);
from the frontend itself.从前端本身。
What I did in the react is check whether the typeof photo.image is string or not.我在反应中所做的是检查typeof photo.image是否为字符串。 If it is a string this means that no file has been uploaded and it contains the url path, therefore, I do not append it in the formData else I append it.
如果它是一个字符串,这意味着没有文件被上传并且它包含 url 路径,因此,我不会将它附加到 formData 中,否则我会附加它。 Below is my code
下面是我的代码
react part反应部分
if (typeof photo.image === "string") {
} else {
formData.append("profile_photo", photo.image);
}
I do not know if this is an efficient way to do it.我不知道这是否是一种有效的方法。 But for the time being this works for me.
但目前这对我有用。 Please suggest if anyone has a better way to handle it in the backend.
请建议是否有人有更好的方法在后端处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.