Why raising serializers.ValidationError() is causing UnicodeDecodeError?
I am creating a django rest API(with a ImageField) and it is working fine. But I want to add some validations to some CharFields fields. I noticed some unicodeDecoderError while added a validator or simply raising a validation error. Spent quite a lot of time trying to solve it. Any help will be appreciated.
Here is my serializers.py file
from rest_framework import serializers
from .models import *
def validate_phone(phone_number: str):
print(phone_number)
if not (phone_number.startswith(("6", "7", "8", "9"))):
raise serializers.ValidationError(
{"phone": "phone number must startwith digits from 6-9 !!!"})
if not phone_number.isnumeric():
raise serializers.ValidationError(
{"phone": "phone number should contain digits only !!!"})
if len(phone_number) != 10:
raise serializers.ValidationError(
{"phone": "phone number must contain only 10 digits !!!"})
class StudentSerializer(serializers.ModelSerializer):
start_date = serializers.DateField(format='%d %B %Y')
phone = serializers.CharField(max_length=10, validators=[validate_phone])
class Meta:
model = Student
fields = '__all__'
Raising a validation error is resulting a UnicodeDecoderError. Working fine otherwise.
This is my models.py file
from django.db import models
class Student(models.Model):
...
phone = models.CharField(max_length=10)
...
start_date = models.DateField()
profile_picture = models.ImageField(upload_to='profile/', blank=True)
...
I am sending the data using javascript fetch API with FormData() which handles the file formatting and encoding.
Here is the javascript file:
const form = document.querySelector("form");
form.addEventListener("submit", (e) => {
e.preventDefault();
const formdata = new FormData(form);
const json_data = Object.fromEntries(formdata);
console.log(json_data);
const requestOptions = {
method: 'POST',
body: formdata,
};
fetch("http://127.0.0.1:8000/api/join/", requestOptions)
.then((response) => response.json())
.then((result) => console.log(result))
.catch((error) => console.error(error))
Feeling helpless. Without raising a ValidationError it is working fine, I just want to add some validations without any UnicodeDecodeError. I tried to test with postman and the result is same. I do not know how to proceed.
Where am I missing
i think that your problem is here "profile_picture" it's a ImageField, try this in StudentSerializer return profile_picture.url instead profile_picture because profile_picture.url return a string and not a ImageField instance