Home > Blockchain >  Facing ErrorDetail(string='The submitted data was not a file. Check the encoding type on the fo
Facing ErrorDetail(string='The submitted data was not a file. Check the encoding type on the fo

Time:05-13

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

Below are the codes

views.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

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);

/media/photos/2022/05/12/jgs.jpeg

TeacherDetail Model (Update)

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)

CodePudding user response:

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

CodePudding user response:

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. 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. 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.

  • Related