Discussion:
The submitted data was not a file. Check the encoding type on the form.
d***@gmail.com
2018-09-17 06:41:05 UTC
Permalink
I am making a student admission system for that i need to upload image
,When iam uploading image my models.py looks like this,

models.py:

def scramble_uploaded_filename(instance, filename):
extension = filename.split(".")[-1]
return "{}.{}".format(uuid.uuid4(), extension)

class StudentAdmission(BaseModel):
student = models.ForeignKey(Student,on_delete=models.CASCADE)
admission_date = models.DateTimeField(auto_now_add=True)
batch = models.IntegerField()
course = models.ForeignKey(Course,on_delete=models.CASCADE)
description = models.CharField(max_length=120)
image = models.ImageField("Uploaded image",
upload_to=scramble_uploaded_filename)


And im using a planeSerializer imageField in serializers.py like this:

serializers.py

class StudentAdmissionBaseSerializer(serializers.Serializer):
user = UserSerializer()
user_detail = UserDetailSerializer()
phone_detail = PhoneSerializer()
address_detail = AddressSerializer()
registration_no = serializers.IntegerField()
batch = serializers.IntegerField()
description = serializers.CharField(default='')
image = serializers.ImageField()

And My views.py looks like this:

views.py:

class StudentAdmissionViewSet(viewsets.ModelViewSet):
queryset = StudentAdmission.objects.all()
serializer_class = StudentAdmissionSerializer
parser_classes = (NestedMultipartParser,)



def get(self, request):
return Response([])
def list(self, request):
return Response([])

def create(self,request):
print({**request.POST,**request.FILES})
serializer = self.get_serializer(data={**request.data,**request.FILES})


if serializer.is_valid():
data = serializer.data
ud = data['user']

user,b = User.objects.get_or_create(
email=ud['email'],
defaults={
'username':ud['email'],
'first_name':ud['first_name'],
'last_name':ud['last_name'],
'gender':ud['gender'],
'type':ud['type']
}
)
if not b:
raise serializers.ValidationError({
'detail':["Email Already Exist"]
})



c = ContentType.objects.get_for_model(user)
Phone.objects.get_or_create(content_type=c,
object_id=user.id,
number=data['phone_detail']['number'],
type=data['phone_detail']['type']
)
Address.objects.get_or_create(
content_type=c,object_id=user.id,
defaults={
'province':data['address_detail']['province'],
'district':data['address_detail']['district'],
'city':data['address_detail']['city'],
'address':data['address_detail']['address']
}
)

detail = data.get('user_detail', False)
if detail:
UserDetail.objects.get_or_create(user_id=user.id,
defaults={
'blood_group':detail.get('blood_group',''),
'nationality':detail.get('nationality',''),
'mother_tongue':detail.get('mother_tongue',''),
'religion':detail.get('religion',''),
'citizenship_no':detail.get('citizenship_no',''),
}
)

student,bval =
Student.objects.get_or_create(user_id=user.id,registration_no=data['registration_no'])

StudentAdmission.objects.get_or_create(student_id=student.id,
defaults={
'batch':data['batch'],
'course_id':data['course'],
'description':data['description'],
'image':data['image']
}
)

return Response(data,status=status.HTTP_201_CREATED)

else:
raise serializers.ValidationError({
'detail':serializer.errors
})


And here i have written a NestedMultipartParser .This is my Own parser
class .The complete code of this parser class looks like This:

from rest_framework import parsers

class NestedMultipartParser(parsers.MultiPartParser):

def parse(self, stream, media_type=None, parser_context=None):

result = super().parse(stream=stream, media_type=media_type,
parser_context=parser_context)

data = {}
print(result.data)
for key, value in result.data.items():
if '.' in key:
dict_key = key.split('.')
nested_dict_key = dict_key[0]
nested_value_key = dict_key[1]

if nested_dict_key not in data:
data[nested_dict_key] = {}

data[nested_dict_key][nested_value_key] = value


# if nested_value_key not in data:
# data[nested_dict_key] = {}
# data[nested_dict_key][nested_value_key] = value
# else:
# data[key] = value
else:
data[key] = value
return parsers.DataAndFiles(data,result.files)



This is the all of code that i have written, When i try to upload image
through form then it raise the error like

"image": [
"The submitted data was not a file. Check the encoding type on the
form."
],


Can Anyone Explain about This type of error?? and please Any developer can
give me solution of it.Thank You!!!!
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Continue reading on narkive:
Loading...