簡體   English   中英

Facing ErrorDetail(string='提交的數據不是文件。檢查表單上的編碼類型。', code='invalid') -Django Rest + React

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM